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: When a faster python? There was the Unladen Swallow project that aims to get a faster python, but it seems to be stopped : Is there a way to get a faster python, I mean faster than C-Python, without the use of psyco ? A: You could write hot code paths in Cython, Pyrex or Shedskin. That would have the positive si...
When a faster python?
There was the Unladen Swallow project that aims to get a faster python, but it seems to be stopped : Is there a way to get a faster python, I mean faster than C-Python, without the use of psyco ?
[ "You could write hot code paths in Cython, Pyrex or Shedskin. That would have the positive side effect of forcing you to benchmark your code to find the hot paths in the first place, which in turn could lead to the (not implausible) revelation that Python performance may not be the actual bottleneck in your code. \...
[ 4, 3, 3, 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0004132493_performance_python.txt
Q: Python datetime not including DST when using pytz timezone If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this? >>> # Modified for readability >>> import pytz >>> import datetime >>> s...
Python datetime not including DST when using pytz timezone
If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this? >>> # Modified for readability >>> import pytz >>> import datetime >>> sweden = pytz.timezone('Europe/Stockholm') >>> >>> datetime.datet...
[ "The sweden object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.\nIn the first example, you create a datetime object and convert it to local time. The sweden object knows that the UTC time you passed occurs during daylight savings time and can convert it ...
[ 13, 0 ]
[]
[]
[ "datetime", "python", "pytz", "timezone", "utc" ]
stackoverflow_0002659908_datetime_python_pytz_timezone_utc.txt
Q: Python import trouble I am having some trouble importing a class from a particular module. The class is in the module my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 This code works import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 which means to acce...
Python import trouble
I am having some trouble importing a class from a particular module. The class is in the module my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 This code works import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 which means to access my class I have to do my...
[ "Looks like a circular import.\nGordon McMillan says:\nCircular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet availa...
[ 3, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0004135207_import_python.txt
Q: Facebook Events and timezones, how to convert UTC datetime to what facebook expects? My application needs to create facebook events. Everything works fine, but I can't get the timezones correct. The start/end dates are all wrong. Facebook's Event API docs say this: Note: The start_time and end_time are the times ...
Facebook Events and timezones, how to convert UTC datetime to what facebook expects?
My application needs to create facebook events. Everything works fine, but I can't get the timezones correct. The start/end dates are all wrong. Facebook's Event API docs say this: Note: The start_time and end_time are the times that were input by the event creator, converted to UTC after assuming that they were in Pa...
[ "It means that if the user enters \"12 am\" you're supposed to assume its \"12 am pacific time\", convert that to UTC so its \"8 am GMT\" and turn that into a unix epoch.\nYou can do it like this:\nimport datetime, calendar\n\ndate_local = datetime.datetime.now() # some date in some timezone\ndate_utc = date_local....
[ 2, 1 ]
[]
[]
[ "datetime", "facebook", "python", "timezone" ]
stackoverflow_0004134718_datetime_facebook_python_timezone.txt
Q: Proper way to construct MySQL queries in python? After starting with python last week after coming from php I am wondering what is the best way to build a MySQL query. I am using Python's MySQLdb module. After doing some research it seems the best way is something similar to the following code below: def upda...
Proper way to construct MySQL queries in python?
After starting with python last week after coming from php I am wondering what is the best way to build a MySQL query. I am using Python's MySQLdb module. After doing some research it seems the best way is something similar to the following code below: def updateEmployee(employee): try: cursor = db.cursor(...
[ "You don't need backquotes in your query. Mistake is here `posOrg`:%s\nSET `employeeID`=%s, `parentNameN`=%s, `firstName`=%s, `lastName`=%s,\n `title`=%s, `room`=%s, `locCode`=%s, **`posOrg`:%s**\n\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004135683_mysql_python.txt
Q: In asyncore how can i send data to all or some of the clients? I'm building a little MMORPG and im trying to use asyncore rather then threading. 1) How would i send data to certain clients, because in threading a saved each clients socket and current in a dictionary a with its unique id as a key. So how could i su...
In asyncore how can i send data to all or some of the clients?
I'm building a little MMORPG and im trying to use asyncore rather then threading. 1) How would i send data to certain clients, because in threading a saved each clients socket and current in a dictionary a with its unique id as a key. So how could i subjective send data to all the clients. Thankyou, please say if i did...
[ "I find it great that you want to move to asynchronous programming instead of threading, since it is so much reliable and easier to debug. \nHowever, asyncore is a bad library to do so. I don't advise you use it at all, since it requires a significant rewrite to do simple things like read standard io.\nI suggest yo...
[ 1 ]
[]
[]
[ "asyncore", "python", "sockets" ]
stackoverflow_0004135793_asyncore_python_sockets.txt
Q: How do I write a string equation solver in python? Thanks in advance! I am writing a program to check if a is true and then return True or False. I need to split it up at the equal sign and then check if the 1st item in the list is equal to the second item and vise-versa. Here is what I have so far: def s_equatio...
How do I write a string equation solver in python?
Thanks in advance! I am writing a program to check if a is true and then return True or False. I need to split it up at the equal sign and then check if the 1st item in the list is equal to the second item and vise-versa. Here is what I have so far: def s_equation(a): equal=a.split("=")
[ "left, right = a.split(\"=\")\nassert left == right\n\n\nYou're gonna need to give us more details than that if you want a useful answer. Are you trying to write a full computer algebra system (like e.g. Mathematica)? That's a biiiiig project and has already been done several times. Consider using something like Sa...
[ 4, 3, 0 ]
[]
[]
[ "algebra", "equation", "python", "solver" ]
stackoverflow_0004135105_algebra_equation_python_solver.txt
Q: HDF5 internal data organization and NumPy usage as hdf5 documentation says, HDF5 stores data using NumPy "It is built on top of the HDF5 library, the Python language and the NumPy package. It features an object-oriented interface that, combined with C extensions for the performance-critical parts of the code, make...
HDF5 internal data organization and NumPy usage
as hdf5 documentation says, HDF5 stores data using NumPy "It is built on top of the HDF5 library, the Python language and the NumPy package. It features an object-oriented interface that, combined with C extensions for the performance-critical parts of the code, makes it a fast yet extremely easy-to-use tool for intera...
[ "HDF5 is a C language library. HDF5 stores numbers, including floats, in a platform independent manner (scroll down to the table titled \"Examples of Native Datatypes and Corresponding C Types,\" there's more information in the Users Guide).\nPyTables simply converts from the HDF5 datatype to a NumPy datatype. An...
[ 1 ]
[]
[]
[ "hdf5", "numpy", "pytables", "python" ]
stackoverflow_0004135293_hdf5_numpy_pytables_python.txt
Q: Poisson simulation not working as expected? I have a simple script to set up a Poisson distribution by constructing an array of "events" of probability = 0.1, and then counting the number of successes in each group of 10. It almost works, but the distribution is not quite right (P(0) should equal P(1), but is ins...
Poisson simulation not working as expected?
I have a simple script to set up a Poisson distribution by constructing an array of "events" of probability = 0.1, and then counting the number of successes in each group of 10. It almost works, but the distribution is not quite right (P(0) should equal P(1), but is instead about 90% of P(1)). It's like there's an of...
[ "I did a combinatorial reality check on your math, and it looks like your results are correct actually. P(0) should not be roughly equivalent to P(1)\n.9^10 = 0.34867844 = probability of 0 events\n.1 * .9^9 * (10 choose 1) = .1 * .9^9 * 10 = 0.387420489 = probability of 1 event\n\nI wonder if you accidentally did y...
[ 1 ]
[]
[]
[ "poisson", "python" ]
stackoverflow_0004135837_poisson_python.txt
Q: Twisted daemon unittest I've started a client/server project at work using Twisted (I'm a newcomer, so not much experience). I probably did setup things the wrong way/order, because now I'm a little stuck with a Daemon server (using twistd --python to launch it). I'm wondering if I've to re-implement the server a...
Twisted daemon unittest
I've started a client/server project at work using Twisted (I'm a newcomer, so not much experience). I probably did setup things the wrong way/order, because now I'm a little stuck with a Daemon server (using twistd --python to launch it). I'm wondering if I've to re-implement the server as a standard process to use i...
[ "\nIs it ok to have a daemon implementation for production and standard process for unittest?\n\nYour unit test isn't for Twisted's daemonization functionality. It's for the custom application/protocol/server/whatever functionality that you implemented. In general, in a unit test, you want to involve as little co...
[ 0 ]
[]
[]
[ "daemon", "python", "twisted" ]
stackoverflow_0004136096_daemon_python_twisted.txt
Q: recursive method returning original value So I'm trying to learn python on my own, and am doing coding puzzles. I came across one that pretty much ask for the best position to stand in line to win a contest. The person running the contest gets rid of people standing in odd number positions. So for example if 1, 2,...
recursive method returning original value
So I'm trying to learn python on my own, and am doing coding puzzles. I came across one that pretty much ask for the best position to stand in line to win a contest. The person running the contest gets rid of people standing in odd number positions. So for example if 1, 2, 3, 4, 5 It would get rid of the odd positions ...
[ "You must return the value from the recurse function to the caller function:\nreturn findWinner(remainingContestants)\n\nelse you would return just the original value without any changes.\ndef findWinner(contestants):\n if (len(contestants) != 1):\n remainingContestants = []\n for i, contestant in ...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0004136193_python_recursion.txt
Q: Pros and cons of using sqlite3 vs custom table implementation I noticed that a significant part of my (pure Python) code deals with tables. Of course, I have class Table which supports the basic functionality, but I end up adding more and more features to it, such as queries, validation, sorting, indexing, etc. I ...
Pros and cons of using sqlite3 vs custom table implementation
I noticed that a significant part of my (pure Python) code deals with tables. Of course, I have class Table which supports the basic functionality, but I end up adding more and more features to it, such as queries, validation, sorting, indexing, etc. I to wonder if it's a good idea to remove my class Table, and refacto...
[ "SQLite does not run in a separate process. So you don't actually have any extra overhead from IPC. But IPC overhead isn't that big, anyway, especially over e.g., UNIX sockets. If you need multiple writers (more than one process/thread writing to the database simultaneously), the locking overhead is probably worse,...
[ 5, 4, 0 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0004136800_performance_python_sqlite.txt
Q: Define variables in template based on user being staff or not I'm trying to display an HTML table of values with about 20 columns where say staff users see one subset of columns, and non-staff users see another subset of columns. I may want to define further types of users later. Now right now I have three stat...
Define variables in template based on user being staff or not
I'm trying to display an HTML table of values with about 20 columns where say staff users see one subset of columns, and non-staff users see another subset of columns. I may want to define further types of users later. Now right now I have three static header rows so the template looks like <table> <tr> <th>Col A<...
[ "This depends a lot on what view you have and templates.\nWays to do:\n\nmake a public template and staff template and add a simple method to change the templates on the fly for the views.\nmake a template tag:\n{% is_staff myvar %}\n\ntag code:\nclass IsStaffNode(Node):\n def __init__(self, var):\n self....
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004136785_django_django_templates_python.txt
Q: How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics? I have written the turtle graphics functions that define the fourteen segments, and the functions that assemble these segments to form characters, e.g. def MethodA (width) : top_stroke(wi...
How to write a python program that read the input and convert it to pre-defined 14-segments characters with turtle graphics?
I have written the turtle graphics functions that define the fourteen segments, and the functions that assemble these segments to form characters, e.g. def MethodA (width) : top_stroke(width) middle_stroke(width) left_stroke right_stroke(width) I have all the definitions ready, but how do I let pytho...
[ "You could define a dictionary with function references like this:\nCharacters = {\n 'A': MethodA,\n 'B': MethodB,\n # ...\n}\n\nThen, for a string s:\ns = \"Pizza\"\nfor c in s:\n c = c.upper() # to fold lowercase into upper case\n if c in Characters:\n Characters[c](width)\n\nThis code works...
[ 1 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0004137040_python_turtle_graphics.txt
Q: Grouping a queryset by another related model I have two models: class Stop(models.Model): line = models.ForeignKey(TransitLine, related_name='stops') name = models.CharField(max_length=32) approved_ts = models.DateTimeField(null=True, blank=True) class TransitLine(models.Model): name = models.Char...
Grouping a queryset by another related model
I have two models: class Stop(models.Model): line = models.ForeignKey(TransitLine, related_name='stops') name = models.CharField(max_length=32) approved_ts = models.DateTimeField(null=True, blank=True) class TransitLine(models.Model): name = models.CharField(max_length=32) desc = models.CharField(m...
[ "In the template, you can use regroup ...\nYou must order them by TransitLine, while you filter the queryset using\nStop.objects.filter(approved_ts__isnull=False).order_by('line')\n\nYou can check the documentation...\n", "If I understand correctly, you should really just give the template a queryset of Translit...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0004130880_django_django_queryset_python.txt
Q: Can not install hcluster from pypi under python 2.6 on xp I am using the setup.py file supplied with hcluster with the following lines added: sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0") sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0\\hcluster...
Can not install hcluster from pypi under python 2.6 on xp
I am using the setup.py file supplied with hcluster with the following lines added: sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0") sys.path.append("c:\\Program Files\\Python26\\Lib\\site-packages\\hcluster-0.2.0\\hcluster") Then used setup.py as follows: "c:\program files\python26\...
[ "\nYou don't need to add packages in site-packages in sys.path. \nDid you copy the hcluster in site-package manually? It is not the correct way to do it.\n2.1 You should have the hcluster outside the site-packages say in your home directory and then run \"python setup.py install\"\n2.2 This will put the package aft...
[ 1 ]
[]
[]
[ "hcluster", "python" ]
stackoverflow_0004137159_hcluster_python.txt
Q: Python & wxPython - Code Critique - Short Hand / Convenience / Repetition I'd actually like to start by admitting that I'm terrified to ask this question. That said, I have the following combination of classes: A Dialog Class: class formDialog(wx.Dialog): def __init__(self, parent, id = -1, panel = None, title ...
Python & wxPython - Code Critique - Short Hand / Convenience / Repetition
I'd actually like to start by admitting that I'm terrified to ask this question. That said, I have the following combination of classes: A Dialog Class: class formDialog(wx.Dialog): def __init__(self, parent, id = -1, panel = None, title = _("Unnamed Dialog"), modal = False, sizes = (400, -1)): wx...
[ "You should also try wxFormDesigner or XRCed.\n", "Since you're using wx, you should study wxglade. It's a graphical GUI builder which you use to build your GUI and it generates a .wxg file with the layout, and you can load that into your script.\nThe file is actually just xml, so you can programatically generate...
[ 2, 0 ]
[]
[]
[ "automation", "layout", "python", "repeat", "wxpython" ]
stackoverflow_0004135829_automation_layout_python_repeat_wxpython.txt
Q: Python pickle seems to break inside class, but not in command line script I've been trying to unpickle some dictionaries from the database. I've reverted to using the marshal module, but was still wondering why pickle is having such a difficult time unserializing some data. Here is a command line python session sh...
Python pickle seems to break inside class, but not in command line script
I've been trying to unpickle some dictionaries from the database. I've reverted to using the marshal module, but was still wondering why pickle is having such a difficult time unserializing some data. Here is a command line python session showing essentially what I am trying to do: >>> a = {'service': 'amazon', 'proto...
[ "Your code works. How are you testing it?\nimport logging\nimport base64\nimport pickle\nclass Resource:\n @staticmethod\n def resource_factory(resource_data):\n resource_data = \"KGRwMApTJ3Byb3RvY29sJwpwMQpTJ3N0cmVhbScKcDIKc1Mna2V5JwpwMwpTJ2xhamRmb2F1MDk0MjRqb2pmLmZsdicKcDQKc1Mnc2VydmljZScKcDUKUydhbWF...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "pickle", "python", "serialization" ]
stackoverflow_0004135615_django_django_models_pickle_python_serialization.txt
Q: Python regex non-capturing issue? I was trying to get all quoted (" or ') substrings from a string excluding the quotation marks. I came up with this: "((?:').*[^'](?:'))|((?:\").*[^\"](?:\"))" For some reason the matching string still contains the quotation marks in it. Any reason why ? Sincerely, nikita.utiu. ...
Python regex non-capturing issue?
I was trying to get all quoted (" or ') substrings from a string excluding the quotation marks. I came up with this: "((?:').*[^'](?:'))|((?:\").*[^\"](?:\"))" For some reason the matching string still contains the quotation marks in it. Any reason why ? Sincerely, nikita.utiu.
[ "You could do it with lookahead and lookbehind assertions:\n>>> match = re.search(r\"(?<=').*?(?=')\", \"a 'quoted' string. 'second' quote\")\n>>> print match.group(0)\nquoted\n\n", "Using non-capturing groups doesn’t mean that they are not captured at all. They just don’t create separate capturing groups like no...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004136987_python_regex.txt
Q: Setting the value of a model field based on user authentication in Django I'm trying to selectively process a field in my Django/Python application based on whether a user is logged in or not. Basically, I have a model similar to the following: class Resource(models.Model): uploaded = models.DateTimeField() ...
Setting the value of a model field based on user authentication in Django
I'm trying to selectively process a field in my Django/Python application based on whether a user is logged in or not. Basically, I have a model similar to the following: class Resource(models.Model): uploaded = models.DateTimeField() name = models.CharField(max_length=200) description = models.CharField(ma...
[ "Your best bet is to create a function used to access the file attribute, and check there. In general, it would possible to turn the attribute into a descriptor which does it implicitly, but Django's metaclass magic would impede that.\nIn general however, Django is designed to handle authentication at the view-lev...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_sessions", "python" ]
stackoverflow_0004092821_django_django_models_django_sessions_python.txt
Q: Recommendations for a Python library that can capture still images from a Flash/HTML5 video? Part of a web application I am developing requires the ability to capture still images from a Flash or HTML5 video playing with in a browser. Is there a Python library out there that could help me along with this task? UP...
Recommendations for a Python library that can capture still images from a Flash/HTML5 video?
Part of a web application I am developing requires the ability to capture still images from a Flash or HTML5 video playing with in a browser. Is there a Python library out there that could help me along with this task? UPDATE Actually, users of this web app will also have to have the ability to Draw a crop box on to...
[ "What about capturing it inside Flash and sending it as BiteArray to the server?\n", "If you know Python, http://pyjs.org could be useful.\nEDIT\nI just saw there's \"Python\" written on the title, so you obviously know Python. My bad, i'm overtired.\n" ]
[ 1, 0 ]
[]
[]
[ "flash", "html5_video", "image_capture", "python", "screen_capture" ]
stackoverflow_0004129858_flash_html5_video_image_capture_python_screen_capture.txt
Q: Redirect method call and pass caller along automatically I'm building a modular app and I wanted all Objects of a certain type to be able to call a management object, and automatically have their own instance passed along. Scenario: My application consists of a framework and plugins that are being loaded at runtim...
Redirect method call and pass caller along automatically
I'm building a modular app and I wanted all Objects of a certain type to be able to call a management object, and automatically have their own instance passed along. Scenario: My application consists of a framework and plugins that are being loaded at runtime. One of these plugins provides functionality that operates i...
[ "If all you're doing is accessing attributes, use a descriptor. It appears that you're implementing a descriptor-like design and calling it a \"Wrapper\". A descriptor will probably be slightly simpler and more consistent with all the other places in Python that use descriptors.\nhttp://docs.python.org/reference/...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004136972_python.txt
Q: Context processors, passing a session which doesn't exist Hay All, I've got a simple context processor which looks within a session and if a 'user' key exists. If it does i want to return it to the template. Here's my context Processor def get_user_details(request): user = request.session['user'] data = { ...
Context processors, passing a session which doesn't exist
Hay All, I've got a simple context processor which looks within a session and if a 'user' key exists. If it does i want to return it to the template. Here's my context Processor def get_user_details(request): user = request.session['user'] data = { 'user':user } return data and here is a sample...
[ "You can get a default value like None this way: request.session.get('user', None). Just like in normal Python dicts.\n", "user = request.session.get('user', None)\n\nor,\nuser = None\nif 'user' in request.session:\n user = request.session['user']\n\n", "def get_user_details(request):\n try:\n user...
[ 3, 3, 0 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0004138088_django_python_session.txt
Q: How to check if a file is open for writing on windows in python? We have a process here at work where an input file is created by SAS. That input file is then read by a legacy application and that legacy application creates results. SAS then reads the results and summarizes them. A non-programmer usually takes ...
How to check if a file is open for writing on windows in python?
We have a process here at work where an input file is created by SAS. That input file is then read by a legacy application and that legacy application creates results. SAS then reads the results and summarizes them. A non-programmer usually takes care of these actions one by one. So the person just creates the inpu...
[ "Write output to a temp file. When done writing, close it, then rename it to the name the other program is waiting for. That way, the file only appears when it is ready to be read.\n", "\nif there is a way, in python, to tell if a file on a network drive is open for writing by any application on any computer?\n...
[ 2, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004138015_python_windows.txt
Q: python - simplejson not serializing when i try to serialize the list variable returned by the database query, an error of 'non-serializable is returned. But when i hardcode the same exact string in, or so it seems...serialization works. Any ideas why? car_list = Car.objects.get(id=query).all_cars.values('id','na...
python - simplejson not serializing
when i try to serialize the list variable returned by the database query, an error of 'non-serializable is returned. But when i hardcode the same exact string in, or so it seems...serialization works. Any ideas why? car_list = Car.objects.get(id=query).all_cars.values('id','name').order_by('name') #car_list = [{'id':...
[ "simplejson cannot serialize Django types. Pass the result to list() to turn it into something simplejson can serialize.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004138296_python.txt
Q: Copied python egg no longer works I needed to make a change to a 3rd party library, so I edited the files in the egg (which is not zipped). The egg lives in site-packages in a virtualenv. Everything works fine on my dev machine, but when I copied the egg to another machine, the module can longer be found to import...
Copied python egg no longer works
I needed to make a change to a 3rd party library, so I edited the files in the egg (which is not zipped). The egg lives in site-packages in a virtualenv. Everything works fine on my dev machine, but when I copied the egg to another machine, the module can longer be found to import. I'm sure I went about this the wrong ...
[ "A quick fix to your problem should be by adding the full path of the egg to a .pth file which should exist in the sys-path (in your case site-packages).\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004137917_python.txt
Q: exchanging data through pipes between C# and cPython I have what (I think) is a relatively simple task. I have to provide to some C# app a way to invoke my Python app and pass some data for processing and receive back the results at the end of the Python task (both are GUI apps. I thought that pipes would do the j...
exchanging data through pipes between C# and cPython
I have what (I think) is a relatively simple task. I have to provide to some C# app a way to invoke my Python app and pass some data for processing and receive back the results at the end of the Python task (both are GUI apps. I thought that pipes would do the job nicely with the C# side creating a named pipe thus ...
[ "CallNamedPipe requires a pipe that is created in PIPE_TYPE_MESSAGE; your C# code creates a pipe in PIPE_TYPE_BYTE. So you either need to create a pipe in message mode in C# (using a constructor that expects PipeTransmissionMode), or use WriteFile to put data into the pipe.\n" ]
[ 1 ]
[]
[]
[ "c#", "ipc", "pipe", "python" ]
stackoverflow_0004138124_c#_ipc_pipe_python.txt
Q: Why does mechanize list one form? If you run the following program: import mechanize br = mechanize.Browser() br.open("http://hansardindex.ontla.on.ca/hansarde.asp") for f in br.forms(): print f.name Only one line of output is printed. However if you visit the page there are many forms with names such as "D...
Why does mechanize list one form?
If you run the following program: import mechanize br = mechanize.Browser() br.open("http://hansardindex.ontla.on.ca/hansarde.asp") for f in br.forms(): print f.name Only one line of output is printed. However if you visit the page there are many forms with names such as "DateFrom". Why does mechanize not list t...
[ "There is a difference between 'Forms' and 'Input'. A form can contain many input fields.\nsee http://www.w3schools.com/html/html_forms.asp\nMechanize is right there is only ONE form but with multiple input fields.\nWhat you probably want to do is access the input fields by name. So for example setting the 'searchc...
[ 3 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0004138522_mechanize_python.txt
Q: One-to-many relationships in Django I'm trying to create a One-to-many relationship in Django. In my example, I have a news post, which may have several images associated with it. However, different news posts will never share images. As far as I can see, there are two ways to do this: Through a ManyToManyField, ...
One-to-many relationships in Django
I'm trying to create a One-to-many relationship in Django. In my example, I have a news post, which may have several images associated with it. However, different news posts will never share images. As far as I can see, there are two ways to do this: Through a ManyToManyField, which creates a multi-select tool in the ...
[ "The second part is the easier one:\nYou want the horizontal javascript filter\nIf you go with a ManyToManyField, you could filter those choices by using a Custom Manager. \nIf you use a ForeignKey, you would want to use one of the Admin Inlines. If you really never re-use images, use the inlines. \n" ]
[ 3 ]
[]
[]
[ "django", "one_to_many", "python" ]
stackoverflow_0004138833_django_one_to_many_python.txt
Q: Is there a python unit test framework that gives compact error output when comparing strings Using the Java JUnit framework and comparing the strings "abcde" and "abde" you would get the error output 'expected:<...b[c]d...> but was: <...b[]d...>' Using python unittest I get "abcde" != "abde" which is not all as us...
Is there a python unit test framework that gives compact error output when comparing strings
Using the Java JUnit framework and comparing the strings "abcde" and "abde" you would get the error output 'expected:<...b[c]d...> but was: <...b[]d...>' Using python unittest I get "abcde" != "abde" which is not all as useful if you are dealing with long strings. So my question is: Is there a python unit test framewor...
[ "The unittest2 package is a backport (to Python >= 2.4) of features that are native to the PyUnit (unittest) framework in Python 2.7.\nIt includes enhanced string comparison features.\n\nhttp://www.voidspace.org.uk/python/articles/unittest2.shtml#unicode-string-comparison\n" ]
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0004138662_python_unit_testing.txt
Q: Simple Python server How can I start a simple python server that will allow me to connect to sockets from some outer source ? I've tried : import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] ...
Simple Python server
How can I start a simple python server that will allow me to connect to sockets from some outer source ? I've tried : import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request[0].strip() socket = self.request[1] print "%s wrote:" % self.c...
[ "The simplest solution is SocketServer, which is part of the Python standard library.\n" ]
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004139140_python_sockets.txt
Q: Python: best way to serve multiple users? I have a (game) server that I am writing in python (3.1), and have a few questions on that. The client program uses the socket module to connect to the server. Multiple people may be connecting at any time, and I need a way to handle that. Would the best way be to employ t...
Python: best way to serve multiple users?
I have a (game) server that I am writing in python (3.1), and have a few questions on that. The client program uses the socket module to connect to the server. Multiple people may be connecting at any time, and I need a way to handle that. Would the best way be to employ the multi/sub processing module, and start a new...
[ "Don't reinvent the wheel use Twisted.\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004139345_multithreading_python.txt
Q: How to call python functions when running from terminal Say i have code that does something complicated and prints the result, but for the purposes of this post say it just does this: class tagFinder: def descendants(context, tag): print context print tag But say i have multiple functions in t...
How to call python functions when running from terminal
Say i have code that does something complicated and prints the result, but for the purposes of this post say it just does this: class tagFinder: def descendants(context, tag): print context print tag But say i have multiple functions in this class. How can i run this function? Or even when say i do...
[ "~ python\nPython 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) \n[GCC 4.4.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import filename\n>>> a = tagFinder()\n>>> a.descendants(arg1, arg2)\n # output\n\n", "This will throw an error\n>>> class tagFinder:\n... def...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004139436_python.txt
Q: Trouble installing MySQLdb for second version of Python The context: I'm working on some Python scripts on an Ubuntu server. I need to use some code written in Python 2.7 but our server has Python 2.5. We installed 2.7 as a second instance of Python so we wouldn't break anything reliant on 2.5. Now I need to insta...
Trouble installing MySQLdb for second version of Python
The context: I'm working on some Python scripts on an Ubuntu server. I need to use some code written in Python 2.7 but our server has Python 2.5. We installed 2.7 as a second instance of Python so we wouldn't break anything reliant on 2.5. Now I need to install the MySQLdb package. I assume I can't do this the easy way...
[ "As far as I'm aware, there is a very significant difference between \"mysql_config\" and \"my.cnf\".\n\n\"mysql_config\" is usually located in the \"bin\" folder of your MySQL install and when executed, spits out various filesystem location information about your install.\n\"my.cnf\" is a configuration script used...
[ 2, 0 ]
[]
[]
[ "configuration_files", "mysql", "permissions", "python" ]
stackoverflow_0004138504_configuration_files_mysql_permissions_python.txt
Q: Using a custom collection extending from a dict() with SqlAlchemy I'm trying to use a custom collection to "connect" (or relate) two classes but I haven't been able to do it. Maybe I got the whole concept of the SqlAlchemy custom collections wrong, but let me explain what I am doing (and see if someone can give me...
Using a custom collection extending from a dict() with SqlAlchemy
I'm trying to use a custom collection to "connect" (or relate) two classes but I haven't been able to do it. Maybe I got the whole concept of the SqlAlchemy custom collections wrong, but let me explain what I am doing (and see if someone can give me a hint, or something) I have a Parent class (which some of you will re...
[ "Got it. \nI had also asked the same question in the SqlAlchemy google group and I just got an answer.\nhttp://groups.google.com/group/sqlalchemy/msg/5c8fc09a75fd4fa7\nQuote:\n\nSo this is incorrect -\n collection_class takes a class or\n other callable as an argument that\n will produce an instance of your\n c...
[ 2 ]
[]
[]
[ "collections", "inheritance", "python", "sqlalchemy" ]
stackoverflow_0004135315_collections_inheritance_python_sqlalchemy.txt
Q: How to create Unix and Linux binaries from Python code Anybody know how this can be done? I took a look at cx_Freeze, but it seems that it doesn't compile everything necessary into one binary (i.e., the python builtins aren't present). A: The standard freeze tool (from Tools/freeze) can be used to make fully-st...
How to create Unix and Linux binaries from Python code
Anybody know how this can be done? I took a look at cx_Freeze, but it seems that it doesn't compile everything necessary into one binary (i.e., the python builtins aren't present).
[ "The standard freeze tool (from Tools/freeze) can be used to make fully-standalone binaries on Unix, including all extension modules and builtins (and omitting anything that is not directly or indirectly imported).\n" ]
[ 4 ]
[]
[]
[ "cross_compiling", "linux", "python", "unix" ]
stackoverflow_0004138886_cross_compiling_linux_python_unix.txt
Q: Python tips for memory optimization I need to optimize the RAM usage of my application. PLEASE spare me the lectures telling me I shouldn't care about memory when coding Python. I have a memory problem because I use very large default-dictionaries (yes, I also want to be fast). My current memory consumption is 350...
Python tips for memory optimization
I need to optimize the RAM usage of my application. PLEASE spare me the lectures telling me I shouldn't care about memory when coding Python. I have a memory problem because I use very large default-dictionaries (yes, I also want to be fast). My current memory consumption is 350MB and growing. I already cannot use shar...
[ "I suggest the following: store all the values in a DB, and keep an in-memory dictionary with string hashes as keys. If a collision occurs, fetch values from the DB, otherwise (vast majority of the cases) use the dictionary. Effectively, it will be a giant cache.\nA problem with dictionaries in Python is that the...
[ 13, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "memory_management", "optimization", "python" ]
stackoverflow_0003021264_memory_management_optimization_python.txt
Q: C++ Allocated Memory Problem It has been a long time since I have programmed in C++, but I recently wrote a little C++ function and am having a little bit of trouble. The function returns a struct, Result, that have some strings in it. I thought I allocated memory for the strings, but jsonResult is sometimes parti...
C++ Allocated Memory Problem
It has been a long time since I have programmed in C++, but I recently wrote a little C++ function and am having a little bit of trouble. The function returns a struct, Result, that have some strings in it. I thought I allocated memory for the strings, but jsonResult is sometimes partially overwritten. //The struct...
[ "Use std::string. You won't regret it.\n", "I'd put money on your problem being in here:\njsonResult = interp.ResultData().Print(SI_FORMAT_ECMA);\n\nWho 'owns' the char* array returned by Print()? Maybe it's attempting to return a pointer to memory that's out of scope???\nexample:\n char* badFunction(void)\n {\...
[ 4, 1, 0 ]
[]
[]
[ "c++", "ctypes", "memory_management", "python" ]
stackoverflow_0004139576_c++_ctypes_memory_management_python.txt
Q: Python server for hosting sockets and reading data I'm trying to create a python server that will serve calls from outer source through sockets. So I've skimmed through the docs and copied this code, I can connect but no sent data is shown. What am I doing wrong ? import SocketServer class MyUDPHandler(SocketServ...
Python server for hosting sockets and reading data
I'm trying to create a python server that will serve calls from outer source through sockets. So I've skimmed through the docs and copied this code, I can connect but no sent data is shown. What am I doing wrong ? import SocketServer class MyUDPHandler(SocketServer.BaseRequestHandler): def handle(self): se...
[ "you problem might lie in that server.serve_forever() never returns, it will block your code and nothing beyond it will run.\nyou might have this work better by splitting this across threads:\nimport threading\ndef launch_server():\n server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)\n print(\"workin...
[ 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0004139735_python_sockets.txt
Q: Multiple urllib2 connections I want to download multiple images at the same time. For that I'm using threads, each one downloading an image, using urllib2 module. My problem is that even if threads starts (almost) simultaneously, the images are downloaded one by one, like in a single-threaded environment. Here is ...
Multiple urllib2 connections
I want to download multiple images at the same time. For that I'm using threads, each one downloading an image, using urllib2 module. My problem is that even if threads starts (almost) simultaneously, the images are downloaded one by one, like in a single-threaded environment. Here is the threaded function: def updateI...
[ "Consider using urllib3. It supports connection pooling and multiple concurrent requests via processes (not threads). It should solve this problem. Be careful to garbage collect connection pools if you contact many different sites, since each site gets its own pool.\n", "In my experience, multithreads of CPython ...
[ 3, 0 ]
[]
[]
[ "multithreading", "python", "urllib2" ]
stackoverflow_0004139988_multithreading_python_urllib2.txt
Q: How to implement server & multi-clients "communication"? What I aim to do is to fulfill a mutual communication between one server but multiple clients. Here is the Server part I wrote: Import subprocess, time, socket, fileinput s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host='' port = 2000 s.bind((host,...
How to implement server & multi-clients "communication"?
What I aim to do is to fulfill a mutual communication between one server but multiple clients. Here is the Server part I wrote: Import subprocess, time, socket, fileinput s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host='' port = 2000 s.bind((host, port)) s.listen(2) # here 2 means the maximum number of clien...
[ "Use Twisted.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004140431_python.txt
Q: firefox can't establish connection with localhost while running a cherrypy tutorial example in Fedora core my configuration [global] server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 10 server.environment = "production" server.showTracebacks = "True" server.logToScreen = "False" I have...
firefox can't establish connection with localhost while running a cherrypy tutorial example in Fedora core
my configuration [global] server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 10 server.environment = "production" server.showTracebacks = "True" server.logToScreen = "False" I have no access to "root" Please suggest me anythin
[ "Make your socket host address as \"localhost\" or correct ip address.\n[global]\nserver.socket_host = \"\"\nserver.socket_port = 8080\n\n[Edit:]\nThere seems to be a bug in cherrypy < 3.0\nserver.socket_host \n\nThis setting binds CherryPy to a particular ip address. This isn't usually necessary, as CherryPy will ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004140550_python.txt
Q: Does JQuery/Django have a way to build "click the text to edit"? A Flickr page displays the title and description of the photo. When I click on the description, it will turn it into a text-box, with a Save button. Then, I can edit what I want...and click "Save." It'll save it via AJAX. It doesn't go to a differe...
Does JQuery/Django have a way to build "click the text to edit"?
A Flickr page displays the title and description of the photo. When I click on the description, it will turn it into a text-box, with a Save button. Then, I can edit what I want...and click "Save." It'll save it via AJAX. It doesn't go to a different page or anything...it just turns the current description into a wik...
[ "jEditable\nhttp://www.appelsiini.net/projects/jeditable/default.html for demo\n" ]
[ 4 ]
[]
[]
[ "django", "forms", "html", "javascript", "python" ]
stackoverflow_0004140634_django_forms_html_javascript_python.txt
Q: Shrink and merge PDFs in Python I'm trying to shrink and merge two A4 PDF pages into one A4 page so that if I had; _____ _____ | | | | | p1 | | p2 | | | | | |_____| |_____| I would get; _____ | p1 | |.....| | p2 | |_____| As a ne...
Shrink and merge PDFs in Python
I'm trying to shrink and merge two A4 PDF pages into one A4 page so that if I had; _____ _____ | | | | | p1 | | p2 | | | | | |_____| |_____| I would get; _____ | p1 | |.....| | p2 | |_____| As a new PDF, with two A5 sized pages on tha...
[ "pdfnup has this functionality (http://pypi.python.org/pypi/pdfnup)#\ne.g.\nfrom pyPdf import PdfFileWriter, PdfFileReader\nfrom pdfnup import generateNup\n\noutput = PdfFileWriter()\ninput1 = PdfFileReader(file(\"in.pdf\", \"rb\"))\n\npage1 = input1.getPage(0)\npage2 = input1.getPage(1)\n\noutput.addPage(page1)\no...
[ 4, 1 ]
[]
[]
[ "pdf", "pdf_generation", "python" ]
stackoverflow_0004140466_pdf_pdf_generation_python.txt
Q: Python Search Algebra Function I am trying to make a search function to work with algebra problems. I want something like Wolfram Alpha but I am building a python framework for it. It should be able to figure out multiple variables and equations on both sides of the equal sign. I have recently asked about a valida...
Python Search Algebra Function
I am trying to make a search function to work with algebra problems. I want something like Wolfram Alpha but I am building a python framework for it. It should be able to figure out multiple variables and equations on both sides of the equal sign. I have recently asked about a validator for the program so I need a loop...
[ "The eval()s won't work, because left and right are strings, not expressions. Moreover, you'll have to do substantial validation to make what a user might input a valid Python expression. Consider a few values you might get:\n# The typical person's notation for x-squared isn't valid Python\nx^2 + x - 3\n# 3x means ...
[ 1 ]
[]
[]
[ "algebra", "function", "python", "search" ]
stackoverflow_0004140780_algebra_function_python_search.txt
Q: Python: Random combination from two files New to python, bear with me. I have two text files, each has a word on a line (some funny words). I want to create a third file which has the random combination of those. with a space between them. Example: File1: Smile Sad Noob Happy ... File2: Face Apple Orange ... Fil...
Python: Random combination from two files
New to python, bear with me. I have two text files, each has a word on a line (some funny words). I want to create a third file which has the random combination of those. with a space between them. Example: File1: Smile Sad Noob Happy ... File2: Face Apple Orange ... File3: Smile Orange Sad Apple Noob Face ..... How...
[ "from __future__ import with_statement\nimport random\nimport os\n\nwith open('File1', 'r') as f1:\n beginnings = [word.rstrip() for word in f1]\n\nwith open('File2', 'r') as f2:\n endings = [word.rstrip() for word in f2]\n\nwith open('File3', 'w') as f3:\n for beginning in beginnings:\n f3.write('%...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004140798_python.txt
Q: How do I convert GAE TimeProperty to integer? In this Python package there is this code: >>> dt = DateTime('Mar 9, 1997 13:45:00 US/Eastern') >>> dt.timeTime() 857933100.0 I would use this package but there is a warning: "Unless you need to communicate with Zope 2 APIs, you're probably better off using Python's b...
How do I convert GAE TimeProperty to integer?
In this Python package there is this code: >>> dt = DateTime('Mar 9, 1997 13:45:00 US/Eastern') >>> dt.timeTime() 857933100.0 I would use this package but there is a warning: "Unless you need to communicate with Zope 2 APIs, you're probably better off using Python's bult-in datetime module." TimeProperty in GAE gives ...
[ "Check out the time module.\nimport time\nvalue = time.time()\n\n" ]
[ 1 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0004140944_datetime_google_app_engine_python.txt
Q: Tkinter: Listbox separators, disabled items, keyboard navigation? I'm studying the Tkinter Listbox widget and have been unable to find solutions for the following functionality: How can I create non-selectable horizontal separator items, eg. separators equivalent to the Tkinter Menu widget's .add_separator()? (Us...
Tkinter: Listbox separators, disabled items, keyboard navigation?
I'm studying the Tkinter Listbox widget and have been unable to find solutions for the following functionality: How can I create non-selectable horizontal separator items, eg. separators equivalent to the Tkinter Menu widget's .add_separator()? (Using chars like dashes and underscores looks awful). How can I disable ...
[ "\nyou cannot. The widget doesn't support that.\nyou can't disable certain items, the widget doesn't support a state attribute. That being said, you can monitor the selection and do the appropriate thing if the user selects something that is disabled, and use the item foreground to denote disabled-ness.\nYou will n...
[ 5 ]
[]
[]
[ "listbox", "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0004140396_listbox_python_tkinter_ttk_user_interface.txt
Q: My script needs to run two loops at the same time to read IO data from two different sources. Is my threading correct? import threading import mynetworking def FirstNIC(): for addr in mynetworking.first.scan(): print addr def SecondNIC(): for addr in mynetworking.second.scan(): print ad...
My script needs to run two loops at the same time to read IO data from two different sources. Is my threading correct?
import threading import mynetworking def FirstNIC(): for addr in mynetworking.first.scan(): print addr def SecondNIC(): for addr in mynetworking.second.scan(): print addr first = threading.Thread(target=FirstNIC) second = threading.Thread(target=SecondNIC) first.start() second.start() Th...
[ "Your code is fine except that your print statments can collide because they could both write at once. Use Queue.queue for easy synchronization:\nimport threading\nimport mynetworking\nimport Queue\n\ndef FirstNIC(queue):\n for addr in mynetworking.first.scan(queue):\n queue.put(addr)\n\ndef SecondNIC(qu...
[ 1 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0004140928_asynchronous_multithreading_python.txt
Q: Temporary variables in Mathematica I have written a package for Mathematica called MathOO. In short, it allows you to use object orientation in Mathematica just like you do in Python. Please read the following article in Voofie/MathOO for details: MathOO: Adding Python style Object Orientation to Mathematica with ...
Temporary variables in Mathematica
I have written a package for Mathematica called MathOO. In short, it allows you to use object orientation in Mathematica just like you do in Python. Please read the following article in Voofie/MathOO for details: MathOO: Adding Python style Object Orientation to Mathematica with MathOO (1.0 beta launch) [Alternative to...
[ "Mathematica really does garbage collects Temporary variables when they have no more references. That said, there's two reasons that your x$117 is not garbage collected.\n\nRemember that Module uses lexical scoping, so the module variables are only \"local\" in the sense that they are give a unique name \"var$modnu...
[ 2, 1 ]
[]
[]
[ "oop", "python", "wolfram_mathematica" ]
stackoverflow_0004114136_oop_python_wolfram_mathematica.txt
Q: What is a simple way to extract the list of URLs on a webpage using python? I want to create a simple web crawler for fun. I need the web crawler to get a list of all links on one page. Does the python library have any built in functions that would make this any easier? Thanks any knowledge appreciated. A: This ...
What is a simple way to extract the list of URLs on a webpage using python?
I want to create a simple web crawler for fun. I need the web crawler to get a list of all links on one page. Does the python library have any built in functions that would make this any easier? Thanks any knowledge appreciated.
[ "This is actually very simple with BeautifulSoup.\nfrom BeautifulSoup import BeautifulSoup\n\n[element['href'] for element in BeautifulSoup(document_contents).findAll('a', href=True)]\n\n# [u'http://example.com/', u'/example', ...]\n\nOne last thing: you can use urlparse.urljoin to make all URLs absolute. If you ne...
[ 7, 0, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0004139989_python_web_applications.txt
Q: Python API for Amazon EC2 that supports files The command line tool ec2-run-instances takes a -f parameter to pass a file to the instance at run time. Are there any Python APIs for EC2 that do the equivalent? I'm looking to customize a Wowza Media Server, which requires passing in a file when booting up a new ima...
Python API for Amazon EC2 that supports files
The command line tool ec2-run-instances takes a -f parameter to pass a file to the instance at run time. Are there any Python APIs for EC2 that do the equivalent? I'm looking to customize a Wowza Media Server, which requires passing in a file when booting up a new image.
[ "You can either use boto. Then you can possibly code a small script to open a file first and read it's contents and pass it as user-data. \nOr try http://github.com/fschulze/mr.awsome\n" ]
[ 1 ]
[]
[]
[ "amazon_ec2", "api", "python" ]
stackoverflow_0004140640_amazon_ec2_api_python.txt
Q: json.dumps throws UnicodeDecodeError I had unknown encoding in a MS ACCESS data table because the text inputs originated by people copying and pasting from Word documents. So when I attempted: final_data_to_write = json.dumps(list_of_text_lines) The error output was: "UnicodeDecodeError: 'utf8' codec can't deco...
json.dumps throws UnicodeDecodeError
I had unknown encoding in a MS ACCESS data table because the text inputs originated by people copying and pasting from Word documents. So when I attempted: final_data_to_write = json.dumps(list_of_text_lines) The error output was: "UnicodeDecodeError: 'utf8' codec can't decode byte 0xe1 in position 5: unexpected end...
[ "You need to find out what character encoding is used in your database. Then you need to tell JSON encoder to use that encoding to properly interpret strings.\nfinal_data_to_write = json.dumps(myDict, encoding=\"XXX\")\n\nDefault encoding assumed by json module is UTF-8.\n", "The conversion from Access to Excel s...
[ 3, 2, 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0004140869_json_python.txt
Q: Pylons config has a different content in websetup.py In my pylons application I want to add some data on setup. ( a user) To secure passwords in the database i've hashed the passwords with a salt, this salt is stored in the configuration file. If I want to get the saltkey from configuration I do this (shortened ex...
Pylons config has a different content in websetup.py
In my pylons application I want to add some data on setup. ( a user) To secure passwords in the database i've hashed the passwords with a salt, this salt is stored in the configuration file. If I want to get the saltkey from configuration I do this (shortened example): from pylons import config saltkey = config.get("s...
[ "You can access your config file in this step. The from pylons import config method is best suited to doing so in the context of a WSGI request. However, you're not dealing with a WSGI request, so it's unavailable. Fortunately, you have a very easy way of accessing config during websetup.py's operation. The set...
[ 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0004126000_pylons_python_sqlalchemy.txt
Q: Java setRequestHeader in Python What is the equivalent of this java statement in python? post.setRequestHeader("Cookie", jSessionID); I'm very confused as to whether this is really a cookie or just POST data with a key of 'Cookie' I have urllib2 and cookielib imported, and am confused. I'm also trying to send a f...
Java setRequestHeader in Python
What is the equivalent of this java statement in python? post.setRequestHeader("Cookie", jSessionID); I'm very confused as to whether this is really a cookie or just POST data with a key of 'Cookie' I have urllib2 and cookielib imported, and am confused. I'm also trying to send a file along with the url request, but t...
[ "Try something like this:\nsock = httplib.HTTPConnection('server.com', 80)\ndata = \"op=a_login_attempt\"\nheaders = { \"Host\":\"server.com\",\n \"Content-Type\":\"application/x-www-form-urlencoded; charset=UTF=8\",\n \"Referer\":\"server2.com\",\n \"Cookie\":\"session=12345678\",}...
[ 2, 0 ]
[]
[]
[ "http_headers", "java", "python" ]
stackoverflow_0004142253_http_headers_java_python.txt
Q: Why tuple is being used in string format I came across code like print "Users connected: %d" % (userCount, ) I was wondering, is there any reason of not writing them in print "Users connected: %d" % userCount They seem having the same output A: The code without an explicid tuple may bite you if your variable c...
Why tuple is being used in string format
I came across code like print "Users connected: %d" % (userCount, ) I was wondering, is there any reason of not writing them in print "Users connected: %d" % userCount They seem having the same output
[ "The code without an explicid tuple may bite you if your variable contains a tuple.\n>>> nums = (1, 2, 3, 4)\n>>> print \"debug: %r\" % (nums, )\ndebug: (1, 2, 3, 4)\n>>> print \"debug: %r\" % nums\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: not all arguments converted d...
[ 14, 0, 0, 0 ]
[ "They have the same output but the code looks different. Every software developer has developed a \"style\" over the years based on the kind of errors they make. If you tend to forget the comma in a single-element tuple or if you write code for different versions of Python or you just want to make your life easier ...
[ -1 ]
[ "python", "syntax" ]
stackoverflow_0004142243_python_syntax.txt
Q: Handling multiple end-users using threading in python I have an upload page in django powered site. The end-users upload the documents from that page. The back end processing of that uploaded document can take several minutes. How do i handle multiple end-users' request in the back end? I have thought of using thr...
Handling multiple end-users using threading in python
I have an upload page in django powered site. The end-users upload the documents from that page. The back end processing of that uploaded document can take several minutes. How do i handle multiple end-users' request in the back end? I have thought of using thread for each end-user's request. However, i am finding it d...
[ "The other way to start a thread is to give your callable to the Thread constructor, like this:\nfrom threading import Thread\n\nprocessing_thread = Thread(target=your_heavy_lifting_function_name)\nprocessing_thread.start()\n\n", "Without more information its hard to say what exactly, but threads sound like a rea...
[ 2, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004142206_multithreading_python.txt
Q: lxml.html search and replace I need your help or suggestion, whatever. I start reading some books about python just because of this problem I have :) But I see it will takes long time for me to learn the whole language. I also skimmed and searched through lxml.html documentation but still I can figure out how to d...
lxml.html search and replace
I need your help or suggestion, whatever. I start reading some books about python just because of this problem I have :) But I see it will takes long time for me to learn the whole language. I also skimmed and searched through lxml.html documentation but still I can figure out how to do this what I want. I created two ...
[ "Use BeautifulSoup to parse the document and recreate it after processing it. It is the easiest thing to do. I wouldn't use lxml for what you are trying to do.\n\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html\n\nLook at example here on how tags are added and removed:\n\nExtract all <script> tags i...
[ 2, 1 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0004141764_html_lxml_python.txt
Q: pyparsing, forward, and recursion I'm using pyparsing to parse vcd (value change dump) files. Essentially, I want to read in the files, parse it into an internal dictionary, and manipulate the values. Without going into details on the structure, my problem occurs with identifying nested categories. In vcd files, ...
pyparsing, forward, and recursion
I'm using pyparsing to parse vcd (value change dump) files. Essentially, I want to read in the files, parse it into an internal dictionary, and manipulate the values. Without going into details on the structure, my problem occurs with identifying nested categories. In vcd files, you have 'scopes' which include wires a...
[ "According to your definition, a scope cannot contain another scope, followed by some maps, followed by another scope.\nIf the parser has a debug mode where it prints its parse tree, you will be able to see this immediately. But in short, you're saying there are zero or more maps, followed by zero or more scopes, ...
[ 9, 6 ]
[]
[]
[ "forward", "pyparsing", "python", "recursion" ]
stackoverflow_0004140884_forward_pyparsing_python_recursion.txt
Q: Using Python's PIL, how do I enhance the contrast/saturation of an image? Just a simple contrast and saturation enhancement. Nothing fancy. A: Since PIL is dead for the most part. Install the Pillow fork instead, sudo pip install pillow, and use its ImageEnhance module http://pillow.readthedocs.org/en/3.0.x/refe...
Using Python's PIL, how do I enhance the contrast/saturation of an image?
Just a simple contrast and saturation enhancement. Nothing fancy.
[ "Since PIL is dead for the most part. Install the Pillow fork instead, sudo pip install pillow, and use its ImageEnhance module http://pillow.readthedocs.org/en/3.0.x/reference/ImageEnhance.html\n>>> from PIL import Image, ImageEnhance\n>>> image = Image.open('downloads/jcfeb2011.jpg')\n>>> contrast = ImageEnhance....
[ 28 ]
[]
[]
[ "algorithm", "image", "python", "python_imaging_library" ]
stackoverflow_0004142687_algorithm_image_python_python_imaging_library.txt
Q: Python class changer I need class runtime class declaration from database. Some class need override field and redeclaration. models.py class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") utils.py def class_changer(class_path, field_key, new_Fi...
Python class changer
I need class runtime class declaration from database. Some class need override field and redeclaration. models.py class Staff(object): name = StringField( verbose_name = "Full name") age = IntegerField( verbose_name = "Age") utils.py def class_changer(class_path, field_key, new_Field): pass ??????...
[ "you need better architecture for this, but as a starting solution you may try this,\nIn [12]: class a1(object):\n ...: pass\n\nIn [13]: def class_changer(cls_path, attr, val):\n ....: try:\n ....: obj = eval(cls_path)\n ....: setattr(obj, attr, val)\n ....: except:\n ....: ...
[ 4, 1 ]
[]
[]
[ "architecture", "coding_style", "metaprogramming", "python" ]
stackoverflow_0004142681_architecture_coding_style_metaprogramming_python.txt
Q: Python properties also as class properties I have a set of classes which can contain an optional name attribute. The reason is that the classes will get a default name if the attribute is set, but individual classes can still have a custom name if needed. What I want is to be able to get the name attribute from bo...
Python properties also as class properties
I have a set of classes which can contain an optional name attribute. The reason is that the classes will get a default name if the attribute is set, but individual classes can still have a custom name if needed. What I want is to be able to get the name attribute from both the class (without any class instance) and fr...
[ "class NameMixinMeta(type):\n def _get_name(self):\n return getattr(self, '_name', self.__name__)\n\n def _set_name(self, name):\n self._name = name\n\n name = property(_get_name, _set_name)\n\nclass NameMixin(object):\n __metaclass__ = NameMixinMeta\n def _get_name(self):\n retu...
[ 1, 0 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0004143002_properties_python.txt
Q: Python: split by (different) n spaces I have lines like this: 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000 6 30 139 "guid" Other name^7 0 ip.a.dd.res:port 932 25000 I would like to split this, but the problem is that there is different number of space...
Python: split by (different) n spaces
I have lines like this: 2 20 164 "guid" Some name^7 0 ip.a.dd.res:port -21630 25000 6 30 139 "guid" Other name^7 0 ip.a.dd.res:port 932 25000 I would like to split this, but the problem is that there is different number of spaces between this "words"... How can I do this...
[ "Python's split function doesn't care about the number of spaces:\n>>> ' 2 20 164 \"guid\" Some name^7 0 ip.a.dd.res:port -21630 25000'.split()\n['2', '20', '164', '\"guid\"', 'Some', 'name^7', '0', 'ip.a.dd.res:port', '-21630', '25000']\n\n", "Have you tried split()? It will \"compress\" space...
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0004143531_python_split.txt
Q: Emacs on Mac for Python - python-mode keeps using the default Python version how do I change the version of Python that emacs uses in the python-mode to the latest version that I just installed ? I tried setting the PATH in my init.el file to the path where the latest version of python resides but its not working....
Emacs on Mac for Python - python-mode keeps using the default Python version
how do I change the version of Python that emacs uses in the python-mode to the latest version that I just installed ? I tried setting the PATH in my init.el file to the path where the latest version of python resides but its not working.
[ "Set the variable python-python-command. This can be done via customize:\n\nM-x customize-option RET python-python-command RET\nChange the value to point to the appropriate binary.\n\n", "PATH is only searched when a program is launched via the shell.\nFor programs that are launched directly by Emacs (for example...
[ 1, 0 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0004140943_emacs_python.txt
Q: Make Python aritmetic operations Possible Duplicate: python limiting floats to two decimal points If I make this: 12.45-12 in Python the answer I get is: 0.44999999999999929 I do I do it to make it: 0.45? BTW I did remember to do: 12.45-12.0 But no result. A: This is a result of the fact that many decimals can...
Make Python aritmetic operations
Possible Duplicate: python limiting floats to two decimal points If I make this: 12.45-12 in Python the answer I get is: 0.44999999999999929 I do I do it to make it: 0.45? BTW I did remember to do: 12.45-12.0 But no result.
[ "This is a result of the fact that many decimals cannot be exactly represented in binary.\nFor example, 0.25 can: it's 0.01 (0*1, 0*1/2, 1*1/4). 0.1 can't (0.0001100110011...), just like you can't write 1/3 as a complete decimal (0.3333333333...).\nIf you do\nprint(12.45-12)\n\nyou get\n0.45\n\nbecause print only d...
[ 5, 2, 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0004143709_floating_point_python.txt
Q: Filter the particular dictionary d = {'id': 'ccccc', 'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]} I want to filter it using s_id. Suppose if some one want to filter the s_id = 11 it should return {'s_id': '11', 'city':'yy'}. Please answer using the filter keyword. A: Just use pyt...
Filter the particular dictionary
d = {'id': 'ccccc', 'school': [{'s_id': '12', 'city': 'xxx'}, {'s_id': '11', 'city':'yy'}]} I want to filter it using s_id. Suppose if some one want to filter the s_id = 11 it should return {'s_id': '11', 'city':'yy'}. Please answer using the filter keyword.
[ "Just use python built-in filter function :\n>>> filter(lambda d:d['s_id']=='11',d['school'])\n[{'s_id': '11', 'city': 'yy'}]\n\nas a bonus, if you want to sort by 's_id'\nyou can do:\n>>> for school in sorted(d['school'],key=lambda d:d['s_id']):\n... print school\n... \n{'s_id': '11', 'city': 'yy'}\n{'s_id': '...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "filter", "python" ]
stackoverflow_0004143705_dictionary_filter_python.txt
Q: Does on-the-fly list creation and return in a function create a memory leak in Python? If I create a list in a python function and return it to the caller, how does garbage collection work on that list? Do I have to do anything to keep a memory leak from occurring? For example: #!/usr/bin/python import random c...
Does on-the-fly list creation and return in a function create a memory leak in Python?
If I create a list in a python function and return it to the caller, how does garbage collection work on that list? Do I have to do anything to keep a memory leak from occurring? For example: #!/usr/bin/python import random class Example: def f1(self): list = [] len = random.randint(0, 30) ...
[ "There's no memory leak here. The list assigned to l is the same list that is generated in the function. Python passes objects, not references or values.\nPython keeps track of the references to that list: on each iteration of the while loop, a new list is created and assigned to l. This causes the previous one to ...
[ 6, 2 ]
[]
[]
[ "garbage_collection", "memory_leaks", "python" ]
stackoverflow_0004143967_garbage_collection_memory_leaks_python.txt
Q: In Python can one implement mixin behavior without using inheritance? Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance? class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Foo(object): # Somehow...
In Python can one implement mixin behavior without using inheritance?
Is there a reasonable way in Python to implement mixin behavior similar to that found in Ruby -- that is, without using inheritance? class Mixin(object): def b(self): print "b()" def c(self): print "c()" class Foo(object): # Somehow mix in the behavior of the Mixin class, # so that all of the methods b...
[ "def mixer(*args):\n \"\"\"Decorator for mixing mixins\"\"\"\n def inner(cls):\n for a,k in ((a,k) for a in args for k,v in vars(a).items() if callable(v)):\n setattr(cls, k, getattr(a, k).im_func)\n return cls\n return inner\n\nclass Mixin(object):\n def b(self): print \"b()\"\...
[ 9, 4, 3, 3, 3, 0, 0, 0 ]
[]
[]
[ "inheritance", "mixins", "python", "ruby" ]
stackoverflow_0004139508_inheritance_mixins_python_ruby.txt
Q: django-paypal IPN doesn't work I'm using django-paypal as a payment solution inside my django application. I'm trying to implement a IPN handler. What happens when I receive an IPN message at my IPN-handling URL the django server crashes: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-pac...
django-paypal IPN doesn't work
I'm using django-paypal as a payment solution inside my django application. I'm trying to implement a IPN handler. What happens when I receive an IPN message at my IPN-handling URL the django server crashes: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/django/core/servers/basehttp.p...
[ "I admit I'm an idiot :)\nYou don't need ssl for this. But what you need is to do a syncdb before you are able to use it,...\nGod sometimes it is so easy that you just don't see it.\n", "Can you monitor precisely the packet that paypal is sending your server using tcpdump or wireshark? It looks like they may be t...
[ 5, 0 ]
[]
[]
[ "django", "django_paypal", "paypal", "python" ]
stackoverflow_0004133988_django_django_paypal_paypal_python.txt
Q: Vertical code block delimiters in eclipse Is it possible to enable vertical bars delimiting code blocks in eclipse ? A: If you are referencing to bug 84878 about "Draw vertical lines in control flow statements", then no, it isn't possible yet. In order to help reading complex algorithm, one could imagine having...
Vertical code block delimiters in eclipse
Is it possible to enable vertical bars delimiting code blocks in eclipse ?
[ "If you are referencing to bug 84878 about \"Draw vertical lines in control flow statements\", then no, it isn't possible yet.\n\nIn order to help reading complex algorithm, one could imagine having some graphical connections in between constructs (remember when we learned algorithmic at school).\n\nif (...) {\n| ...
[ 1 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0004143737_eclipse_python.txt
Q: Python to C# conversion In python i'm creating .an file using commandStr="dpan.exe -np -Lwork_%s.lib -Owork_%s.lib %s %s.an" %( option1, option2, Sourcefile, Destination file) os.system( commandStr ) This will create the .an file (Destination file) from Sourcefile. Now i'm converting this line of code from Pytho...
Python to C# conversion
In python i'm creating .an file using commandStr="dpan.exe -np -Lwork_%s.lib -Owork_%s.lib %s %s.an" %( option1, option2, Sourcefile, Destination file) os.system( commandStr ) This will create the .an file (Destination file) from Sourcefile. Now i'm converting this line of code from Python to C# So how do i do this i...
[ "You could use the Process.Start method:\nProcess.Start(\n \"dpan.exe\", \n string.Format(\n \"-np -Lwork_{0}.lib -Owork_{1}.lib \\\"{2}\\\" \\\"{3}.an\\\"\", \n option1, option2, sourceFile, destinationFile\n )\n);\n\n", "The equivalent of os.system is System.Diagnostics.Process.Start in C...
[ 4, 2 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0004144649_c#_python.txt
Q: What's the fix for module _mysql: This Python has API version 1012, module _mysql has version 1013 If I try to use the shell I get this API conflict. /home/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-linux-i686.egg-tmp/_mysql.so:6: RuntimeWarning: Python C API version mismatch for module _mysql: This Python...
What's the fix for module _mysql: This Python has API version 1012, module _mysql has version 1013
If I try to use the shell I get this API conflict. /home/username/.python-eggs/MySQL_python-1.2.3c1-py2.6-linux-i686.egg-tmp/_mysql.so:6: RuntimeWarning: Python C API version mismatch for module _mysql: This Python has API version 1012, module _mysql has version 1013. I'm running: Python 2.6 MySQL Server version: 5....
[ "The error message means the _mysql module, part of MySQLdb, was built for a newer version of Python than it's being loaded into. API version 1013 is the one used by Python 2.5 and 2.6, and 1012 is the one used by Python 2.4. You don't say how you're using MySQLdb, but apparently it's being imported by Python 2.4.\...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004138414_mysql_python.txt
Q: Python: Execute scp, stdin for password not working I'm trying the following from subprocess import Popen, PIPE Popen(["scp", "-B","user@url:file", "."], stdin=PIPE, shell=False).communicate(input="password") But I still get the password promt, and no password is sent. I know I can use scp with keys, but this is ...
Python: Execute scp, stdin for password not working
I'm trying the following from subprocess import Popen, PIPE Popen(["scp", "-B","user@url:file", "."], stdin=PIPE, shell=False).communicate(input="password") But I still get the password promt, and no password is sent. I know I can use scp with keys, but this is not what I need. Any help?
[ "scp interacts with the terminal directly, rather than reading from STDIN, You can't pass the password via a pipe, it security matter for scp and it's the same for sftp, ssh.\nyou can try it in you terminal like this (and it will not work):\necho \"password\" | scp me@localhost:test .\n\n", "As others have said, ...
[ 2, 1 ]
[]
[]
[ "passwords", "popen", "python", "scp", "stdin" ]
stackoverflow_0004144134_passwords_popen_python_scp_stdin.txt
Q: How to have data structure with both tuple and dictionary characteristic By refering code at http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor >>> rec['data'] "abc'def" >>> rec[2] "abc'def" I was wondering how they manage to make a data structure having both tuple and dictionary characteristic? A:...
How to have data structure with both tuple and dictionary characteristic
By refering code at http://initd.org/psycopg/docs/extras.html#dictionary-like-cursor >>> rec['data'] "abc'def" >>> rec[2] "abc'def" I was wondering how they manage to make a data structure having both tuple and dictionary characteristic?
[ "In Python the [] lookups are handled by the __getitem__ magic method; in other words, when you index a custom class Python will call instance.__getitem__(...) and return you the value. This lets you do e.g.\n>>> class Foo:\n... def __getitem__(self, value):\n... return value\n...\n>>> foo = Foo()\n...
[ 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0004142406_psycopg2_python.txt
Q: Extract lines below category and stop when another category is reached Let's suppose I have a text file of movie genres with my favorite movies under each genre. [category] Horror: Movie Movie Movie [category] Comedy: Movie [category] Action: Movie Movie How would I create a function that extracts and packa...
Extract lines below category and stop when another category is reached
Let's suppose I have a text file of movie genres with my favorite movies under each genre. [category] Horror: Movie Movie Movie [category] Comedy: Movie [category] Action: Movie Movie How would I create a function that extracts and packages all the movie titles below a certain [category] * into an array without...
[ "You could parse the file line-by-line this way:\nimport collections\n\nresult=collections.defaultdict(list)\nwith open('data') as f:\n genre='unknown'\n for line in f:\n line=line.strip()\n if line.startswith('[category]'):\n genre=line.replace('[category]','',1)\n elif line:\...
[ 2, 2, 1, 0 ]
[]
[]
[ "python", "text_extraction" ]
stackoverflow_0004145053_python_text_extraction.txt
Q: calling cmd from python windows error 2 I am tring to call the cmd command "move" from python. cmd1 = ["move", spath , npath] startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd1, startupinfo=startupinfo) While the comammand works in the ...
calling cmd from python windows error 2
I am tring to call the cmd command "move" from python. cmd1 = ["move", spath , npath] startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd1, startupinfo=startupinfo) While the comammand works in the cmd. I can move files. With this python code ...
[ "move is built-in into the cmd shell, so it's not a file command that you can call this way.\nYou could use shutil.move(), but this \"forgets\" all alternate data stream, ACLs etc.\n", "try to use cmd1 = [\"cmd\", \"/c\", \"move\", spath, npath]\n" ]
[ 3, 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004145331_python_windows.txt
Q: Cron Syntax, MAC OS X Quick Summary of Issue I would to run a python script every minute of everyday. I would like cron to run the following 2 commands (in this order) every minute: cd ~/desktop/WebProgramming python MyPythonScript.py Is it possible for cron to run 2 commands? More Detailed Explanation I am havi...
Cron Syntax, MAC OS X
Quick Summary of Issue I would to run a python script every minute of everyday. I would like cron to run the following 2 commands (in this order) every minute: cd ~/desktop/WebProgramming python MyPythonScript.py Is it possible for cron to run 2 commands? More Detailed Explanation I am having difficulty running a pyt...
[ "The proper fix would be to make MyPythonFile.py look in the appropriate directory for its files.\nIf you don't want to do that (...), then:\n* * * * * cd ~/desktop/WebProgramming ; python MyPythonScript.py\n\n", "... (cd ~/desktop/WebProgramming/ && python ...)\n", "Try and specify absolute paths to scripts wh...
[ 6, 1, 0 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0004145387_cron_python.txt
Q: Python + QT, Windows Forms or Swing for a cross-platform application? I'd like to develop a small/medium-size cross-platform application (including GUI). My background: mostly web applications with MVC architectures, both Python (Pylons + SqlAlchemy) and Java (know the language well, but don't like it that much). ...
Python + QT, Windows Forms or Swing for a cross-platform application?
I'd like to develop a small/medium-size cross-platform application (including GUI). My background: mostly web applications with MVC architectures, both Python (Pylons + SqlAlchemy) and Java (know the language well, but don't like it that much). I also know some C#. So far, I have no GUI programming experience (neither ...
[ "I'm a Python guy and use PyQt myself, and I can wholly recommend it. Concerning your cons:\n\ncompilation, distribution and deployment more difficult?\n\nNo, not really. For many projects, a full setup.py for e.g. cx_Freeze can be less than 30 lines that rarely need to change (most import dependencies are detected...
[ 5 ]
[]
[]
[ "c#", "cross_platform", "java", "python", "user_interface" ]
stackoverflow_0004145350_c#_cross_platform_java_python_user_interface.txt
Q: /etc/init.d sh script I'm new to python. I want to create controlled script executed from /etc/init.d command like /etc/init.d something start/stop/restart Any advise appreciated. A: See this post on how to write a script to place in your /etc/init.d directory. The only difference is you must change the hash-b...
/etc/init.d sh script
I'm new to python. I want to create controlled script executed from /etc/init.d command like /etc/init.d something start/stop/restart Any advise appreciated.
[ "See this post on how to write a script to place in your /etc/init.d directory. The only difference is you must change the hash-bang line to point to python, and not bash:\n#!/usr/bin/python\ndef myfunc():\n print 'myfunct()'\n\nif __name__ == '__main__':\n print 'running python script'\n myfunc()\n\nAnd m...
[ 3, 1, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004145282_linux_python.txt
Q: How to use .pem file with Python M2Crypto To generate an RSA key pair I used openssl: openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem Now I want to use this my_key.public.pem file in a function of another .py file: import M2Crypto from M2Crypto import ...
How to use .pem file with Python M2Crypto
To generate an RSA key pair I used openssl: openssl genrsa -out my_key.private.pem 1024 openssl rsa -in my_key.private.pem -pubout -out my_key.public.pem Now I want to use this my_key.public.pem file in a function of another .py file: import M2Crypto from M2Crypto import RSA,SSL def encrypt(): pk = open( 'my_key....
[ "According to the documentation the load_pub_key expects a file name as input. It returns a M2Crypto.RSA.RSA_pub object, which doesn't make sense to print. What exactly are trying to achieve?\n", "Try this:\nRSA.load_key('mykey.pem')\n\n" ]
[ 4, 0 ]
[]
[]
[ "m2crypto", "pem", "python" ]
stackoverflow_0001176055_m2crypto_pem_python.txt
Q: In Python, how can you respond to method calls that don't exist on an object? Possible Duplicate: Dynamic Finders and Method Missing in Python I know you can do this in Ruby, but how would it be done in Python? So basically you could maybe to a regex on the method call that didn't exist, and create 'syntactic su...
In Python, how can you respond to method calls that don't exist on an object?
Possible Duplicate: Dynamic Finders and Method Missing in Python I know you can do this in Ruby, but how would it be done in Python? So basically you could maybe to a regex on the method call that didn't exist, and create 'syntactic sugar'.
[ "Define __getattr__.\nBut that still won't make s./.*/ valid syntax, if that's what you have in mind. Python's syntax is nowhere as bendable as Ruby's.\n", "You can override __getattribute__ on an object to handle requests for attributes that do not exist. This only works for new-style classes. If you have old-st...
[ 2, 1 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0004145844_metaprogramming_python.txt
Q: Best way to python table? Any thoughts on the best way to implement a table (i.e. a small relational database) in python without using any external databases extra modules and when the sqlite3 module is broken or missing. user:~ $ python3 >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line...
Best way to python table?
Any thoughts on the best way to implement a table (i.e. a small relational database) in python without using any external databases extra modules and when the sqlite3 module is broken or missing. user:~ $ python3 >>> import sqlite3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/bns/rm...
[ "Use sqlite3.\n\nIt comes with python, you don't need\nexternal databases or extra modules.\nIt can create the whole database on\nmemory. You don't need extra files on\ndisk if you don't want to.\nIt's lightning fast.\nIt can do modern queries on the\ntables, like JOINs\n\nThere's no reason to not use it. It will b...
[ 14, 4, 2 ]
[]
[]
[ "database", "python" ]
stackoverflow_0004146254_database_python.txt
Q: __getattr__ doesn't work with __enter__ -> AttributeError I would like to use with on an object that uses __getattr__ to redirect calls. Howerver, this does not seem to work with the method __enter__ Please consider the following, simplified code to reproduce the error: class EnterTest(object): def myenter(sel...
__getattr__ doesn't work with __enter__ -> AttributeError
I would like to use with on an object that uses __getattr__ to redirect calls. Howerver, this does not seem to work with the method __enter__ Please consider the following, simplified code to reproduce the error: class EnterTest(object): def myenter(self): pass def __exit__(self, type, value, traceback)...
[ "According to upstream, this working was a bug in 2.6 which was \"fixed\" in 2.7. The short answer is that methods like __enter__ are looked up on the class, not on the object.\nThe documentation for this obscure behavior is at http://docs.python.org/reference/datamodel#specialnames: x[i] is roughly equivalent to ...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004146095_python.txt
Q: Scatter plot with a huge amount of data I would like to use Matplotlib to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way. import matplotlib.pyplot as plt import numpy as np from numpy import * from ...
Scatter plot with a huge amount of data
I would like to use Matplotlib to generate a scatter plot with a huge amount of data (about 3 million points). Actually I've 3 vectors with the same dimension and I use to plot in the following way. import matplotlib.pyplot as plt import numpy as np from numpy import * from matplotlib import rc import pylab from pylab ...
[ "Unless your graphic is huge, many of those 3 million points are going to overlap.\n(A 400x600 image only has 240K dots...)\nSo the easiest thing to do would be to take a sample of say, 1000 points, from your data:\nimport random\ndelta_sample=random.sample(delta,1000)\n\nand just plot that.\nFor example:\nimport m...
[ 29, 11, 9 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0004082298_matplotlib_numpy_python.txt
Q: Python Combinatorics, part 2 This is a follow-up question to Combinatorics in Python I have a tree or directed acyclic graph if you will with a structure as: Where r are root nodes, p are parent nodes, c are child nodes and b are hypothetical branches. The root nodes are not directly linked to the parent nodes, i...
Python Combinatorics, part 2
This is a follow-up question to Combinatorics in Python I have a tree or directed acyclic graph if you will with a structure as: Where r are root nodes, p are parent nodes, c are child nodes and b are hypothetical branches. The root nodes are not directly linked to the parent nodes, it is only a reference. I am intres...
[ "This problem can be solved in Python easily and elegantly, because there is a module called \"itertools\".\nLets say we have objects of type HypotheticalBranch, which have attributes r, p and c. Just as you described it in your post:\nclass HypotheticalBranch(object):\n def __init__(self, r, p, c):\n self.r=r\...
[ 3, 1, 1, 0 ]
[]
[]
[ "combinatorics", "python" ]
stackoverflow_0004145873_combinatorics_python.txt
Q: How can I use Boost::Python to add a method to an exported class without modifying the base class? I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion be...
How can I use Boost::Python to add a method to an exported class without modifying the base class?
I have a class in C++ that I can't modify. However, that class holds an std::list<> of items that I need to be able to access in a Python extension. Since Boost::Python doesn't seem to have a built-in conversion between an std::list and a Python list, I was hoping to be able to write a method in C++ that could do thi...
[ "To answer the question in a more general way, you can attach any c++ function that has the right signature to the python export in the class_ declaration. \nassume a class foo:\nstruct foo\n{\n //class stuff here\n}\n\nYou can define a free function that takes a reference to foo as the first argument:\nint do_t...
[ 3, 1 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0002348960_boost_python_c++_python.txt
Q: How do I insert a SuperColumn with python/thrift? Using the python/thrift interface I am trying to insert a SuperColumn just like the Comments example in WTF is a Supercolumn.. I've gotten as far as to create the SuperColumn and figured out that I should use batch_mutate to insert it. But I don't know how to creat...
How do I insert a SuperColumn with python/thrift?
Using the python/thrift interface I am trying to insert a SuperColumn just like the Comments example in WTF is a Supercolumn.. I've gotten as far as to create the SuperColumn and figured out that I should use batch_mutate to insert it. But I don't know how to create the Mutation and set the key and SuperColumn type key...
[ "I would use pycassa or something to make life easier, but something like:\nkeyspace = \"Keyspace1\"\ntableName = \"Super1\"\nkey = \"jdoe\"\ncol1 = Column(name = \"commenter\", value = \"J Doe\", timestamp = time.time())\ncol2 = Column(name = \"email\", value = \"jdoe@example.com\", timestamp = time.time())\n\nnew...
[ 0 ]
[]
[]
[ "cassandra", "python", "thrift" ]
stackoverflow_0004145831_cassandra_python_thrift.txt
Q: Removing clients from the reactor in Twisted I have a simple TCP client which is connected to twisted using: reactor.connectTCP(host, port, SomeClientFactory()) The program is able to receive a HUP signal to trigger a reload. I'd like to basically: Remove the old clients Reload config Create new clients based up...
Removing clients from the reactor in Twisted
I have a simple TCP client which is connected to twisted using: reactor.connectTCP(host, port, SomeClientFactory()) The program is able to receive a HUP signal to trigger a reload. I'd like to basically: Remove the old clients Reload config Create new clients based upon new config However, I can't seem to find a way...
[ "IReactorTCP.connectTCP returns an IConnector provider. As you can see on the definition of the IConnector interface, the disconnect method will do something like what you want. You can also use the protocol instance's transport attribute's loseConnection method, of course. The latter would be more suitable if t...
[ 2 ]
[]
[]
[ "python", "tcp", "twisted" ]
stackoverflow_0004146379_python_tcp_twisted.txt
Q: Uniqueness of global Python objects void in sub-interpreters? I have a question about inner-workings of Python sub-interpreter initialization (from Python/C API) and Python id() function. More precisely, about handling of global module objects in a WSGI Python containers (like uWSGI used with nginx and mod_wsgi on...
Uniqueness of global Python objects void in sub-interpreters?
I have a question about inner-workings of Python sub-interpreter initialization (from Python/C API) and Python id() function. More precisely, about handling of global module objects in a WSGI Python containers (like uWSGI used with nginx and mod_wsgi on Apache). The following code works as expected (isolated) in both o...
[ "It's not entirely clear what you're asking; I'd give a more concise answer if the question was more specific.\nFirst, the id of an object is, in fact--at least in CPython--its address in memory. That's perfectly normal: two objects in the same process at the same time can't share an address, and an object's addre...
[ 2, 2 ]
[]
[]
[ "mod_wsgi", "python", "uwsgi" ]
stackoverflow_0004146630_mod_wsgi_python_uwsgi.txt
Q: How can I handle attributes in python? I have to create a function, printObjects(attribute, option), which must print the objects based on a certain attribute. The attribute can take ints or strings as input. The option attribute is optional. How do I implement this for my class? A: I assume you want something l...
How can I handle attributes in python?
I have to create a function, printObjects(attribute, option), which must print the objects based on a certain attribute. The attribute can take ints or strings as input. The option attribute is optional. How do I implement this for my class?
[ "I assume you want something like this, or perhaps it will be helpful at least:\n\ndef printObject(obj, attributes=()):\n for a in attributes:\n print getattr(obj, a)\n\n" ]
[ 1 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0004147202_arguments_python.txt
Q: Django Text Markup Editors Can you suggest some good django-specific text-markup editors? A: As for WYSIWYG in-page editor, there are not too many alternatives: wymeditor (used by djangocms), tinymce, ckeditor. I prefer tinymce because there is an easy integration with django-filebrowser. btw you can find better...
Django Text Markup Editors
Can you suggest some good django-specific text-markup editors?
[ "As for WYSIWYG in-page editor, there are not too many alternatives: wymeditor (used by djangocms), tinymce, ckeditor. I prefer tinymce because there is an easy integration with django-filebrowser.\nbtw you can find better answers than mine in SO:\nhttps://stackoverflow.com/search?q=django+wysiwyg\n", "If you've ...
[ 2, 0 ]
[]
[]
[ "django", "markup", "markup_extensions", "python", "semantic_markup" ]
stackoverflow_0004141220_django_markup_markup_extensions_python_semantic_markup.txt
Q: What's the right way for a Python/Twisted program to validate an SSL certificate under Windows? Is there a way for a Python/Twisted program to cleanly make use of the list of root certificates that Internet Explorer uses to validate an SSL connection to an HTTPS server? The answers provided to Validate SSL certif...
What's the right way for a Python/Twisted program to validate an SSL certificate under Windows?
Is there a way for a Python/Twisted program to cleanly make use of the list of root certificates that Internet Explorer uses to validate an SSL connection to an HTTPS server? The answers provided to Validate SSL certificates with Python are very helpful but the example code gets the root certificates by reading the Un...
[ "The Windows equivalent is \"copy /etc/ssl/certs/*.pem from your Linux machine\". Mac and Windows have different native APIs for getting at their respective certificate stores, which Twisted doesn't directly support. They don't use OpenSSL certificates natively, and they certainly don't put things in as straightf...
[ 3 ]
[]
[]
[ "python", "ssl", "twisted", "windows" ]
stackoverflow_0004145123_python_ssl_twisted_windows.txt
Q: Silent Installer - to install scripting langues from winform Application I am developing Winform application, using C# on .NET 4.0, which need to install scripting langue(s) based on the user selection. What is the best way to detect if a particular scripting environment/Engine for a given langue(Ruby, python, Per...
Silent Installer - to install scripting langues from winform Application
I am developing Winform application, using C# on .NET 4.0, which need to install scripting langue(s) based on the user selection. What is the best way to detect if a particular scripting environment/Engine for a given langue(Ruby, python, Perl, etc) is installed on client machine and silently install it if not already ...
[ "Though I agree with idea that a truly \"silent\" install might not be desirable for the users, there are many different installer packages that support silent installation.\nThis page actually has a good breakdown of the various installers and the command arguments needed to do unattended and silent installations....
[ 1 ]
[]
[]
[ "c#", "python", "ruby", "silent_installer", "winforms" ]
stackoverflow_0004146953_c#_python_ruby_silent_installer_winforms.txt
Q: Python Class Inheritance issue I'm playing with Python Class inheritance and ran into a problem where the inherited __init__ is not being executed if called from the sub-class (code below) the result I get from Active Python is: >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Li...
Python Class Inheritance issue
I'm playing with Python Class inheritance and ran into a problem where the inherited __init__ is not being executed if called from the sub-class (code below) the result I get from Active Python is: >>> start Tom Sneed Sue Ann Traceback (most recent call last): File "C:\Python26\Lib\site-packages\pythonwin\pywin\fram...
[ "Three things:\n\nYou need to explicitly call the constructor. It isn't called for you automatically like in C++\nUse a new-style class inherited from object\nWith a new-style class, use the super() method available\n\nThis will look like:\nclass Person(object):\n AnotherName = 'Sue Ann'\n def __init__(self):...
[ 25, 9, 5, 2 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0000927985_class_inheritance_python.txt
Q: Proxying with django and gunicorn I have a django application that i serve using gunicorn. I do that by using the method prescribed on the gunicorn site - embedding gunicorn into my django application. I'm trying to set up a proxy into my application so that when you go to "http://mysite.com/proxy/" it does proxy ...
Proxying with django and gunicorn
I have a django application that i serve using gunicorn. I do that by using the method prescribed on the gunicorn site - embedding gunicorn into my django application. I'm trying to set up a proxy into my application so that when you go to "http://mysite.com/proxy/" it does proxy you to "http://mysite.com:8100". I know...
[ "You should deploy some proxy application into your gunicorn installation, such as WSGIProxy.\n", "I've written dj-revproxy for easy integration of a proxy in django. Bonus point it's using restkit which use the gunicorn HTTP engine. (I'm one of the gunicorn authors). More info here:\nhttps://github.com/benoitc/d...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004065437_django_python.txt
Q: Spurious failures in django.contrib.messages.tests when running manage.py test I've recently added authentication (via django.contrib.auth of course) to my application, along with appropriate "signin"/"signup" links to my base.html. The problem comes when I run manage.py tests, and I get 4 failures, all from djang...
Spurious failures in django.contrib.messages.tests when running manage.py test
I've recently added authentication (via django.contrib.auth of course) to my application, along with appropriate "signin"/"signup" links to my base.html. The problem comes when I run manage.py tests, and I get 4 failures, all from django.contrib.messages.tests: ERROR: test_middleware_disabled_anon_user (django.contrib....
[ "There are several suggestions for workarounds in this Django ticket and links therein: http://code.djangoproject.com/ticket/11077 The one I like is this: http://groups.google.com/group/django-developers/msg/ec7508651e9e9fb8. To summarize, it divides up built-in tests and app tests, then overrides manage.py test to...
[ 3 ]
[]
[]
[ "django", "django_contrib", "python" ]
stackoverflow_0003424710_django_django_contrib_python.txt
Q: Macintosh Python: 64-bit vs 32-bit problems I'm trying to sort through a whole host of problems arising from upgrading my macintosh to 10.6. Most of the tools I need work, but a couple (scipy, wxpython) do not, and give error messages that are highly suggestive of my messing up something with 64-bit and 32-bit bin...
Macintosh Python: 64-bit vs 32-bit problems
I'm trying to sort through a whole host of problems arising from upgrading my macintosh to 10.6. Most of the tools I need work, but a couple (scipy, wxpython) do not, and give error messages that are highly suggestive of my messing up something with 64-bit and 32-bit binaries. I'm currently running Python 2.7. I don't ...
[ "I also had major problems upgrading, so you are not alone, only a bit late.\nTo figure out what kind of binary you have, the file command is your friend:\n$ file /usr/local/bin/python\n/usr/local/bin/python: Mach-O universal binary with 2 architectures\n/usr/local/bin/python (for architecture i386): Mach-O execut...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004146317_python.txt
Q: write sql results to XML using python using SQL server 2005+ for over a year now, I've been running a query to return all users from the database for whom i'd like generate a report for. at the end of the query, I've added for xml auto The result of this is a link to a file where the xml lives (one row, one co...
write sql results to XML using python
using SQL server 2005+ for over a year now, I've been running a query to return all users from the database for whom i'd like generate a report for. at the end of the query, I've added for xml auto The result of this is a link to a file where the xml lives (one row, one column). I then take this file and pass it th...
[ "PyODBC to talk to MS SQL Server, libxml2 to handle the XSLT, and subprocess to run your Java program.\n" ]
[ 2 ]
[]
[]
[ "python", "sql_server_2005", "xml" ]
stackoverflow_0004147865_python_sql_server_2005_xml.txt
Q: is there a more efficient way to write results from a query in python? This is effectively how i'm using _mssql. Everything works fine, even after i use fetch_array(). The problem is, when I iterate through fetch_array(), it takes over ten minutes for 6K rows to be written to the body of an email. This just isn't ...
is there a more efficient way to write results from a query in python?
This is effectively how i'm using _mssql. Everything works fine, even after i use fetch_array(). The problem is, when I iterate through fetch_array(), it takes over ten minutes for 6K rows to be written to the body of an email. This just isn't acceptable. Is there a better way for me to do this? EDIT: haven't figured o...
[ "Could you show us some code of iterating through the results and creating an email? If I had to make a wild guess, I would say you are probably violating this idiom: \"Build strings as a list and use ''.join at the end.\" If you keep adding to a string as you go you create a new (and progressively larger) string o...
[ 1 ]
[]
[]
[ "python", "sql_server_2005" ]
stackoverflow_0004147901_python_sql_server_2005.txt
Q: Using python to generate XML from SQL tables I have some XML as follows: <dd> <persson> <name>sam</name> <tel>9748</tel> </persson> <cat> <name>frank</name> </cat> </dd> I parsed it into two SQL tables, one for the tags and one for the pcdata. The start and stop columns rep...
Using python to generate XML from SQL tables
I have some XML as follows: <dd> <persson> <name>sam</name> <tel>9748</tel> </persson> <cat> <name>frank</name> </cat> </dd> I parsed it into two SQL tables, one for the tags and one for the pcdata. The start and stop columns represent the position the tag appears at and ends. T...
[ "H'mmm having decoded your \"columns\":\n<dd><persson><name>sam</name><tel>9748</tel></persson>\n1 2 3 4 5 6 7 8 9 \n<cat><name>frank</name></cat></dd>\n10 11 12 13 14 15\n\nI have some questions for you: How did you do that? Why did you do that? Exactly ...
[ 3, 1, 1 ]
[]
[]
[ "postgresql", "python", "sql", "xml" ]
stackoverflow_0004139959_postgresql_python_sql_xml.txt