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: Matching 3 out 5 fields - Django I'm finding this a bit tricky! Maybe someone can help me on this one I have the following model: class Unicorn(models.Model): horn_length = models.IntegerField() skin_color = models.CharField() average_speed = models.IntegerField() magical = models.BooleanField() affinit...
Matching 3 out 5 fields - Django
I'm finding this a bit tricky! Maybe someone can help me on this one I have the following model: class Unicorn(models.Model): horn_length = models.IntegerField() skin_color = models.CharField() average_speed = models.IntegerField() magical = models.BooleanField() affinity = models.CharField() I would like t...
[ "It has to be done in the HAVING clause:\nSELECT ... HAVING (IF(a.horn_length=b.horn_length, 1, 0) + ...) >= 3\n\nThere's no way to express HAVING in the Django ORM so you'll need to drop to raw SQL in order to perform it.\n", "You should use Q objects. The rough example is:\nfrom django.db.models import Q\nfrom ...
[ 2, 2, 1, 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "python", "sql_server" ]
stackoverflow_0002964460_django_django_models_django_queryset_python_sql_server.txt
Q: Python - Converting CSV to Objects - Code Design I have a small script we're using to read in a CSV file containing employees, and perform some basic manipulations on that data. We read in the data (import_gd_dump), and create an Employees object, containing a list of Employee objects (maybe I should think of a be...
Python - Converting CSV to Objects - Code Design
I have a small script we're using to read in a CSV file containing employees, and perform some basic manipulations on that data. We read in the data (import_gd_dump), and create an Employees object, containing a list of Employee objects (maybe I should think of a better naming convention...lol). We then call clean_all_...
[ "Looks fine to me. Good job. How often are you going to run this script? Most of your questions are moot if this is a one-off thing.\n\nI like the way Employees.cleen_all_phone_numbers() delegates to Employee.clean_phone_number()\nYou really should be using an index (dictionary) here. You can index each employee by...
[ 3, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002963975_oop_python.txt
Q: CSRF error when trying to log onto Django admin page with w3m on Emacs23 I normally use Firefox and have had no problems with the admin page on my Django website. But I use Emacs23 for writing my posts, and wanted to be able to use w3m in Emacs to copy the stuff across. When I try to log into my admin pages, it ...
CSRF error when trying to log onto Django admin page with w3m on Emacs23
I normally use Firefox and have had no problems with the admin page on my Django website. But I use Emacs23 for writing my posts, and wanted to be able to use w3m in Emacs to copy the stuff across. When I try to log into my admin pages, it gives the CSRF error: CSRF verification failed. Request aborted. Help Reason...
[ "Django 1.2 requires a CSRF token by default for all form POSTs. I don't think there's a way to get the token via an API call in order to be able to to post from Emacs. \nYou could just remove the effects of the @protect_csrf decorator on the django-bundled view by copying and tweaking that view's code to make a be...
[ 1 ]
[]
[]
[ "django", "emacs", "python" ]
stackoverflow_0002964790_django_emacs_python.txt
Q: Upon USB insert, record unique identifer sting, format drive to FAT32 and copy a file. Bash or Python This is what I want to do, insert USB flash drive. mount it. record uniquie identifer string to a file. format the drive to FAT32. copy a text file to the drive. unmount it. remove the drive. 30 times The situat...
Upon USB insert, record unique identifer sting, format drive to FAT32 and copy a file. Bash or Python
This is what I want to do, insert USB flash drive. mount it. record uniquie identifer string to a file. format the drive to FAT32. copy a text file to the drive. unmount it. remove the drive. 30 times The situation is this, I have bought 30 usb drives. I need to format each one to ensure they are clean, I need the un...
[ "In order to automatically detect an inserted USB flash drive, you could use autofs. Unfortunately it is not able to run a script when a device is inserted, otherwise the other steps could be performed quite easily.\nSo, you need to detect that autofs mounted a new flash drive. crontab might be a solution to period...
[ 2 ]
[]
[]
[ "bash", "detect", "python", "usb_drive" ]
stackoverflow_0002964749_bash_detect_python_usb_drive.txt
Q: How to see if there is one microphone active using python? I want to see if there is a microphone active using Python. How can I do it? Thanks in advance! A: Microphones are analog devices, most api's probably couldn't even tell you if there is a microphone plugged in, your computer just reads data from one of y...
How to see if there is one microphone active using python?
I want to see if there is a microphone active using Python. How can I do it? Thanks in advance!
[ "Microphones are analog devices, most api's probably couldn't even tell you if there is a microphone plugged in, your computer just reads data from one of your soundcards input channels.\nWhat you probably want to know is if the input channels are turned on or off. Determining that is highly platform specific.\n",...
[ 4, 2 ]
[]
[]
[ "microphone", "python", "python_2.7" ]
stackoverflow_0002797572_microphone_python_python_2.7.txt
Q: Add Header section to SOAP request using SOAPpy I need to construct this SOAP query using python SOAPpy module: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelo...
Add Header section to SOAP request using SOAPpy
I need to construct this SOAP query using python SOAPpy module: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <LicenseHeader xmlns="http://s...
[ "I am not sure how to do this in SOAPpy but I do know how to do it in suds. SUDS does the same thing as SOAPpy but it is newer and is still supported. I don't think SOAPpy is supported anymore. Below show's the code to connect to a WSDL and send a soap request:\nclass MySudsClass():\n\ndef sudsFunction(self):\n\n ...
[ 3 ]
[]
[]
[ "python", "soap", "soappy", "xml" ]
stackoverflow_0002964867_python_soap_soappy_xml.txt
Q: Is safe ( documented behaviour? ) to delete the domain of an iterator in execution I wanted to know if is safe ( documented behaviour? ) to delete the domain space of an iterator in execution in Python. Consider the code: import os import sys sampleSpace = [ x*x for x in range( 7 ) ] print sampleSpace for dx in...
Is safe ( documented behaviour? ) to delete the domain of an iterator in execution
I wanted to know if is safe ( documented behaviour? ) to delete the domain space of an iterator in execution in Python. Consider the code: import os import sys sampleSpace = [ x*x for x in range( 7 ) ] print sampleSpace for dx in sampleSpace: print str( dx ) if dx == 1: del sampleSpace[ 1 ] ...
[ "From the Python tutorial:\n\nIt is not safe to modify the sequence\n being iterated over in the loop (this\n can only happen for mutable sequence\n types, such as lists). If you need to\n modify the list you are iterating over\n (for example, to duplicate selected\n items) you must iterate over a copy.\n Th...
[ 6, 1, 0 ]
[]
[]
[ "iteration", "python", "undocumented_behavior" ]
stackoverflow_0002965351_iteration_python_undocumented_behavior.txt
Q: Is there a 'hello world' website for django? OR (I've installed django, now what)? I'm learning Python and decided to start familiarizing myself with the (defacto?) Python web framework - django. I have successfully installed the latest release of django. I want a simple 'hello world' website that will get me up a...
Is there a 'hello world' website for django? OR (I've installed django, now what)?
I'm learning Python and decided to start familiarizing myself with the (defacto?) Python web framework - django. I have successfully installed the latest release of django. I want a simple 'hello world' website that will get me up and running quickly. I am already familiar with web frameworks (albeit for different lang...
[ "Next step? The (free, online and excellent) Django book.\n", "Writing your first Django app, part 1 was a lot of help.\n", "\"Hello World\" of django is the \"Polls and Votes\"\n", "I think the official tutorial says it all...\ncd /path/to/your/code\npython django-admin.py startproject mysite #creates dir '...
[ 10, 3, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002964452_django_python.txt
Q: feedparser - various errors I need feedparser (se http://www.feedparser.org) for a project, and want to keep third party modules in a separate folder. I did this by adding a folder to my python path, and putting relevant modules there, among them feedparser. This first attempt to import feedparser resulted in >>> ...
feedparser - various errors
I need feedparser (se http://www.feedparser.org) for a project, and want to keep third party modules in a separate folder. I did this by adding a folder to my python path, and putting relevant modules there, among them feedparser. This first attempt to import feedparser resulted in >>> import feedparser Traceback (most...
[ "The first error sounds like your copy of feedparser.py is corrupt. The last line of the file should be entirely a comment:\n#4.1 - MAP - removed socket timeout; added support for chardet library\n\nIt sounds like a line break has been introduced resulting in an invalid statement at the end of the file:\n#4.1 - MAP...
[ 1 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0002965324_feedparser_python.txt
Q: How can I include static text in a StringVar() and still have it update to variable changes? I would like to create a StringVar() that looks something like this: someText = "The Spanish Inquisition" # Here's a normal variable whose value I will change eventually TkEquivalent = StringVar() # and here's the StringV...
How can I include static text in a StringVar() and still have it update to variable changes?
I would like to create a StringVar() that looks something like this: someText = "The Spanish Inquisition" # Here's a normal variable whose value I will change eventually TkEquivalent = StringVar() # and here's the StringVar() TkEquivalent.set(string(someText)) #and here I set it equal to the normal variable. When som...
[ "A StringVar does not bind with a Python name (what you'd call a variable), but with a Tkinter widget, like this:\na_variable= Tkinter.StringVar()\nan_entry= Tkinter.Entry(textvariable=a_variable)\n\nFrom then on, any change of a_variable through its .set method will reflect in the an_entry contents, and any modifi...
[ 4 ]
[]
[]
[ "concatenation", "python", "string", "text", "tkinter" ]
stackoverflow_0002770409_concatenation_python_string_text_tkinter.txt
Q: Send files between python+django and C# i would like to know, what is the best way to send files between python and C# and vice versa. I have my own protocol which work on socket level, and i can send string and numbers in both ways. Loops works too. With this i can send pretty much anything, like package of users...
Send files between python+django and C#
i would like to know, what is the best way to send files between python and C# and vice versa. I have my own protocol which work on socket level, and i can send string and numbers in both ways. Loops works too. With this i can send pretty much anything, like package of users id, if it is simple data. But soon i will st...
[ "RPC may be a good idea for you, because it's relatively very high level. Instead of defining your own server and protocols, you can simply remotely execute routines over the network, pass in arguments and get back results. \nFor example, both languages have libraries for XML-RPC.\n", "The easier way on my use ca...
[ 0, 0 ]
[]
[]
[ "c#", "python", "sockets" ]
stackoverflow_0002930211_c#_python_sockets.txt
Q: whats the best way to parse and replace the string with its values? I may have string like, """Hello, %(name)s, how are you today, here is amount needed: %(partner_id.account_id.debit_amount)d """ what would be the best solution for such template may i need to combine regular expression and eval, input string ma...
whats the best way to parse and replace the string with its values?
I may have string like, """Hello, %(name)s, how are you today, here is amount needed: %(partner_id.account_id.debit_amount)d """ what would be the best solution for such template may i need to combine regular expression and eval, input string may differ like $partner_id.account_id.debit_amount$ - for the moment I've ...
[ "Python implemented a new .format() method on strings in Python 2.6 and 3.0. Check out this PEP: http://www.python.org/dev/peps/pep-3101/\nIt is more powerful and flexible than the % operator and built into python:\nHere are some examples from the PEP:\n\"My name is {0}\".format('Fred')\n\"My name is {0.name}\".for...
[ 2, 1, 0 ]
[]
[]
[ "python", "replace", "string_formatting", "templates" ]
stackoverflow_0002965694_python_replace_string_formatting_templates.txt
Q: Reading and writing pickles to an encoded stream A file format commonly used in our system is base64 encoded pickles - at the moment I can translate to and from strings in this trivial format with some simple code like this: def dumps( objinput ): """ Return an encoded cPickle """ return cpickle_du...
Reading and writing pickles to an encoded stream
A file format commonly used in our system is base64 encoded pickles - at the moment I can translate to and from strings in this trivial format with some simple code like this: def dumps( objinput ): """ Return an encoded cPickle """ return cpickle_dumps( objinput ).encode( ENCODING ) def loads( strinpu...
[ "I think you can in fact do this by implementing a file-like object, which can then be passed directly to cPickle.load\nclass Base64PickleAdapter:\n def __init__(self, base64_input):\n ...\n\n def read(size=-1):\n ... \n\n def readline():\n ... # Can be implemented in terms of read.\n\ncPickle only re...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002966042_python.txt
Q: How can I get mounted name and (Drive letter too) on Windows using python I am using Daemon tool to mount an ISO image on Windows XP machine.I do mount using Daemon command (daemon.exe -mount 0,iso_path). Above command will mount ISO image to device number. In my case I have 4 partition (C,D,E,F) and G for DVD/CD-...
How can I get mounted name and (Drive letter too) on Windows using python
I am using Daemon tool to mount an ISO image on Windows XP machine.I do mount using Daemon command (daemon.exe -mount 0,iso_path). Above command will mount ISO image to device number. In my case I have 4 partition (C,D,E,F) and G for DVD/CD-RW. Now what happen, ISO gets mounted to drive letter 'H:' with name (as define...
[ "The daemon tools exe itself has some command line parameters :\n-get_count and -get_letter\nBut for me these do not work in the latest version (DLite).\nInstead you can use the commands :\nmountvol - lists all the mounted drives\ndir - you can parse the output to get the volume label\nWhat you should do is run mou...
[ 1, 1, 0 ]
[]
[]
[ "daemon", "iso", "mount", "python" ]
stackoverflow_0002673236_daemon_iso_mount_python.txt
Q: multi threading python/ruby vs java? i wonder if the multi threading in python/ruby is equivalent to the one in java? by that i mean, is it as efficient? cause if you want to create a chat application that use comet technology i know that you have to use multi threading. does this mean that i can use python or rub...
multi threading python/ruby vs java?
i wonder if the multi threading in python/ruby is equivalent to the one in java? by that i mean, is it as efficient? cause if you want to create a chat application that use comet technology i know that you have to use multi threading. does this mean that i can use python or ruby for that or is it better with java? than...
[ "This is not a question about Ruby, Python or Java, but more about a specific implementation of Ruby, Python or Java. There are Java implementations with extremely efficient threading implementations and there are Java implementations with extremely bad threading implementations. And the same is true for Ruby and P...
[ 10, 3, 1 ]
[]
[]
[ "java", "python", "ruby" ]
stackoverflow_0002963615_java_python_ruby.txt
Q: Python and IronPython on same machine? I am a total newbie in the Python world. I want to start to experiment with Python and IronPython and compare the results. Is it possible to install Python and IronPython on the same machine with interfering each other or is it better to do this in the virtual machine. Thx in...
Python and IronPython on same machine?
I am a total newbie in the Python world. I want to start to experiment with Python and IronPython and compare the results. Is it possible to install Python and IronPython on the same machine with interfering each other or is it better to do this in the virtual machine. Thx in advance.
[ "Yes, Python and IronPython are completely different applications that happen to implement (almost) the same language.\n", "Should be no problem, they have different executable filenames also.\n", "Sure, you could even install different versions of cPython interpreter (2.5, 2.6, 3.0, etc). \n" ]
[ 6, 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0002964910_ironpython_python.txt
Q: Modify Django admin app index I want to change the app index page so I add help text to the models themselves, e.g. under each model I want to add help text. I know that I should override AdminSite.app_index. What is the best way to do this? A: I can create a new AdminSite subclass, and override app_index method...
Modify Django admin app index
I want to change the app index page so I add help text to the models themselves, e.g. under each model I want to add help text. I know that I should override AdminSite.app_index. What is the best way to do this?
[ "I can create a new AdminSite subclass, and override app_index method to send the help text to the template. In urls.py I can use an instance of MyAdminSite instead of django's vanilla AdminSite.\n# urls.py\nfrom mysite.admin import MyAdminSite\nsite = MyAdminSite()\n\nurlpatterns = patterns('', \n (r'^admin/'...
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002966300_django_django_admin_python.txt
Q: More efficient web framework than Web.py? Extremely Pythonic please! I love webpy, it's really quite Pythonic but I don't like having to add the url mappings and create a class, typically with just 1 function inside it. I'm interested in minimising code typing and prototyping fast. Does anyone have any up and comi...
More efficient web framework than Web.py? Extremely Pythonic please!
I love webpy, it's really quite Pythonic but I don't like having to add the url mappings and create a class, typically with just 1 function inside it. I'm interested in minimising code typing and prototyping fast. Does anyone have any up and coming suggestions such as Bobo, Nagare, Bottle, Flask, Denied, cherrypy for a...
[ "Flask, Armin Ronacher's microframework built on top of Werkzeug, Jinja2 and good intentions (though you can use whichever templating engine you like, or none at all), does URL mapping very concisely.\n@app.route(\"/\")\ndef index():\n return \"\"\"Hello, world. <a href=\"/thing/spam_eggs\">Here's a thing.</a>\"\"...
[ 9, 8, 1 ]
[]
[]
[ "cherrypy", "python", "web.py", "web_applications" ]
stackoverflow_0002964281_cherrypy_python_web.py_web_applications.txt
Q: How to transition from PHP to Python Django? Here's my background: Decent experience with PHP/MySql. Beginner's experience with OOP Why I want to learn Python Django? I gave in, based on many searches on SO and reading over some of the answers, Python is a great, clean, and structured language to learn. And with...
How to transition from PHP to Python Django?
Here's my background: Decent experience with PHP/MySql. Beginner's experience with OOP Why I want to learn Python Django? I gave in, based on many searches on SO and reading over some of the answers, Python is a great, clean, and structured language to learn. And with the framework Django, it's easier to write codes ...
[ "\nCan i do everything in Django as in PHP?\n\nAlways\n\nIs Django a \"big\" hit in web development as PHP?\n\nOnly time will tell.\n\nWith PHP, PHP and Mysql are VERY closely related, is there a close relation between Django and Mysql?\n\nDjango supports several RDBMS interfaces. MySQL is popular, so is SQLite an...
[ 6, 1, 1, 1 ]
[]
[]
[ "django", "php", "python" ]
stackoverflow_0002961402_django_php_python.txt
Q: How to force PyYAML to load strings as unicode objects? The PyYAML package loads unmarked strings as either unicode or str objects, depending on their content. I would like to use unicode objects throughout my program (and, unfortunately, can't switch to Python 3 just yet). Is there an easy way to force PyYAML to ...
How to force PyYAML to load strings as unicode objects?
The PyYAML package loads unmarked strings as either unicode or str objects, depending on their content. I would like to use unicode objects throughout my program (and, unfortunately, can't switch to Python 3 just yet). Is there an easy way to force PyYAML to always strings load unicode objects? I do not want to clutter...
[ "Here's a version which overrides the PyYAML handling of strings by always outputting unicode. In reality, this is probably the identical result of the other response I posted except shorter (i.e. you still need to make sure that strings in custom classes are converted to unicode or passed unicode strings yourself ...
[ 28, 3 ]
[]
[]
[ "python", "python_2.x", "pyyaml" ]
stackoverflow_0002890146_python_python_2.x_pyyaml.txt
Q: Send a .png file using python cgi How can I send a .png file using python cgi to a flex application? Thanks in advance... A: The Python/CGI side of your question can be as simple as something like this, if you just need to send an existing image: import sys # Send the Content-Type header to let the client know ...
Send a .png file using python cgi
How can I send a .png file using python cgi to a flex application? Thanks in advance...
[ "The Python/CGI side of your question can be as simple as something like this, if you just need to send an existing image:\nimport sys\n\n# Send the Content-Type header to let the client know what you're sending\nsys.stdout.write('Content-Type: image/png\\r\\n\\r\\n')\n\n# Send the actual image data\nwith open('pat...
[ 3 ]
[]
[]
[ "apache_flex", "cgi", "python" ]
stackoverflow_0002965726_apache_flex_cgi_python.txt
Q: How do I configure the Python logging module in Django? I'm trying to configure logging for a Django app using the Python logging module. I have placed the following bit of configuration code in my Django project's settings.py file: import logging import logging.handlers import os date_fmt = '%m/%d/%Y %H:%M:%S' lo...
How do I configure the Python logging module in Django?
I'm trying to configure logging for a Django app using the Python logging module. I have placed the following bit of configuration code in my Django project's settings.py file: import logging import logging.handlers import os date_fmt = '%m/%d/%Y %H:%M:%S' log_formatter = logging.Formatter(u'[%(asctime)s] %(levelname)-...
[ "Kind of anti-climactic, but it turns out there was a third-party app installed in the project that had its own logging configuration that was overriding the one I set up (it modified the root logger, for some reason -- not very kosher for a Django app!). Removed that code and everything works as expected.\n", "I...
[ 3, 2, 2, 0 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002961001_django_logging_python.txt
Q: autocomplete-like feature with a python dict In PHP, I had this line matches = preg_grep('/^for/', array_keys($hash)); What it would do is it would grab the words: fork, form etc. that are in $hash. In Python, I have a dict with 400,000 words. It's keys are words I'd like to present in an auto-complete like featur...
autocomplete-like feature with a python dict
In PHP, I had this line matches = preg_grep('/^for/', array_keys($hash)); What it would do is it would grab the words: fork, form etc. that are in $hash. In Python, I have a dict with 400,000 words. It's keys are words I'd like to present in an auto-complete like feature (the values in this case are meaningless). How w...
[ ">>> mydict={\"fork\" : True, \"form\" : True, \"fold\" : True, \"fame\" : True}\n>>> [k for k in mydict if k.startswith(\"for\")]\n['fork', 'form']\n\nThis should be faster than using a regular expression (and sufficient if you're just looking for word beginnings).\n", "So this isn't a direct answer to what you ...
[ 6, 3, 1, 1, 0 ]
[]
[]
[ "autocomplete", "python" ]
stackoverflow_0002967799_autocomplete_python.txt
Q: How to minimize one application using c# or python? How can I minimize Microsoft Speech Recognition: (source: microsoft.com) using C# or python? A: For C#: Using System.Diagnostics.Process you can select the process when it's running. From there you can get the MainWindow Handle at .MainWindowHandle and then c...
How to minimize one application using c# or python?
How can I minimize Microsoft Speech Recognition: (source: microsoft.com) using C# or python?
[ "For C#:\nUsing System.Diagnostics.Process you can select the process when it's running. From there you can get the MainWindow Handle at .MainWindowHandle and then call the windows API to minimize the application.\nUnfortunately I do not know the specifics for that call, you'd have to google it.\n" ]
[ 1 ]
[]
[]
[ "c#", "minimize", "process", "python", "window" ]
stackoverflow_0002967965_c#_minimize_process_python_window.txt
Q: Problems installing a package from PyPI: root files not installed After installing the BitTorrent-bencode package, either via easy_install BitTorrent-bencode or pip install BitTorrent-bencode, or by downloading the tarball and installing that via easy_install $tarball, I discover that /usr/local/lib/python2.6/dist...
Problems installing a package from PyPI: root files not installed
After installing the BitTorrent-bencode package, either via easy_install BitTorrent-bencode or pip install BitTorrent-bencode, or by downloading the tarball and installing that via easy_install $tarball, I discover that /usr/local/lib/python2.6/dist-packages/BitTorrent_bencode-5.0.8-py2.6.egg/ contains EGG-INFO/ and te...
[ "It seems this package's setup.py is broken — it does not define right package for distribution. I think, you need to check setup.py in source release and if it is true — report a bug to author of this package.\n" ]
[ 1 ]
[]
[]
[ "easy_install", "pip", "pypi", "python" ]
stackoverflow_0002963302_easy_install_pip_pypi_python.txt
Q: How to share an array in Python with a C++ Program? I two programs running, one in Python and one in C++, and I need to share a two-dimensional array (just of decimal numbers) between them. I am currently looking into serialization, but pickle is python-specific, unfortunately. What is the best way to do this? Tha...
How to share an array in Python with a C++ Program?
I two programs running, one in Python and one in C++, and I need to share a two-dimensional array (just of decimal numbers) between them. I am currently looking into serialization, but pickle is python-specific, unfortunately. What is the best way to do this? Thanks Edit: It is likely that the array will only have 50 e...
[ "I suggest Google's protobuf\n", "You could try using boost::python to make your applications interoperable.\nSome information about pickle support and plain boost::python documentation.\n", "You could try hosting the array in a Memory-mapped file, although you will need to synchronize access to the file to avo...
[ 5, 4, 4, 3, 2, 1, 1 ]
[]
[]
[ "c++", "python", "serialization" ]
stackoverflow_0002968172_c++_python_serialization.txt
Q: extend php with java/c++? i only know php and i wonder if you can extend a php web application with c++ or java when needed? i dont want to convert my code with quercus, cause that is very error prone. is there another way to extend it? cause from what i have read python can extend it with c++ without converting t...
extend php with java/c++?
i only know php and i wonder if you can extend a php web application with c++ or java when needed? i dont want to convert my code with quercus, cause that is very error prone. is there another way to extend it? cause from what i have read python can extend it with c++ without converting the python code and use java wit...
[ "Most of PHP is written in modular C code. You can create your own PHP extensions in C. See http://php.net/internals, the PHP wiki and the book \"Extending and Embedding PHP\" by Sara Golemon.\n" ]
[ 3 ]
[]
[]
[ "c++", "java", "php", "php_extension", "python" ]
stackoverflow_0002968814_c++_java_php_php_extension_python.txt
Q: parsing xml file with similar tags and different attributes! I am sorry if this is a repeated question or a basic one as I am new to Python. I am trying to parse the following XML commands so that I can "extract" the tag value for Daniel and George. I want the answer to look like Daniel = 78, George = 90. <epas:p...
parsing xml file with similar tags and different attributes!
I am sorry if this is a repeated question or a basic one as I am new to Python. I am trying to parse the following XML commands so that I can "extract" the tag value for Daniel and George. I want the answer to look like Daniel = 78, George = 90. <epas:property name="Tom">12</epas:property> <epas:property name="Alice">...
[ "Don't use xml.dom.minidom, it's a terrible library! Use ElementTree or lxml (ElementTree is in the standard library and will probably work fine for you).\nYou should have an XML namespace, i.e., something like xmlns:epas=\"http://something\". Also you can't have bare elements, they need to be enclosed. If you h...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002968824_python.txt
Q: 2 techniques for including files in a Python distribution: which is better? I'm working on packaging a small Python project as a zip or egg file so that it can be distributed. I've come across 2 ways to include the project's config files, both of which seem to produce identical results. Method 1: Include this code...
2 techniques for including files in a Python distribution: which is better?
I'm working on packaging a small Python project as a zip or egg file so that it can be distributed. I've come across 2 ways to include the project's config files, both of which seem to produce identical results. Method 1: Include this code in setup.py: from distutils.core import setup setup(name='ProjectName', ...
[ "MANIFEST.in controls what files are put into the distribution zip file when you call python setup.py sdist. It does not control what is installed. data_files (or better package_data) controls what files are installed (and I think also makes sure files are included in the zip file). Use MANIFEST.in for files you...
[ 29 ]
[]
[]
[ "distribution", "distutils", "python" ]
stackoverflow_0002968701_distribution_distutils_python.txt
Q: Output MySQL query results in Django shell I have the following Django Model which retrieves 3 records from a database. The class below represents a Model within a Django application I'm building. I realize that the parameters taken in by the create_hotspots function are not being used. I just simplified what the ...
Output MySQL query results in Django shell
I have the following Django Model which retrieves 3 records from a database. The class below represents a Model within a Django application I'm building. I realize that the parameters taken in by the create_hotspots function are not being used. I just simplified what the code looked like previously for the purposes of ...
[ "The Victims.create_hotspots method has no return statement. What did you expect it to return?\nAlso, Victims.create_hotspots does not do a save() to save the Victims instance.\nBTW, the use of raw SQL inside a models object is often a really poor idea. You should consider making your \"poi_table\" a proper part ...
[ 3 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002969086_django_mysql_python.txt
Q: How to do a back-reference on Google AppEngine? I'm trying to access an object that is linked to by a db.ReferenceProperty in Google app engine. Here's the model's code: class InquiryQuestion(db.Model): inquiry_ref = db.ReferenceProperty(reference_class=GiftInquiry, required=True, collection_name="inquiry_ref...
How to do a back-reference on Google AppEngine?
I'm trying to access an object that is linked to by a db.ReferenceProperty in Google app engine. Here's the model's code: class InquiryQuestion(db.Model): inquiry_ref = db.ReferenceProperty(reference_class=GiftInquiry, required=True, collection_name="inquiry_ref") And I am trying to access it in the following way...
[ "Your naming conventions are a bit confusing. inquiry_ref is both your ReferenceProperty name and your back-reference collection name, so question.inquiry_ref gives you a GiftInquiry Key object, but question.inquiry_ref.inquiry_ref gives you a Query object filtered to InquiryQuestion entities.\nLet's say we have th...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0002968231_google_app_engine_python_web_applications.txt
Q: Python - a clean approach to this problem? I am having trouble picking the best data structure for solving a problem. The problem is as below: I have a nested list of identity codes where the sublists are of varying length. li = [['abc', 'ghi', 'lmn'], ['kop'], ['hgi', 'ghy']] I have a file with two entries on e...
Python - a clean approach to this problem?
I am having trouble picking the best data structure for solving a problem. The problem is as below: I have a nested list of identity codes where the sublists are of varying length. li = [['abc', 'ghi', 'lmn'], ['kop'], ['hgi', 'ghy']] I have a file with two entries on each line; an identity code and a number. abc ...
[ "You can read the file into a dictionary (string=>int), then use a list comprehension to get the highest identity code from each sublist.\nd = {}\nwith open(\"data\", 'rb') as data:\n for line in data:\n key, val = line.split(' ')\n d[key] = float(val)\n\nids = [max(sublist, key=lambda k: d[k]) for sublist i...
[ 4, 2, 0 ]
[]
[]
[ "data_structures", "file", "python" ]
stackoverflow_0002958799_data_structures_file_python.txt
Q: What c# equivalent encoding does Python's hash.digest() use? I am trying to port a python program to c#. Here is the line that's supposed to be a walkthrough but is currently tormenting me: hash = hashlib.md5(inputstring).digest() After generating a similar MD5 hash in c# It is absolutely vital that I create a si...
What c# equivalent encoding does Python's hash.digest() use?
I am trying to port a python program to c#. Here is the line that's supposed to be a walkthrough but is currently tormenting me: hash = hashlib.md5(inputstring).digest() After generating a similar MD5 hash in c# It is absolutely vital that I create a similar hash string as the original python program or my whole appli...
[ "I presume you're using an earlier version of Python than 3, and your string is a normal str.\nIf you're talking about the output, the digest method returns a string consisting on raw bytes . The equivalent type in C# is byte[], which you already seem to have. It's not text, so using the Encoding class makes no sen...
[ 5, 2, 0 ]
[]
[]
[ "c#", "digest", "encoding", "python" ]
stackoverflow_0002969492_c#_digest_encoding_python.txt
Q: EOF error using recv in python I am doing this in my code, HOST = '192.168.1.3' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) query_details = {"page" : page, "query" : query, "type" : type} s.send(str(query_details)) #data = eval(pickle.loads(s.recv(40...
EOF error using recv in python
I am doing this in my code, HOST = '192.168.1.3' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) query_details = {"page" : page, "query" : query, "type" : type} s.send(str(query_details)) #data = eval(pickle.loads(s.recv(4096))) data = s.recv(16384) But I am...
[ "s.send is not guaranteed to send every byte you give it; use s.sendall instead.\nSimilarly, s.recv is not guaranteed to receive every byte you ask -- in that case you need to know by other ways exactly how many bytes you need to receive (e.g., send first the length of the string you're sending, encoded with the st...
[ 8 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002969509_python_sockets.txt
Q: A means to access my db in python - what is my problem afterall? I have a remote database (at the moment sqlite, but eventually mysql) that I want to be able to call from a webpage dynamically. Basically to query for data that will populate goog viz charts etc on the page (and possibly images). I have a small, slo...
A means to access my db in python - what is my problem afterall?
I have a remote database (at the moment sqlite, but eventually mysql) that I want to be able to call from a webpage dynamically. Basically to query for data that will populate goog viz charts etc on the page (and possibly images). I have a small, slow server that i can basically run anything on. I've also located the p...
[ "The first thing you'll need to do is deploy a web server (apache is a common choice).\nOnce your server is running, you can test it by pushing simple HTML files to it and make sure they are accessible to you from a browser.\nOnce your server is properly configured, you have a number of options available for interf...
[ 2 ]
[]
[]
[ "django", "pylons", "python", "web_services" ]
stackoverflow_0002969640_django_pylons_python_web_services.txt
Q: How to use HTTP method DELETE on Google App Engine? I can use this verb in the Python Windows SDK. But not in production. Why? What am I doing wrong? The error message includes (only seen via firebug or fiddler) Malformed request or something like that My code looks like: from google.appengine.ext import db from...
How to use HTTP method DELETE on Google App Engine?
I can use this verb in the Python Windows SDK. But not in production. Why? What am I doing wrong? The error message includes (only seen via firebug or fiddler) Malformed request or something like that My code looks like: from google.appengine.ext import db from google.appengine.ext import webapp class Handler(webapp...
[ "Your handler looks OK, are you sure you're sending the request correctly? Using jQuery, this works for me (both using dev_appserver and google app engine production):\n$('#delete-button').click(function() {\n $.ajax({\n 'type': 'DELETE',\n 'url': '/some/url/that/handles/delete'\n })\n});\n\ncla...
[ 3 ]
[]
[]
[ "google_app_engine", "http", "http_delete", "python" ]
stackoverflow_0002398012_google_app_engine_http_http_delete_python.txt
Q: How do i send a file with sockets in python? I am already familiar with python and socket usage and can send strings of text over these. But how would i go about sending, say, an MP3 file? A: The following code would do what you literally ask (assuming thesocket is a connected stream socket): with open('thefile....
How do i send a file with sockets in python?
I am already familiar with python and socket usage and can send strings of text over these. But how would i go about sending, say, an MP3 file?
[ "The following code would do what you literally ask (assuming thesocket is a connected stream socket):\nwith open('thefile.mp3', 'rb') as f:\n thesocket.sendall(f.read())\n\nbut of course it's unlikely to be much use without some higher-level protocol to help the counterpart know how much data it's going to rece...
[ 1 ]
[]
[]
[ "mp3", "networking", "python", "send", "sockets" ]
stackoverflow_0002970019_mp3_networking_python_send_sockets.txt
Q: php equivalent to jython? i wonder if there is a php equivalent to jython so you can use java classes with php? thanks A: http://www.caucho.com/resin-3.0/quercus/ http://php-java-bridge.sourceforge.net/pjb/ A: I'm not quite sure what you are asking, since you are talking about two completely different things: ...
php equivalent to jython?
i wonder if there is a php equivalent to jython so you can use java classes with php? thanks
[ "http://www.caucho.com/resin-3.0/quercus/\nhttp://php-java-bridge.sourceforge.net/pjb/\n", "I'm not quite sure what you are asking, since you are talking about two completely different things: a PHP equivalent to Jython, and accessing Java classes from PHP. So, I'm going to answer both.\nJython is a Python implem...
[ 7, 5, 1, 1, 1 ]
[]
[]
[ "java", "jython", "php", "python" ]
stackoverflow_0002968381_java_jython_php_python.txt
Q: CherryPy configuration for CSS file access The following is the result of CherryPy and css pathing problems I have recently posted, both of which have been answered, but another problem has arisen. I have a html page which I preview in a browser (via. editor/IDE) and which calls a css file from a css folder in par...
CherryPy configuration for CSS file access
The following is the result of CherryPy and css pathing problems I have recently posted, both of which have been answered, but another problem has arisen. I have a html page which I preview in a browser (via. editor/IDE) and which calls a css file from a css folder in parallel with my application folder (containing mai...
[ "\nbut no other staticdir declarations\n because CP should be looking for\n ..\\css\\commoncss.css relative to the\n static root folder (am I right?)\n\nYou can't reach into your physical file directory (static dir) via URLs, nor should you want to.\nCherrypy is looking for the css file relative to your HTML fil...
[ 1 ]
[]
[]
[ "cherrypy", "configuration", "css", "python" ]
stackoverflow_0002970767_cherrypy_configuration_css_python.txt
Q: Change embedded image type in APIC ID3 tag via Mutagen I have a large music library which I have just spent around 30 hours organizing. For some of the MP3 files, I embedded the cover art image as type 0 (Other) and I'd like to change it to type 3 (Front Cover). Is there a way to do this in Python, specifically in...
Change embedded image type in APIC ID3 tag via Mutagen
I have a large music library which I have just spent around 30 hours organizing. For some of the MP3 files, I embedded the cover art image as type 0 (Other) and I'd like to change it to type 3 (Front Cover). Is there a way to do this in Python, specifically in Mutagen?
[ "Here's how I was able to pull it off.\nFirst, get access to the file in Mutagen:\naudio = MP3(\"filename.mp3\")\n\nThen, get a reference to the tag you're looking for:\npicturetag = audio.tags['APIC:Folder.jpg']\n\nThen, modify the type attribute:\npicturetag.type = 3\n\nThen, assign it back into the audio file, j...
[ 8 ]
[]
[]
[ "apic", "id3", "mp3", "mutagen", "python" ]
stackoverflow_0002970473_apic_id3_mp3_mutagen_python.txt
Q: Is processing a dead project? Look at the last updated release, Python 2.5?? http://pypi.python.org/pypi/processing A: It became multiprocessing.
Is processing a dead project?
Look at the last updated release, Python 2.5?? http://pypi.python.org/pypi/processing
[ "It became multiprocessing.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002970871_python.txt
Q: win32com equivalent of xlrd's sheet.ncols xlrd makes it pretty easy to know what the last column is. is there an easy way using win32com? I have tried using ws.UsedRange.Rows.Count but this doesnt seem to give a correct answer. A: That's defined to give the count of rows in the used range (which may not start at...
win32com equivalent of xlrd's sheet.ncols
xlrd makes it pretty easy to know what the last column is. is there an easy way using win32com? I have tried using ws.UsedRange.Rows.Count but this doesnt seem to give a correct answer.
[ "That's defined to give the count of rows in the used range (which may not start at cell A1). You need the number of columns in the worksheet.\nTry something like this:\nused = ws.UsedRange\nnrows = used.Row + used.Rows.Count - 1\nncols = used.Column + used.Columns.Count - 1\n\n" ]
[ 6 ]
[]
[]
[ "com", "excel", "python", "win32com", "xlrd" ]
stackoverflow_0002968830_com_excel_python_win32com_xlrd.txt
Q: best way to form Validation on gae (1) is this way : http://code.google.com/intl/en/appengine/articles/djangoforms.html (2) is write by self : #/usr/bin/env python2.5 #---------------------------- # Datastore models for user & signup #---------------------------- from base64 import b64encode as b64 from hashlib i...
best way to form Validation on gae
(1) is this way : http://code.google.com/intl/en/appengine/articles/djangoforms.html (2) is write by self : #/usr/bin/env python2.5 #---------------------------- # Datastore models for user & signup #---------------------------- from base64 import b64encode as b64 from hashlib import md5, sha256 from random import ran...
[ "If you're using Django, djangoforms is definitely the way to go. If tipfy or other light-weight frameworks, try wtforms (it's also in the tipfy source tree).\n" ]
[ 1 ]
[]
[]
[ "forms", "google_app_engine", "python", "validation" ]
stackoverflow_0002971093_forms_google_app_engine_python_validation.txt
Q: Unexpected Blank lines in python output I have a bit of code that runs through a dictionary and outputs the values from it in a CSV format. Strangely I'm getting a couple of blank lines where all the output of all of the dictionary entries is blank. I've read the code and can't understand has anything except lin...
Unexpected Blank lines in python output
I have a bit of code that runs through a dictionary and outputs the values from it in a CSV format. Strangely I'm getting a couple of blank lines where all the output of all of the dictionary entries is blank. I've read the code and can't understand has anything except lines with commas can be output. The blank line...
[ "Why are you not using Python's built-in csv module?\nThen, what does self.derive_pkeys(value) do? Could it be that b_pkey sometimes ends with \\n?\n", "without seeing the source data it is hard to tell, but I could speculate that your data has some stray \\n characters in it, like in b_pkey . You could try and d...
[ 3, 1, 1 ]
[]
[]
[ "csv", "file", "python" ]
stackoverflow_0002971804_csv_file_python.txt
Q: Python iteration I'm trying to do a simple script in Python that will print hex values and increment value like this: char = 0 char2 = 0 def doublehex(): global char,char2 for x in range(255): char = char + 1 a = str(chr(char)).encode("hex") for p in range(255): char2...
Python iteration
I'm trying to do a simple script in Python that will print hex values and increment value like this: char = 0 char2 = 0 def doublehex(): global char,char2 for x in range(255): char = char + 1 a = str(chr(char)).encode("hex") for p in range(255): char2 = char2 + 1 ...
[ "for x in xrange(256):\n for y in xrange(256):\n print '%02x %02x' % (x, y)\n\n", "You need to set char2 = 0 before\nfor p in range(255):\n\nAnd actually, you don't need counters - char,char2\nFollowing will work from 0 to ff\nfor x in range(256):\n for p in range(256):\n print chr(x).encode(\...
[ 6, 4, 1, 1, 0, 0 ]
[]
[]
[ "for_loop", "hex", "increment", "loops", "python" ]
stackoverflow_0002972048_for_loop_hex_increment_loops_python.txt
Q: python date appears in last year How do I do a check in python that a date appears in the last year. i.e. date between now and (now-1 year) Thanks A: In [10]: today=datetime.date.today() In [11]: datetime.date(2010,5,5) < today Out[11]: True In [12]: today-datetime.timedelta(days=365) <= datetime.date(2010,5,5...
python date appears in last year
How do I do a check in python that a date appears in the last year. i.e. date between now and (now-1 year) Thanks
[ "In [10]: today=datetime.date.today()\n\nIn [11]: datetime.date(2010,5,5) < today\nOut[11]: True\n\nIn [12]: today-datetime.timedelta(days=365) <= datetime.date(2010,5,5) < today\nOut[12]: True\n\nIn [13]: today-datetime.timedelta(days=365) <= datetime.date(2009,5,5) < today\nOut[13]: False\n\nEdit: if today is the...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002972742_python.txt
Q: pydev 1.5.3 not working fine with Easy Eclipse 1.3.1 I installed Pydev 1.5.3 (so that I could get the merged version of Pydev Extensions in core PyDev) in an EasyEclipse 1.3.1 installation. After this, Compare with > Base revision etc. comparison operations stopped working. I had to disable the PyDev 1.5.3 and rev...
pydev 1.5.3 not working fine with Easy Eclipse 1.3.1
I installed Pydev 1.5.3 (so that I could get the merged version of Pydev Extensions in core PyDev) in an EasyEclipse 1.3.1 installation. After this, Compare with > Base revision etc. comparison operations stopped working. I had to disable the PyDev 1.5.3 and revert back to the pre-installed Pydev 1.3.13 (part of EasyEc...
[ "My pydev broke entirely with 1.5.3.\nI had to downgrade yum downgrade eclipse-pydev and keep yum from updating it ever since.\n", "I am now using PyDev 1.5.6 and its working fine with EasyEclipse (along with SubClipse). The issues in comparison seem to have been resolved. In fact, the file diff in 1.5.6 is looki...
[ 0, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0001938929_eclipse_pydev_python.txt
Q: django basic pagination problem i have a microblog app, and i'm trying to paginate the entries, to show only 10 per page, for example. though i've followed the tutorial, my pagination doesn't seem t be working. the listing function looks like that: def listing(request): blog_list = Blog.objects.all() pagin...
django basic pagination problem
i have a microblog app, and i'm trying to paginate the entries, to show only 10 per page, for example. though i've followed the tutorial, my pagination doesn't seem t be working. the listing function looks like that: def listing(request): blog_list = Blog.objects.all() paginator = Paginator(blog_list, 10) t...
[ "You can use django-pagination which makes it possible to implement pagination without writing a single line of Python code, you only pass list of all objects to template (i.e. blog_list = Blog.objects.all() in your case), and then use three tags in you template:\n {% load pagination_tags %}\n {% autopaginate blog_...
[ 6, 5 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0002973151_django_pagination_python.txt
Q: Can anyone figure out my problem [Python] I have been trying to debug the below python cgi code but doesn't seems to work. When i try in new file it these three lines seems to work filename=unique_file('C:/wamp/www/project/input.fasta') prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(su...
Can anyone figure out my problem [Python]
I have been trying to debug the below python cgi code but doesn't seems to work. When i try in new file it these three lines seems to work filename=unique_file('C:/wamp/www/project/input.fasta') prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname) But, when i try lik...
[ "unique_file() isn't a built-in function of Python. So I assume, either you forget a line in your first code snippet which actually imports this function, or you configured your python interpreter to load a startup file (http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP). In the second case, the CGI s...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002973545_python.txt
Q: Django chat with ajax polling I need to create a chat similar to facebook chat. I am thinking to create a simple application Chat and then using ajax polling ( to send request every 2-3 seconds ). Is this a good approach ? A: I'd go with something that involves push/real-time messaging controlled by the server. ...
Django chat with ajax polling
I need to create a chat similar to facebook chat. I am thinking to create a simple application Chat and then using ajax polling ( to send request every 2-3 seconds ). Is this a good approach ?
[ "I'd go with something that involves push/real-time messaging controlled by the server. You'll get proper real-time chat and it will scale a lot better. Take a look at http://www.orbited.org/ which is the way to go, I reckon. It's not core django, but it's Python and will sit well alongside a Django app on your ser...
[ 6, 0 ]
[]
[]
[ "ajax", "chat", "comet", "django", "python" ]
stackoverflow_0002973591_ajax_chat_comet_django_python.txt
Q: Reorganizing many to many relationships in Django I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages. My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to t...
Reorganizing many to many relationships in Django
I have a many to many relationship in my models and i'm trying to reorganize it on one of my pages. My site has videos. On each video's page i'm trying to list the actors that are in that video with links to each time they are in the video(the links will skip to that part of the video) Here's an illustration Flash Vi...
[ "I think the most Django-ish way of doing this would be using the \"regroup\" template tag:\n{% regroup video.actor_video_set.all by actor as video_times %}\n{% for actor_times in video_times %}\n <li>{{ actor_times.grouper }}: # this will output the actor's name\n {% for time in actor_times %}\n <li>{...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0002893198_django_django_templates_django_views_python.txt
Q: Python - Launch a Long Running Process from a Web App I have a python web application that needs to launch a long running process. The catch is I don't want it to wait around for the process to finish. Just launch and finish. I'm running on windows XP, and the web app is running under IIS (if that matters). So f...
Python - Launch a Long Running Process from a Web App
I have a python web application that needs to launch a long running process. The catch is I don't want it to wait around for the process to finish. Just launch and finish. I'm running on windows XP, and the web app is running under IIS (if that matters). So far I tried popen but that didn't seem to work. It waited u...
[ "Ok, I finally figured this out! This seems to work:\nfrom subprocess import Popen\nfrom win32process import DETACHED_PROCESS\n\npid = Popen([\"C:\\python24\\python.exe\", \"long_run.py\"],creationflags=DETACHED_PROCESS,shell=True).pid\nprint pid\nprint 'done' \n#I can now close the console or anything I want and ...
[ 7, 2, 1, 0 ]
[]
[]
[ "long_running_processes", "popen", "python", "winapi", "windows" ]
stackoverflow_0002970045_long_running_processes_popen_python_winapi_windows.txt
Q: can WTForms check two password is or not same when someone register WTForms is a forms validation and rendering library for python web development and i write this code to check two password is or not same : from wtforms import Form, BooleanField, TextField, validators class SignUpForm(Form): username =...
can WTForms check two password is or not same when someone register
WTForms is a forms validation and rendering library for python web development and i write this code to check two password is or not same : from wtforms import Form, BooleanField, TextField, validators class SignUpForm(Form): username = TextField('Username', [validators.Length(min=4, max=25)]) email = Tex...
[ "use wtforms.validators.EqualTo.\nIt took less than a minute to find this in TFM, having never used this library before.\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "passwords", "python" ]
stackoverflow_0002973149_google_app_engine_passwords_python.txt
Q: What kind of data do I pass into a Django Model.save() method? Lets say that we are getting POSTed a form like this in Django: rate=10 items= [23,12,31,52,83,34] The items are primary keys of an Item model. I have a bunch of business logic that will run and create more items based on this data, the results of som...
What kind of data do I pass into a Django Model.save() method?
Lets say that we are getting POSTed a form like this in Django: rate=10 items= [23,12,31,52,83,34] The items are primary keys of an Item model. I have a bunch of business logic that will run and create more items based on this data, the results of some db lookups, and some business logic. I want to put that logic into...
[ "OK so the first two answers I got have now been contradicted by others. I've been researching this and I'm going to take a stab at answering it myself. Please vote if you think this is correct and/or comment if you disagree with my reasoning.\n\nMethods on models should accept objects and lists of objects, not ids...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002947397_django_django_models_python.txt
Q: Using NetBeans for Python GUI development Is NetBeans recommended for developing a GUI for a Python app? Does it have a form/screen builder for Python apps, like Dabo? A: Although it isn't "built-in" to Netbeans, I've found Qt Designer to be an excellent tool for building GUIs for Python. Of course, this only ...
Using NetBeans for Python GUI development
Is NetBeans recommended for developing a GUI for a Python app? Does it have a form/screen builder for Python apps, like Dabo?
[ "Although it isn't \"built-in\" to Netbeans, I've found Qt Designer to be an excellent tool for building GUIs for Python. Of course, this only works if you're using PyQt or PySide but it's kept me quite happy for years. According to the Netbeans Docs, integrated Qt Designer support is available. I haven't tried it ...
[ 4, 2, 0 ]
[ "Is Google broken?\nThere's the first hit I got from Googling \"Netbeans Python\"\nhttp://netbeans.org/features/python/index.html\nI don't know what kind of \"recommendation\" you're looking for, but it's certainly supported. \n" ]
[ -1 ]
[ "netbeans", "python" ]
stackoverflow_0002971094_netbeans_python.txt
Q: Python - making counters, making loops? I am having some trouble with a piece of code below: Input: li is a nested list as below: li = [['>0123456789 mouse gene 1\n', 'ATGTTGGGTT/CTTAGTTG\n', 'ATGGGGTTCCT/A\n'], ['>9876543210 mouse gene 2\n', 'ATTTGGTTTCCT\n', 'ATTCAATTTTAAGGGGGGGG\n']] Using the function below...
Python - making counters, making loops?
I am having some trouble with a piece of code below: Input: li is a nested list as below: li = [['>0123456789 mouse gene 1\n', 'ATGTTGGGTT/CTTAGTTG\n', 'ATGGGGTTCCT/A\n'], ['>9876543210 mouse gene 2\n', 'ATTTGGTTTCCT\n', 'ATTCAATTTTAAGGGGGGGG\n']] Using the function below, my desired output is simply the 2nd to the ...
[ "Your indentation is possibly wrong, you should check count > 1 within the for j in i loop, not within the one that checks every single character in j[1:].\nAlso, here's a much easier way to do the same thing:\ndef count_slashes(items):\n return sum(item.count('/') for item in items)\n\nfor item in li:\n if c...
[ 9, 8, 0 ]
[]
[]
[ "counter", "loops", "python" ]
stackoverflow_0002973926_counter_loops_python.txt
Q: reading floating-point numbers with 1.#QNAN values in python Does anyone know of a python string-to-float parser that can cope with MSVC nan numbers (1.#QNAN)? Currently I'm just using float(str) which at least copes with "nan". I'm using a python script to read the output of a C++ program (runs under linux/mac/wi...
reading floating-point numbers with 1.#QNAN values in python
Does anyone know of a python string-to-float parser that can cope with MSVC nan numbers (1.#QNAN)? Currently I'm just using float(str) which at least copes with "nan". I'm using a python script to read the output of a C++ program (runs under linux/mac/win platforms) and the script barfs up when reading these values. (I...
[ "Since you have to deal with legacy output files, I see no other possibility but writing a robust_float function:\ndef robust_float(s):\n try:\n return float(s)\n except ValueError:\n if 'nan' in s.lower():\n return float('nan')\n else:\n raise\n\n" ]
[ 2 ]
[]
[]
[ "cross_platform", "nan", "python", "visual_c++" ]
stackoverflow_0002974124_cross_platform_nan_python_visual_c++.txt
Q: Available disk space on an SMB share, via Python Does anyone know a way to get the amount of space available on a Windows (Samba) share via Python 2.6 with its standard library? (also running on Windows) e.g. >>> os.free_space("\\myshare\folder") # return free disk space, in bytes 1234567890 A: If PyWin32 is ava...
Available disk space on an SMB share, via Python
Does anyone know a way to get the amount of space available on a Windows (Samba) share via Python 2.6 with its standard library? (also running on Windows) e.g. >>> os.free_space("\\myshare\folder") # return free disk space, in bytes 1234567890
[ "If PyWin32 is available:\nfree, total, totalfree = win32file.GetDiskFreeSpaceEx(r'\\\\server\\share')\n\nWhere free is a amount of free space available to the current user, and totalfree is amount of free space total. Relevant documentation: PyWin32 docs, MSDN.\nIf PyWin32 is not guaranteed to be available, then f...
[ 8, 0 ]
[]
[]
[ "python", "samba", "windows" ]
stackoverflow_0002973480_python_samba_windows.txt
Q: Multiple Objects of the same class in Python I have a bunch of Objects from the same Class in Python. I've decided to put each object in a different file since it's easier to manage them (If I plan to add more objects or edit them individually) However, I'm not sure how to run through all of them, they are in a...
Multiple Objects of the same class in Python
I have a bunch of Objects from the same Class in Python. I've decided to put each object in a different file since it's easier to manage them (If I plan to add more objects or edit them individually) However, I'm not sure how to run through all of them, they are in another Package So if I look at Netbeans I have To...
[ "It seems that you're misunderstanding the Python jargon. The Python term \"object\" means an actual run-time instance of a class. As far as I can tell, you have \"sub-classes\" of the Shape class called ball, circle and triangle. Note that a sub-class is also a class. You are keeping the code for each such sub-cla...
[ 2, 0 ]
[]
[]
[ "oop", "package", "python" ]
stackoverflow_0002974604_oop_package_python.txt
Q: Does Python copy value or reference upon object instantiation? A simple question, perhaps, but I can't quite phrase my Google query to find the answer here. I've had the habit of making copies of objects when I pass them into object constructors, like so: ... def __init__(self, name): self._name = name[:] ... ...
Does Python copy value or reference upon object instantiation?
A simple question, perhaps, but I can't quite phrase my Google query to find the answer here. I've had the habit of making copies of objects when I pass them into object constructors, like so: ... def __init__(self, name): self._name = name[:] ... However, when I ran the following test code, it appears to not be n...
[ "It is because strings are immutable.\nThe operator +=, rather confusingly, actually reassigns the variable it is applied to, if the object is immutable:\ns = 'a'\nids = id(s)\ns += 'b'\nids == id(s) # False, because s was reassigned to a new object\n\nSo, in your case, in the beginning, both flav and a.flavor poin...
[ 14, 1 ]
[]
[]
[ "instantiation", "language_design", "object", "python" ]
stackoverflow_0002974679_instantiation_language_design_object_python.txt
Q: Why is win32com so much slower than xlrd? I have the same code, written using win32com and xlrd. xlrd preforms the algorithm in less than a second, while win32com takes minutes. Here is the win32com: def makeDict(ws): """makes dict with key as header name, value as tuple of column begin and column end (inclusi...
Why is win32com so much slower than xlrd?
I have the same code, written using win32com and xlrd. xlrd preforms the algorithm in less than a second, while win32com takes minutes. Here is the win32com: def makeDict(ws): """makes dict with key as header name, value as tuple of column begin and column end (inclusive)""" wsHeaders = {} # key is header name, val...
[ "(0) You asked \"Why is win32com so much slower than xlrd?\" ... this question is a bit like \"Have you stopped beating your wife?\" --- it is based on a presupposition that may not be true; win32com was written in C by a brilliant programmer, but xlrd was written in pure Python by an average programmer. The real d...
[ 12, 2, 0 ]
[]
[]
[ "python", "win32com", "xlrd" ]
stackoverflow_0002969225_python_win32com_xlrd.txt
Q: include udf in python? i've a small user defined function in python, say fib(n), how do i use that in other programs or modules? def fib(n): should i use import or is there any other feature? Also i'm learning python in eclipse IDE, it wont support print "any string" but i'm forced to use like, print("string") ...
include udf in python?
i've a small user defined function in python, say fib(n), how do i use that in other programs or modules? def fib(n): should i use import or is there any other feature? Also i'm learning python in eclipse IDE, it wont support print "any string" but i'm forced to use like, print("string") in python manual online, it...
[ "You use import to include the function in other programs. Just say import mymodule where the code is located in file mymodule.py. Then say mymodule.fib to use the function.\nTo answer your second question: The syntax print \"any string\" is acceptable in Python 2, but is no longer allowed in Python 3.\n" ]
[ 2 ]
[]
[]
[ "cross_platform", "import", "python" ]
stackoverflow_0002975473_cross_platform_import_python.txt
Q: Is Django double encoding a Unicode (utf-8?) string? I'm having trouble storing and outputting an ndash character as UTF-8 in Django. I'm getting data from an API. In raw form, as retrieved and viewed in a text editor, given unit of data may be similar to: "I love this detergent \u2013 it is so inspiring." (\u20...
Is Django double encoding a Unicode (utf-8?) string?
I'm having trouble storing and outputting an ndash character as UTF-8 in Django. I'm getting data from an API. In raw form, as retrieved and viewed in a text editor, given unit of data may be similar to: "I love this detergent \u2013 it is so inspiring." (\u2013 is & ndash; as an html entity). If I get this straight ...
[ "This does seem like a case of double-encoding; I don't have much experience with Python, but try adjusting the MySQL connection settings as per the advice at http://tahpot.blogspot.com/2005/06/mysql-and-python-and-unicode.html\nWhat I'm guessing is happening is that the connection is latin1, so MySQL tries to enco...
[ 1, 0 ]
[]
[]
[ "django", "mysql", "python", "unicode", "utf_8" ]
stackoverflow_0002971634_django_mysql_python_unicode_utf_8.txt
Q: Is twisted any good? I keep hearing all this hype about Twisted for python, but i just find it plain confusing. What do you think is more simple to use? Simple sockets or implementing twisted ? A: I stand by what I wrote in Python in a Nutshell (2nd edition p. 540): Twisted includes powerful, high-level compo...
Is twisted any good?
I keep hearing all this hype about Twisted for python, but i just find it plain confusing. What do you think is more simple to use? Simple sockets or implementing twisted ?
[ "I stand by what I wrote in Python in a Nutshell (2nd edition p. 540):\n\nTwisted includes powerful, high-level\n components such as web servers, user\n authentication systems, mail servers\n and clients, instant messaging, SSH\n clients and servers, a DNS server and\n client, and so on, as well as the\n lowe...
[ 30, 4, 3, 0 ]
[]
[]
[ "python", "sockets", "twisted" ]
stackoverflow_0002974781_python_sockets_twisted.txt
Q: python facebook api in linux? How do i install package and libraries of facebook api? When i use import facebook, there's error? I see only svn checkouts, some files are empty, how do i download and get them working? A: If you don't have git, probably the easiest way to download it is to go to http://github.c...
python facebook api in linux?
How do i install package and libraries of facebook api? When i use import facebook, there's error? I see only svn checkouts, some files are empty, how do i download and get them working?
[ "If you don't have git, probably the easiest way to download it is to go to http://github.com/sciyoshi/pyfacebook and click on the \"Download source\" button. Extract the downloaded ZIP to a subdirectory, enter that subdirectory, launch your Python interpreter and type import facebook. It works for me.\n", "Start...
[ 2, 1 ]
[]
[]
[ "facebook", "installation", "python" ]
stackoverflow_0002975582_facebook_installation_python.txt
Q: Working with multiple excel workbooks in python Using win32com, I have two workbooks open. How do you know which one is active? How do you change which one is active? How can you close one and not the other? (not Application.Quit()) A: What is your larger goal here? Automate already open excel windows or simpl...
Working with multiple excel workbooks in python
Using win32com, I have two workbooks open. How do you know which one is active? How do you change which one is active? How can you close one and not the other? (not Application.Quit())
[ "What is your larger goal here? Automate already open excel windows or simply write XLS files? If it's the latter you should use consider using xlwt.\n\nHow do you know which one is active?\n\nxl = win32com.client.Dispatch(\"Excel.Application\")\nwbOne = xl.Workbooks.Add()\nwbTwo = xl.Workbooks.Add()\nxl.ActiveWo...
[ 6 ]
[]
[]
[ "com", "excel", "python", "win32com" ]
stackoverflow_0002975777_com_excel_python_win32com.txt
Q: Is Python programming for Logitech G15 possible? I have a Logitech G15 keyboard. It has a screen. Can i program this? I googled it but the one site i found didn't work.. It seems like it is possible, but i cannot grasp how. Thanks! This site is truly great. A: I believe the G15 comes with an SDK. You could use t...
Is Python programming for Logitech G15 possible?
I have a Logitech G15 keyboard. It has a screen. Can i program this? I googled it but the one site i found didn't work.. It seems like it is possible, but i cannot grasp how. Thanks! This site is truly great.
[ "I believe the G15 comes with an SDK. You could use that along with the ctypes module to call into the supplied DLLs. Otherwise, I imagine you'd have to use something like Swig or Boost.Python to make a Python module for the G15 from the SDK.\n", "It seems to be programmable even with bash shell: http://www.g15-a...
[ 6, 3 ]
[]
[]
[ "g15", "logitech", "python" ]
stackoverflow_0002976446_g15_logitech_python.txt
Q: Why does output of fltk-config truncate arguments to gcc? I'm trying to build an application I've downloaded which uses the SCONS "make replacement" and the Fast Light Tool Kit Gui. The SConstruct code to detect the presence of fltk is: guienv = Environment(CPPFLAGS = '') guiconf = Configure(guienv) if not guicon...
Why does output of fltk-config truncate arguments to gcc?
I'm trying to build an application I've downloaded which uses the SCONS "make replacement" and the Fast Light Tool Kit Gui. The SConstruct code to detect the presence of fltk is: guienv = Environment(CPPFLAGS = '') guiconf = Configure(guienv) if not guiconf.CheckLibWithHeader('lo', 'lo/lo.h','c'): print 'Did not f...
[ "This is quite a complex problem with no quick answer\nI have referred to the instructions for using pkg-config with scons at http://www.scons.org/wiki/UsingPkgConfig. The following question is also helpful\nTest if executable exists in Python?.\nBut we need to go a little bit further with these.\nSo after much inv...
[ 1, 1 ]
[]
[]
[ "c", "c++", "fltk", "python", "scons" ]
stackoverflow_0002945877_c_c++_fltk_python_scons.txt
Q: Binary search of unaccesible data field in ldap from python I'm interested in reproducing a particular python script. I have a friend who was accessing an ldap database, without authentication. There was a particular field of interest, we'll call it nin (an integer) for reference, and this field wasn't accessible ...
Binary search of unaccesible data field in ldap from python
I'm interested in reproducing a particular python script. I have a friend who was accessing an ldap database, without authentication. There was a particular field of interest, we'll call it nin (an integer) for reference, and this field wasn't accessible without proper authentication. However, my friend managed to acce...
[ "Your best bet would be to get authorization to access that field. You are circumventing the security of the database otherwise.\n", "Figured it out. I just needed to filter on (&(cn=My name)(nin=guess*) and I managed to filter until it returns the correct result.\nCode follows in case anyone else needs to find ...
[ 0, 0 ]
[]
[]
[ "ldap", "python" ]
stackoverflow_0002968127_ldap_python.txt
Q: How to resolve bindings during execution with embedded Python? I'm embedding Python into a C++ application. I plan to use PyEval_EvalCode to execute Python code, but instead of providing the locals and globals as dictionaries, I'm looking for a way to have my program resolve symbol references dynamically. For e...
How to resolve bindings during execution with embedded Python?
I'm embedding Python into a C++ application. I plan to use PyEval_EvalCode to execute Python code, but instead of providing the locals and globals as dictionaries, I'm looking for a way to have my program resolve symbol references dynamically. For example, let's say my Python code consists of the following expressio...
[ "Possibly. I've never tried this but in theory you might be able to implement a small extension class in C++ that overrides the __getattr__ method (probably via the tp_as_mapping or tp_getattro function pointers of PyTypeObject). Pass an instance of this as locals and/or globals to PyEval_EvalCode and your C++ meth...
[ 1, 1 ]
[]
[]
[ "dynamic_binding", "python", "python_embedding" ]
stackoverflow_0002976698_dynamic_binding_python_python_embedding.txt
Q: What options are there for visualising class relationships in a Python program I am maintaining a Python program, and am struggling to understand the relationships between the various classes. I think it would be helpful to see a diagram of how the classes interact. What options are there available that might allo...
What options are there for visualising class relationships in a Python program
I am maintaining a Python program, and am struggling to understand the relationships between the various classes. I think it would be helpful to see a diagram of how the classes interact. What options are there available that might allow me to do this?
[ "Just my 2 cents.\nCase tools like Enterprise Architect can generate class diagrams from python code, however for the purpose of understanding I prefer to coarsely model the classes and relationships by hand.\nI too use UML when I want to understand new code, to get a coarse overview of the collaborations between c...
[ 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "class_design", "python", "uml" ]
stackoverflow_0002972198_class_design_python_uml.txt
Q: Python function argument scope (Dictionaries v. Strings) foo = "foo" def bar(foo): foo = "bar" bar(foo) print foo # foo is still "foo"... foo = {'foo':"foo"} def bar(foo): foo['foo'] = "bar" bar(foo) print foo['foo'] # foo['foo'] is now "bar"? I have a function that has been inadvertently ove...
Python function argument scope (Dictionaries v. Strings)
foo = "foo" def bar(foo): foo = "bar" bar(foo) print foo # foo is still "foo"... foo = {'foo':"foo"} def bar(foo): foo['foo'] = "bar" bar(foo) print foo['foo'] # foo['foo'] is now "bar"? I have a function that has been inadvertently over-writing my function parameters when I pass a dictionary. Is ...
[ "In a case like this, you'd have to copy the dictionary if you want to change it and keep the changes local to the function.\nThe reason is that, when you pass a dictionary into your second bar function, Python only passes a reference to the dictionary. So when you modify it inside the function, you're modifying th...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002951112_python.txt
Q: Python, MySQL and Daemon Problem in Ubuntu 10.04 I have a script which runs inside a while loop and monitors a mysql data source every 2 seconds. If I run if from the command line, it runs and works fine. But If I attach it to a daemon, it throws an error saying "MySQL has gone" or something similar. I checked and...
Python, MySQL and Daemon Problem in Ubuntu 10.04
I have a script which runs inside a while loop and monitors a mysql data source every 2 seconds. If I run if from the command line, it runs and works fine. But If I attach it to a daemon, it throws an error saying "MySQL has gone" or something similar. I checked and found MySQL up and running. I could even execute quer...
[ "I haven't worked with Python, but it almost seems you are making a database connection, then forking. The other way around should work: fork at will, then connect in remaining process, possibly in your mymain.py:main() method.\n" ]
[ 1 ]
[]
[]
[ "daemon", "mysql", "python", "ubuntu" ]
stackoverflow_0002972672_daemon_mysql_python_ubuntu.txt
Q: Anyone know a good regex to remove extra whitespace? Possible Duplicate: Substitute multiple whitespace with single whitespace in Python trying to figure out how to write a regex that given the string: "hi this is a test" I can turn it into "hi this is a test" where the whitespace is normalized to ...
Anyone know a good regex to remove extra whitespace?
Possible Duplicate: Substitute multiple whitespace with single whitespace in Python trying to figure out how to write a regex that given the string: "hi this is a test" I can turn it into "hi this is a test" where the whitespace is normalized to just one space any ideas? thanks so much
[ "import re \nre.sub(\"\\s+\",\" \",string)\n\n", "Does it need to be a regex?\nI'd just use\nnew_string = \" \".join(re.split(s'\\s+', old_string.strip()))\n\n", "sed\n sed 's/[ ]\\{2,\\}/ /g'\n\n" ]
[ 10, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002977905_python_regex.txt
Q: Call another classes method in Python I'm tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks. My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong? B...
Call another classes method in Python
I'm tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks. My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong? Brian import logging class yRunMethod(objec...
[ "I think you're making this WAY too hard on yourself (which is easy to do ;-). Methods of classes and instances are first-class objects in Python. You can pass them around and call them like anything else. Digging into a method's instance variables is something that should almost never be done. A simple example to ...
[ 11, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002976840_python.txt
Q: Live UI update of model changes when the model contains plain data structures only Please consult me with your opinions on the following topic: I have a model - a structure of the objects. Such as: Event, containing participants Current task Assignee of each task The model is going to be pickled on the server an...
Live UI update of model changes when the model contains plain data structures only
Please consult me with your opinions on the following topic: I have a model - a structure of the objects. Such as: Event, containing participants Current task Assignee of each task The model is going to be pickled on the server and transferred over the network to the client GUI application. Because of the pickle I'd ...
[ "You may be operating under a mis-conception: pickles don't include the code from classes that are pickled. You can add methods to your data structures, and it will not increase the size of your pickles.\nThis is a common misunderstanding about pickles. They don't include code.\n", "You may add a flag, e.g. sel...
[ 0, 0 ]
[]
[]
[ "architecture", "design_patterns", "python" ]
stackoverflow_0001426272_architecture_design_patterns_python.txt
Q: add xml node to xml file with python I wonder if it is better add an element by opening file, search 'good place' and add string which contains xml code. Or use some library... i have no idea. I know how can i get nodes and properties from xml through for example lxml but what's the simpliest and the best way to a...
add xml node to xml file with python
I wonder if it is better add an element by opening file, search 'good place' and add string which contains xml code. Or use some library... i have no idea. I know how can i get nodes and properties from xml through for example lxml but what's the simpliest and the best way to add?
[ "You could use lxml.etree.Element to make the xml node(s), and use append or insert to attach them into xml document:\ndata='''\\\n<root>\n<node1>\n <node2 a1=\"x1\"> ... </node2>\n <node2 a1=\"x2\"> ... </node2>\n <node2 a1=\"x1\"> ... </node2>\n</node1>\n</root>\n'''\ndoc = lxml.etree.XML(data)\ne=doc.find('no...
[ 4, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002977779_python_xml.txt
Q: Python: Mechanize and BeautifulSoup not working on a shared hosting computer I am writing a small site decorator to make my local airport site work with standard HTML. On my local computer, I use Python's mechanize and BeautifulSoup packages to scrape and parse the site contents, and everything seems to work just ...
Python: Mechanize and BeautifulSoup not working on a shared hosting computer
I am writing a small site decorator to make my local airport site work with standard HTML. On my local computer, I use Python's mechanize and BeautifulSoup packages to scrape and parse the site contents, and everything seems to work just fine. I have installed these packages via apt-get. On my shared hosting site (at D...
[ "You're using BeautifulSoup version 3.1.0 which is for Python 3.x. Use a 3.0 version of BeautifulSoup for Python 2.x.\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "shared_hosting" ]
stackoverflow_0002978205_beautifulsoup_python_shared_hosting.txt
Q: Checkstyle for Python Is there an application similar to Java's Checkstyle for Python? By which I mean, a tool that analyzes Python code and can be run as part of continuous integration (e.g. CruiseControl or Hudson). After analyzing, it should produce an online accessible report which outlines any problems found ...
Checkstyle for Python
Is there an application similar to Java's Checkstyle for Python? By which I mean, a tool that analyzes Python code and can be run as part of continuous integration (e.g. CruiseControl or Hudson). After analyzing, it should produce an online accessible report which outlines any problems found in the code. Thank you,
[ "There are actually a lot of tools:\nas other have said\n\npylint : very very strict (imho too much), yet customizable\npep-8 : very good\npychecker\npyflakes: extremely fast, perfect when used in emacs with flymake.\n\nTo format your code according to pep8 I can suggest you PythonTidy\n", "You may look at pylint...
[ 18, 6, 6, 1 ]
[]
[]
[ "coding_style", "java", "python" ]
stackoverflow_0002977866_coding_style_java_python.txt
Q: Is there a more efficient way to organize random outcomes by size in Python? I'm making a program that, in part, rolls four dice and subtracts the lowest dice from the outcome. The code I'm using is die1 = random.randrange(6) + 1 die2 = random.randrange(6) + 1 die3 = random.randrange(6) + 1 die4 = random.randrange...
Is there a more efficient way to organize random outcomes by size in Python?
I'm making a program that, in part, rolls four dice and subtracts the lowest dice from the outcome. The code I'm using is die1 = random.randrange(6) + 1 die2 = random.randrange(6) + 1 die3 = random.randrange(6) + 1 die4 = random.randrange(6) + 1 if die1 <= die2 and die1 <= die3 and die1 <= die4: drop = die1 elif di...
[ "Put the dice in a list, sort the list using sorted and remove the smallest element using a slice:\n>>> import random\n>>> dice = [random.randint(1, 6) for x in range(4)]\n>>> sum(sorted(dice)[1:])\n13\n\nOr an alternative that is simpler and will also be faster if you have lots of dice: use min to find the minimum...
[ 8 ]
[]
[]
[ "python", "random" ]
stackoverflow_0002978317_python_random.txt
Q: Does Django Have a Way to Auto-Sort Model Fields? So basically, I've got a rather large Django project going. It's a private web portal that allows users to manage various phone-related tasks. Several pages of the portal provide a listing of Model objects to users, and list all of their attributes in a HTML table ...
Does Django Have a Way to Auto-Sort Model Fields?
So basically, I've got a rather large Django project going. It's a private web portal that allows users to manage various phone-related tasks. Several pages of the portal provide a listing of Model objects to users, and list all of their attributes in a HTML table (so that users can visually look through a list of thes...
[ "The way that I'd look at doing this is through a custom QuerySet. In your model, you can define the class QuerySet and add your sorting there. In order to maintain all the logic in the model object, I'd also move the contents of get_my_partylines into the QuerySet, too.\n## This class is used to replicate QueryS...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0002977845_django_django_models_django_templates_python.txt
Q: django : ImportError No module named myapp.views.hometest I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. Thanks for any suggestion and help! A: I just had this problem. It went away whe...
django : ImportError No module named myapp.views.hometest
I have fecora 11, set django with mod_wsgi2.5 and apache2.2. And I can run "python manage.py runserver" at local. It works fine. I got error when i test from remote browser. Thanks for any suggestion and help!
[ "I just had this problem. It went away when I added sys.path.append('/path/to/project') to my .wsgi file.\n", "Is the application containing your Django project in your $PYTHONPATH (when Python is invoked in a server context)? For example, if your Django project is at /home/wwwuser/web/myproj, then /home/wwwuser/...
[ 4, 2, 1, 1 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0001359449_django_mod_wsgi_python.txt
Q: High-concurrency counters without sharding This question concerns two implementations of counters which are intended to scale without sharding (with a tradeoff that they might under-count in some situations): http://appengine-cookbook.appspot.com/recipe/high-concurrency-counters-without-sharding/ (the code in the...
High-concurrency counters without sharding
This question concerns two implementations of counters which are intended to scale without sharding (with a tradeoff that they might under-count in some situations): http://appengine-cookbook.appspot.com/recipe/high-concurrency-counters-without-sharding/ (the code in the comments) http://blog.notdot.net/2010/04/High-c...
[ "Going to datastore is likely to be more expensive than going through memcache. Else memcache wouldn't be all that useful in the first place :-)\nI'd recommend the first option.\nIf you have a reasonable request rate, you can actually implement it even simpler:\n1) update the value in memcache\n2) if the returned u...
[ 1 ]
[ "Memcache gets flushed, you lose your counter. OUCH. Using a mysql database or a NOSQL solution will resolve that problem with a possible performance hit. (Redis, Tokyotyrant, MongoDB etc...) may not have that performance hit.\nKeep in mind, you may want to do 2 actions:\n\nkeep a memcache counter just for the hi...
[ -2 ]
[ "counter", "google_app_engine", "python" ]
stackoverflow_0002769934_counter_google_app_engine_python.txt
Q: Pass parameter one time, but use more times I'm trying to do this: commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', } commands['md'] % 'file.md' But like you see, the commmands['md'] uses the parameter 3 times, but the commands['py'] just use once. How can I repeat the par...
Pass parameter one time, but use more times
I'm trying to do this: commands = { 'py': 'python %s', 'md': 'markdown "%s" > "%s.html"; gnome-open "%s.html"', } commands['md'] % 'file.md' But like you see, the commmands['md'] uses the parameter 3 times, but the commands['py'] just use once. How can I repeat the parameter without changing the last line (so, just p...
[ "Note: The accepted answer, while it does work for both older and newer versions of Python, is discouraged in newer versions of Python.\n\nSince str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str...
[ 11, 3, 1 ]
[]
[]
[ "parameters", "python", "repeat", "string_formatting" ]
stackoverflow_0002978362_parameters_python_repeat_string_formatting.txt
Q: Which is should I use and why? Does it matter? SafeUnicode or django.utils.safestring.mark_safe()? Suppose I've got a custom form label with some HTML on it like so: SafeUnicode('<span class="superscript">&trade;</span>') Why would Django 1.2 have a function mark_safe if this exist? What are the differences if an...
Which is should I use and why? Does it matter? SafeUnicode or django.utils.safestring.mark_safe()?
Suppose I've got a custom form label with some HTML on it like so: SafeUnicode('<span class="superscript">&trade;</span>') Why would Django 1.2 have a function mark_safe if this exist? What are the differences if any? Thanks for the help!
[ "mark_safe is a factory function which encapsulate a bit of type-checking logic in order to return, as appropriate, either a SafeUnicode or a SafeString (or possibly some other subclass of SafeData should you have defined any such subclasses). The source is easily short enough to quote...:\n89 def mark_safe(s):\n...
[ 5 ]
[]
[]
[ "django", "python", "string" ]
stackoverflow_0002978530_django_python_string.txt
Q: Get the inputs from Excel and use those inputs in python script How to get the inputs from excel and use those inputs in python. A: Take a look at xlrd This is the best reference I found for learning how to use it: http://www.dev-explorer.com/articles/excel-spreadsheets-and-python A: Not sure if this is exactl...
Get the inputs from Excel and use those inputs in python script
How to get the inputs from excel and use those inputs in python.
[ "Take a look at xlrd\nThis is the best reference I found for learning how to use it: http://www.dev-explorer.com/articles/excel-spreadsheets-and-python\n", "Not sure if this is exactly what you're talking about, but:\nIf you have a very simple excel file (i.e. basically just one table filled with string-values, n...
[ 6, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001459788_python.txt
Q: Using Elixir, how can I get the table object of a self-referential relationship to perform inserts on? I'm using Elixir with SQLite and I'd like to perform multiple inserts as per the docs: http://www.sqlalchemy.org/docs/05/sqlexpression.html#executing-multiple-statements However, my ManyToMany relationship is sel...
Using Elixir, how can I get the table object of a self-referential relationship to perform inserts on?
I'm using Elixir with SQLite and I'd like to perform multiple inserts as per the docs: http://www.sqlalchemy.org/docs/05/sqlexpression.html#executing-multiple-statements However, my ManyToMany relationship is self-referential and I can't figure out where to get the insert() object from. Can anyone help?
[ "It might be easy if you just stick with SQL Alchemy's built in Declarative style instead of using Elixir as much of what it does is now doable in there. Then you can follow the example here: Many to Many\nThen look very closely at the code where a post is added and then keywords related to that post are added. Y...
[ 0 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002978797_python_python_elixir_sqlalchemy.txt
Q: Parsing complicated query parameters My Python server receives jobs that contain a list of the items to act against, rather like a search query term; an example input: (Customer:24 OR Customer:25 OR (Group:NW NOT Customer:26)) So when a job is submitted, I have to parse this recipient pattern and resolve all thos...
Parsing complicated query parameters
My Python server receives jobs that contain a list of the items to act against, rather like a search query term; an example input: (Customer:24 OR Customer:25 OR (Group:NW NOT Customer:26)) So when a job is submitted, I have to parse this recipient pattern and resolve all those customers that match, and create the job...
[ "I suggest pyparsing (http://pyparsing.wikispaces.com/) which lets you describe a grammar neatly and gives you a tree filled with data. Then, hopefully, your syntax is close enough to SQL so that you can trivially form a \"where\" clause from the parsing results.\nYou may pickle and store the parsed tree, or the un...
[ 1, 0 ]
[]
[]
[ "database", "parsing", "python" ]
stackoverflow_0002918828_database_parsing_python.txt
Q: Proper way to define "remaining time off" for a Django User I've implemented a UserProfile model (as the Django 1.2 docs say is the proper way to save additional data about a User) which has a 'remaining_vacation_hours' field. In our current system, when a user fills out a Time Off Request, the remaining hours av...
Proper way to define "remaining time off" for a Django User
I've implemented a UserProfile model (as the Django 1.2 docs say is the proper way to save additional data about a User) which has a 'remaining_vacation_hours' field. In our current system, when a user fills out a Time Off Request, the remaining hours available should be checked to see that they have enough vacation t...
[ "If you do not want to modify/inherit from the original User model I'd say it's totally ok if the method is added to your UserProfile!\n", "First, I would suggest the solution of making a different method (as you've already suggested), but on a different class and pass the user instance as a parameter. That way, ...
[ 2, 2 ]
[]
[]
[ "django", "python", "user_profile" ]
stackoverflow_0002977824_django_python_user_profile.txt
Q: WTForms error:TypeError: formdata should be a multidict-type wrapper from wtforms import Form, BooleanField, TextField, validators,PasswordField class LoginForm(Form): username = TextField('Username', [validators.Length(min=4, max=25)]) password = PasswordField('Password') when i use LoginForm on weba...
WTForms error:TypeError: formdata should be a multidict-type wrapper
from wtforms import Form, BooleanField, TextField, validators,PasswordField class LoginForm(Form): username = TextField('Username', [validators.Length(min=4, max=25)]) password = PasswordField('Password') when i use LoginForm on webapp(gae) like this : def post(self): form=LoginForm(self.request) but ...
[ "You are supposed to pass in self.request.form (the actual form fields, not the entire request)\n" ]
[ 8 ]
[]
[]
[ "python", "wtforms" ]
stackoverflow_0002978986_python_wtforms.txt
Q: why doesnt netbeans support python and django? i wonder why sun doesnt support python and django in netbeans? cause i am choosing between learning ruby/rails or python/django. does this mean that i should use ruby/rails cause then support comes out of the box? seems that other applications favor support for ruby o...
why doesnt netbeans support python and django?
i wonder why sun doesnt support python and django in netbeans? cause i am choosing between learning ruby/rails or python/django. does this mean that i should use ruby/rails cause then support comes out of the box? seems that other applications favor support for ruby over python.
[ "Netbeans now suports python please take look at http://wiki.netbeans.org/Python and DJANGO http://wiki.netbeans.org/Python70Roadmap\n", "Why let one particular IDE determine what programming language you learn?\nI use python a lot, and Geany does what I need rather well. Other folks like heavier weight editors....
[ 6, 3 ]
[]
[]
[ "ide", "netbeans", "python", "ruby" ]
stackoverflow_0002979053_ide_netbeans_python_ruby.txt
Q: pyplot: really slow creating heatmaps I have a loop that executes the body about 200 times. In each loop iteration, it does a sophisticated calculation, and then as debugging, I wish to produce a heatmap of a NxM matrix. But, generating this heatmap is unbearably slow and significantly slow downs an already slow a...
pyplot: really slow creating heatmaps
I have a loop that executes the body about 200 times. In each loop iteration, it does a sophisticated calculation, and then as debugging, I wish to produce a heatmap of a NxM matrix. But, generating this heatmap is unbearably slow and significantly slow downs an already slow algorithm. My code is along the lines: impor...
[ "Try putting plt.clf() in the loop to clear the current figure:\nfor i in range(200):\n matrix = complex_calculation()\n plt.set_cmap(\"gray\")\n plt.imshow(matrix)\n plt.savefig(\"frame{0}.png\".format(i))\n plt.clf()\n\nIf you don't do this, the loop slows down as the machine struggles to allocate ...
[ 5, 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002971653_matplotlib_python.txt
Q: Is there any thorough, broad documentation of Twisted that is better than the official site? I've been looking at twisted for a while now. It looks interesting - it seems like a good way to leverage a lot of power when writing servers. Unfortunately, in spite of writing a few web servers using twisted.web (from re...
Is there any thorough, broad documentation of Twisted that is better than the official site?
I've been looking at twisted for a while now. It looks interesting - it seems like a good way to leverage a lot of power when writing servers. Unfortunately, in spite of writing a few web servers using twisted.web (from reading other people's source and an extremely dated O'Reilly book) I've never really felt like I ha...
[ "I'm going to repeat what some of the answerers here have said (they're all good answers) in the hopes of providing an answer that is somewhat comprehensive.\n\nWhile the included documentation is spotty in places, the core documentation contains several helpful and brief introductions to the basic concepts in Twis...
[ 16, 7, 2, 2, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002972703_python_twisted.txt
Q: Map vs list comprehension in Python When should you use map/filter instead of a list comprehension or generator expression? A: You might want to take a look at the responses to this question: Python List Comprehension Vs. Map Also, here's a relevant essay from Guido, creator and BDFL of Python: http://www.artima...
Map vs list comprehension in Python
When should you use map/filter instead of a list comprehension or generator expression?
[ "You might want to take a look at the responses to this question:\nPython List Comprehension Vs. Map\nAlso, here's a relevant essay from Guido, creator and BDFL of Python:\nhttp://www.artima.com/weblogs/viewpost.jsp?thread=98196\nPersonally, I prefer list comprehensions and generator expressions because their meani...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002979290_python.txt
Q: Unit testing authorization in a Pylons app fails; cookies aren't been correctly set or recorded I'm having an issue running unit tests for authorization in a Pylons app. It appears as though certain cookies set in the test case may not be correctly written or parsed. Cookies work fine when hitting the app with a b...
Unit testing authorization in a Pylons app fails; cookies aren't been correctly set or recorded
I'm having an issue running unit tests for authorization in a Pylons app. It appears as though certain cookies set in the test case may not be correctly written or parsed. Cookies work fine when hitting the app with a browser. Here is my test case inside a paste-generated TestController: def test_good_login(self): ...
[ "This issue disappeared after downgrading WebTest from 1.2.1 to 1.2.\n", "The issue continually appeared for me regardless of the version of WebTest. However, after much mucking around I noticed that when the cookie was first set it was using 127.0.0.1 as the REMOTE_ADDR value but on the second request it change...
[ 5, 2 ]
[]
[]
[ "nose", "nosetests", "pylons", "python", "webtest" ]
stackoverflow_0002731907_nose_nosetests_pylons_python_webtest.txt
Q: easy way to change a dict data to url Parameter (1) a={'b':'bbbb','c':'ccc',....} (2) self.redirect('/tribes/view?b=' + a['b'] + '&c=' + a['c']) so i want to get b=' + a['b'] + '&c=' + a['c'] ... from dict a hae any easy way to do this ? thanks A: from urllib import urlencode urlencode({'b':'bbbb', 'c':'cc...
easy way to change a dict data to url Parameter
(1) a={'b':'bbbb','c':'ccc',....} (2) self.redirect('/tribes/view?b=' + a['b'] + '&c=' + a['c']) so i want to get b=' + a['b'] + '&c=' + a['c'] ... from dict a hae any easy way to do this ? thanks
[ "from urllib import urlencode\nurlencode({'b':'bbbb', 'c':'ccc'})\n\n" ]
[ 7 ]
[]
[]
[ "google_app_engine", "parameters", "python", "url" ]
stackoverflow_0002979586_google_app_engine_parameters_python_url.txt
Q: how to make the username and email is Unique .. using WTFroms wtforms is a forms validation and rendering library for python web development but i can't find how to handle the username and email Unique , thanks A: Read the whole page in your link and you'll find the header "Custom Validators" which shows a quic...
how to make the username and email is Unique .. using WTFroms
wtforms is a forms validation and rendering library for python web development but i can't find how to handle the username and email Unique , thanks
[ "Read the whole page in your link and you'll find the header \"Custom Validators\" which shows a quick ... custom validator.\nThe documentation has more on the topic.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python", "unique", "web_applications", "wtforms" ]
stackoverflow_0002979655_google_app_engine_python_unique_web_applications_wtforms.txt
Q: ImageChops.duplicate - python I am tring to use the function ImageChops.dulpicate from the PIL module and I get an error I don't understand: this is the code import PIL import Image import ImageChops import os PathDemo4a='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/demo4a' PathDemo4b='C:/Doc...
ImageChops.duplicate - python
I am tring to use the function ImageChops.dulpicate from the PIL module and I get an error I don't understand: this is the code import PIL import Image import ImageChops import os PathDemo4a='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/demo4a' PathDemo4b='C:/Documents and Settings/Ariel/My Docume...
[ "You need to pass a Image object into the duplicate function rather than a string. Something like:\nimg = Image.open(PathBlackBoard)\nBB = ImageChops.duplicate(img) \n\n", "I think you should pass an actual image object to duplicate and not a string. So your code will probably become something like this for one ...
[ 3, 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0002979621_python_python_imaging_library.txt
Q: Parsing a context-free grammar in Python What tools are available in Python to assist in parsing a context-free grammar? Of course it is possible to roll my own, but I am looking for a generic tool that can generate a parser for a given CFG. A: I warmly recommend PLY - it's a Lex/Yacc clone in Python that uses t...
Parsing a context-free grammar in Python
What tools are available in Python to assist in parsing a context-free grammar? Of course it is possible to roll my own, but I am looking for a generic tool that can generate a parser for a given CFG.
[ "I warmly recommend PLY - it's a Lex/Yacc clone in Python that uses the language's introspection facilities in a sophisticated manner to allow for a very natural specification of the grammar. Yacc, if you recall, is the very embodiment of CFGs in an understandable DSL that defines how one parses them.\nI used it to...
[ 9 ]
[]
[]
[ "context_free_grammar", "python", "regex" ]
stackoverflow_0002979703_context_free_grammar_python_regex.txt
Q: Coloring close points I have a dense set of points in the plane. I want them colored so that points that are close to each other have the same color, and a different color if they're far away. For simplicity assume that there are, say, 5 different colors to choose from. Turns out I've not the slightest idea how to...
Coloring close points
I have a dense set of points in the plane. I want them colored so that points that are close to each other have the same color, and a different color if they're far away. For simplicity assume that there are, say, 5 different colors to choose from. Turns out I've not the slightest idea how to do that .. I'm using Tkint...
[ "If you can use whatever color you want, you can use that fact that colors are (almost) continuous. color the points according to their x,y coordinates, so you'll get as a side effect that close points will have a somewhat similar color.\nYou can use something like\npoint.color(R,G,B) = ( point.normalized_x, 0.5, 1...
[ 2, 0, 0, 0 ]
[]
[]
[ "geometry", "python", "tkinter" ]
stackoverflow_0002979697_geometry_python_tkinter.txt