content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to determine which python is used by mac and mac programs I've read through several questions and pages on the how and why of this, but after taking a look on my mac yesterday I found that I currently have 6 versions of python on my machine. Three are located in /Library/Frameworks/Python.framework/Versions (...
How to determine which python is used by mac and mac programs
I've read through several questions and pages on the how and why of this, but after taking a look on my mac yesterday I found that I currently have 6 versions of python on my machine. Three are located in /Library/Frameworks/Python.framework/Versions (2.5, 3.1, 3.2), and then I have three more in /System/Library/Frame...
[ "\nHow to know which Python is the used:\nIn the Terminal, type which python. It will show you the path to the active Python.\n\nWhy so many versions:\nProbably leftovers of previous system upgrades: Tiger -> Leopard -> Snow Leopard, maybe.\n\nHow to point everything to the Python you want:\nIn your .profile or .ba...
[ 5 ]
[]
[]
[ "macos", "path", "python", "textmate" ]
stackoverflow_0006276049_macos_path_python_textmate.txt
Q: How well does your language support unicode in practice? I'm looking into new languages, kind of craving for one where I no longer need to worry about charset problems amongst inordinate amounts of other niggles I have with PHP for a new project. I tend to find Java too verbose and messy, and my not wanting to tou...
How well does your language support unicode in practice?
I'm looking into new languages, kind of craving for one where I no longer need to worry about charset problems amongst inordinate amounts of other niggles I have with PHP for a new project. I tend to find Java too verbose and messy, and my not wanting to touch Windows with a 6-foot pole tends to rule out .Net. That lea...
[ "Python's unicode support did not really change in 3.x. The unicode support in Python has been pretty much the same since Python 2.x, which introduced the separate unicode type and the encoding handling. What Python 3.x changes is that unicode becomes the only string type (and is renamed to str), whereas 2.x has by...
[ 7, 6, 3, 2, 2, 1 ]
[]
[]
[ "lisp", "node.js", "python", "ruby" ]
stackoverflow_0006286922_lisp_node.js_python_ruby.txt
Q: Python efficient mass replacing unknown characterers PHP4+mySQL4 based project post to Django 1.1 project and it mixes up some letters. What is the best way (most efficient) to replace in this fashion? The problem for me is that i cannot get values for those letters. Is there an online tool to do that? I have text...
Python efficient mass replacing unknown characterers
PHP4+mySQL4 based project post to Django 1.1 project and it mixes up some letters. What is the best way (most efficient) to replace in this fashion? The problem for me is that i cannot get values for those letters. Is there an online tool to do that? I have textField with various letters and i want to replace those in ...
[ "Try the str.replace() method - should work with unicode strings.\n\nstr.replace(old, new[, count])\nReturn a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.\n\nMake sure your old and new strings are of...
[ 2, 0, 0 ]
[]
[]
[ "django", "non_unicode", "php4", "python", "replace" ]
stackoverflow_0006279960_django_non_unicode_php4_python_replace.txt
Q: Virtualenv for different version of django I want to use different django version. how can i create django virtualenv. Please help. A: Create your virtualenv: virtualenv myenv Activate that virtualenv: source myenv/bin/activate Install Django: pip install Django Run your project: python manage.py runserver A...
Virtualenv for different version of django
I want to use different django version. how can i create django virtualenv. Please help.
[ "Create your virtualenv:\nvirtualenv myenv\n\nActivate that virtualenv:\nsource myenv/bin/activate\n\nInstall Django:\npip install Django\n\nRun your project:\npython manage.py runserver\n\n", "you need virtualenv and pip. write in shell:\nfor debian:\napt-get install python-pip\n\nfor fedoras(python 2.4, change ...
[ 8, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006288868_django_python.txt
Q: is there a way find substring index through a regular expression in python? i want to find a substring 's index postion,but the substring is long and hard to expression(multiline,& even you need escape for it ) so i want to use regex to match them,and return the substring's index, the function like str.find or str...
is there a way find substring index through a regular expression in python?
i want to find a substring 's index postion,but the substring is long and hard to expression(multiline,& even you need escape for it ) so i want to use regex to match them,and return the substring's index, the function like str.find or str.rfind , is there some package help for this?
[ "Use the .start() method on the result object of a successful match (the so called match object):\n mo = re.search('foo', veryLongString)\n if mo:\n return mo.start()\n\nIf the match was successful, mo.start() will give you the (first) index of the matching substring within the searched string.\n", "regular ...
[ 1, 0, 0 ]
[]
[]
[ "indexing", "python", "regex", "string_matching" ]
stackoverflow_0003911417_indexing_python_regex_string_matching.txt
Q: App Engine: submitting form data to Google Spreadsheet We'd like to duplicate the Google Spreadsheet Form Wizard functionality within our App Engine application. The rational for this is that Google forms look ugly and the form wizard apparently does not provide enough hooks to make layout better. Do you know any ...
App Engine: submitting form data to Google Spreadsheet
We'd like to duplicate the Google Spreadsheet Form Wizard functionality within our App Engine application. The rational for this is that Google forms look ugly and the form wizard apparently does not provide enough hooks to make layout better. Do you know any examples how to integrate Google Spreadsheet GData API in Ap...
[ "Everything you write makes sense, but where's the question?\nYou can put python gdata client library into your GAE project.\nYou can expose the spreadsheet (make it accessible from the outer world), but leave it private, so nobody would be able to manually access it, and authenticate your GAE Django app. Trivially...
[ 1 ]
[]
[]
[ "django", "gdata", "google_app_engine", "google_spreadsheet_api", "python" ]
stackoverflow_0006289080_django_gdata_google_app_engine_google_spreadsheet_api_python.txt
Q: How to make models connected via ManyToMany relationship editable in two places at the same time in Django admin? I have two models - News and Subject. News model has a ManyToManyField related to Subject, like that: subjects = models.ManyToManyField(NewsSubject, verbose_name=u'Subjects', blank=True,null=True,relat...
How to make models connected via ManyToMany relationship editable in two places at the same time in Django admin?
I have two models - News and Subject. News model has a ManyToManyField related to Subject, like that: subjects = models.ManyToManyField(NewsSubject, verbose_name=u'Subjects', blank=True,null=True,related_name='news') And I need to have an ability not only to choose Subjects for News in admin, but also to choose News w...
[ "I am not sure that it can meet your needs but i've done something similar by using TabularInline. Somethink like this should work (i didn't test the following code).\nclass Subject(models.Model):\n ...\n\nclass News(models.Model):\n subject = models.ManyToManyField(Subject, through=\"NewsSubject\")\n\nclass ...
[ 2 ]
[]
[]
[ "admin", "django", "many_to_many", "models", "python" ]
stackoverflow_0006290448_admin_django_many_to_many_models_python.txt
Q: Python macros on Mac using Komodo I'm using Komodo IDE, version 6.1.1, build 61234, platform macosx-x86. I'm also using Python 3.2 and Python 2.7. I've just moved to using (my first) Mac. OS version 10.6.? On my Windows machines I had a couple of macros set up that I would like to continue to use: F2: save file an...
Python macros on Mac using Komodo
I'm using Komodo IDE, version 6.1.1, build 61234, platform macosx-x86. I'm also using Python 3.2 and Python 2.7. I've just moved to using (my first) Mac. OS version 10.6.? On my Windows machines I had a couple of macros set up that I would like to continue to use: F2: save file and then run using Python 2.x, results in...
[ "I ended up writing my own macros - see below...\n// Macro recorded on: Thu Jun 10 2010 08:50:50 GMT+1000 (AUS Eastern Standard Time)\nkomodo.assertMacroVersion(3);\nif (komodo.view && komodo.view.scintilla) { komodo.view.scintilla.focus(); }\nkomodo.doCommand('cmd_save')\nko.run.runEncodedCommand(window, '/usr/loc...
[ 2, 0 ]
[]
[]
[ "komodo", "macos", "macros", "python" ]
stackoverflow_0006172314_komodo_macos_macros_python.txt
Q: Own string usage I have my own string class and I want to export it into python (with boost.python) and use as a native string. I wrote converters for this. The first is exporting of my string: bp::class_<CL_StringRef8>("CL_StringRef8", bp::init<const std::string&>()) .def("CStr", &CL_StringRef8::c_str); Conv...
Own string usage
I have my own string class and I want to export it into python (with boost.python) and use as a native string. I wrote converters for this. The first is exporting of my string: bp::class_<CL_StringRef8>("CL_StringRef8", bp::init<const std::string&>()) .def("CStr", &CL_StringRef8::c_str); Converters are from defaul...
[ "In order for the .def(bp::self_ns::str(bp::self_ns::self)); line to work, you need to have the streaming operator defined for your class.\nstd::ostream & operator<<(std::ostream & os, const CL_StringRef8 &s)\n{ os << s.c_str(); return os; } \n\nAn alternative way of defining the str() method without needing the s...
[ 2 ]
[]
[]
[ "boost", "c++", "export", "python" ]
stackoverflow_0006192947_boost_c++_export_python.txt
Q: Applying a Regex to a Substring Without using String Slice I want to search for a regex match in a larger string from a certain position onwards, and without using string slices. My background is that I want to search through a string iteratively for matches of various regex's. A natural solution in Python would b...
Applying a Regex to a Substring Without using String Slice
I want to search for a regex match in a larger string from a certain position onwards, and without using string slices. My background is that I want to search through a string iteratively for matches of various regex's. A natural solution in Python would be keeping track of the current position within the string and us...
[ "The variants with pos and endpos parameters only exist as members of regular expression objects. Try this:\nimport re\npattern = re.compile(\"match here\")\ninput = \"don't match here, but do match here\"\nstart = input.find(\",\")\nprint pattern.search(input, start).span()\n\n... outputs (25, 35)\n", "The pos k...
[ 6, 4, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006291038_python_regex.txt
Q: python-MySQLdb iphone Does anybody know where to get python-MySQLdb compiled for the arm iPhone architecture? or how to do it? I'm stucked at this point: :~/MySQL-python-1.2.3 root# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.darwin-10.5-arm-2.5/MySQLdb running buil...
python-MySQLdb iphone
Does anybody know where to get python-MySQLdb compiled for the arm iPhone architecture? or how to do it? I'm stucked at this point: :~/MySQL-python-1.2.3 root# python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.darwin-10.5-arm-2.5/MySQLdb running build_ext building '_mysql' ext...
[ "i solved the previous problem.....it was the threadsafe = True in site.cfg i had to put False.\nNow i have another problem really similar\npython setup.py build\nrunning build\nrunning build_py\ncopying MySQLdb/release.py -> build/lib.darwin-10.5-arm-2.5/MySQLdb\nrunning build_ext\nbuilding '_mysql' extension\narm...
[ 0 ]
[]
[]
[ "arm", "compilation", "iphone", "mysql_python", "python" ]
stackoverflow_0006282028_arm_compilation_iphone_mysql_python_python.txt
Q: Creating thread in python rewrites another structure in my Python program I use my own C library where I have quite complicated structure (I use Python only to create GUI). After creating another thread which should handle some calculations going on in the C module, one of the char * in the C structure (maybe more...
Creating thread in python rewrites another structure
in my Python program I use my own C library where I have quite complicated structure (I use Python only to create GUI). After creating another thread which should handle some calculations going on in the C module, one of the char * in the C structure (maybe more, but I didn't find any other yet) contains following str...
[ "I figured it out. The problem was I didn't make defense copy of the string when storing it into char* in my structure and python had no problem overwriting that very memory space with another string although my pointer was still pointing to it.\nThanks for your time everyone.\n" ]
[ 0 ]
[]
[]
[ "c", "multithreading", "python", "wxpython" ]
stackoverflow_0005994405_c_multithreading_python_wxpython.txt
Q: How do I find out why importing failed with PyImportModule? I have this code in a C application that's embedding Python (2.7.1): { PyObject *user_dict; PyObject *user_func; PyObject *result; PyObject *header_tuple; PyObject *original_recipients; PyObject *working_recipients; if (!Py_IsInitialized()) { Py_...
How do I find out why importing failed with PyImportModule?
I have this code in a C application that's embedding Python (2.7.1): { PyObject *user_dict; PyObject *user_func; PyObject *result; PyObject *header_tuple; PyObject *original_recipients; PyObject *working_recipients; if (!Py_IsInitialized()) { Py_Initialize(); } if (!expy_exim_dict) { PyObject *mod...
[ "You do this by looking at the exception that was raised. Currently you wipe the exception (that's what PyErr_Clear() does.) Don't do that, and instead print the traceback or inspect the exception object. See http://docs.python.org/c-api/exceptions.html for information on how to do that from C code, but usually the...
[ 6 ]
[]
[]
[ "python", "python_c_api", "python_embedding" ]
stackoverflow_0006291545_python_python_c_api_python_embedding.txt
Q: Python Unittest2 - avoid including a TestCase in discover() I'm using unittest2 on Python2.5 to discover tests with unittest.TestLoader.discover, like this: suite = unittest2.loader.TestLoader().discover(test_path) unittest2.TextTestRunner(verbosity=2, resultclass=ColorTestResult).run(suite) for some test...
Python Unittest2 - avoid including a TestCase in discover()
I'm using unittest2 on Python2.5 to discover tests with unittest.TestLoader.discover, like this: suite = unittest2.loader.TestLoader().discover(test_path) unittest2.TextTestRunner(verbosity=2, resultclass=ColorTestResult).run(suite) for some test_path at the base of my project. I've a base class that's extende...
[ "I'm guessing that the problem is that UT2 inherits from UT, so the module where UT2 is defined imports UT - and therefore makes it available in the module namespace. So even though discovery is not looking at the module where UT is defined, it can still find the TestCase in the UT2 module.\nThis is a general probl...
[ 2 ]
[]
[]
[ "python", "unit_testing", "unittest2" ]
stackoverflow_0006286499_python_unit_testing_unittest2.txt
Q: Temporary changing python logging handlers I'm working on an app that uses the standard logging module to do logging. We have a setup where we log to a bunch of files based on levels etc. We also use celery to run some jobs out of the main app (maintenance stuff usually that's time consuming). The celery task does...
Temporary changing python logging handlers
I'm working on an app that uses the standard logging module to do logging. We have a setup where we log to a bunch of files based on levels etc. We also use celery to run some jobs out of the main app (maintenance stuff usually that's time consuming). The celery task does nothing other than call functions (lets say spa...
[ "The thing about the StringIO is, there could be multiple processes running (Celery tasks), hence multiple StringIOs, right?\nYou can do something like this:\n\nIn the processes run under Celery, add to the root logger a handler which sends events to a socket (SocketHandler for TCP or DatagramHandler for UDP).\nCre...
[ 2, 0 ]
[]
[]
[ "celery", "logging", "python" ]
stackoverflow_0006282623_celery_logging_python.txt
Q: How would you draw UDP data as it comes in? I want to listen on a on a UDP socket for data that will be streamed in and draw it on screen as it comes in. I believe that the socket module with bind will be suitable for receiving the data on the socket, but I am not sure on the best manner to proceed in drawing the ...
How would you draw UDP data as it comes in?
I want to listen on a on a UDP socket for data that will be streamed in and draw it on screen as it comes in. I believe that the socket module with bind will be suitable for receiving the data on the socket, but I am not sure on the best manner to proceed in drawing the data. The image dimensions would be known beforeh...
[ "kinter is included in Python, you need to install PyQt (or PySide) separately. Qt is more modern, so I would probably try it first if deployment isn't problem.\n", "Tkinter has a canvas widget which can be used for drawing. It is vector-based, with primitives for drawing lines, circles, etc. It is very easy to u...
[ 2, 2 ]
[]
[]
[ "pyqt", "python", "tkinter", "udp" ]
stackoverflow_0006285553_pyqt_python_tkinter_udp.txt
Q: Generator Function Performance I'm trying to understand the performance of a generator function. I've used cProfile and the pstats module to collect and inspect profiling data. The function in question is this: def __iter__(self): delimiter = None inData = self.inData lenData = len(inData) ...
Generator Function Performance
I'm trying to understand the performance of a generator function. I've used cProfile and the pstats module to collect and inspect profiling data. The function in question is this: def __iter__(self): delimiter = None inData = self.inData lenData = len(inData) cursor = 0 while cursor < le...
[ "This is actually the answer of Dunes, who unfortunately only gave it as a comment and doesn't seem to be inclined to put it in a proper answer.\nThe main performance culprit were the string slices. Some timing measurements showed that slicing performance degrades perceivably with big slices (meaning taking a big s...
[ 2, 1 ]
[]
[]
[ "generator", "performance", "profiling", "python" ]
stackoverflow_0006283229_generator_performance_profiling_python.txt
Q: Why this query doesn't work (problem with EXISTS) I'm struggling with such query (generated by sqlalchemy. I've renamed it for clarity) SELECT table.x + :dx AS cx, table.y + :dy AS cy FROM table WHERE NOT (EXISTS (SELECT * FROM table AS table_1 WHERE table_1.x = cx AND table_1.y = cy)) AND ...
Why this query doesn't work (problem with EXISTS)
I'm struggling with such query (generated by sqlalchemy. I've renamed it for clarity) SELECT table.x + :dx AS cx, table.y + :dy AS cy FROM table WHERE NOT (EXISTS (SELECT * FROM table AS table_1 WHERE table_1.x = cx AND table_1.y = cy)) AND (EXISTS (SELECT * FROM table2 WHER...
[ "As written in edit the problem was in flushing.\n" ]
[ 0 ]
[]
[]
[ "exists", "python", "sql", "sqlalchemy" ]
stackoverflow_0006282423_exists_python_sql_sqlalchemy.txt
Q: Why does my python egg not work? - No distributions at all found for I have made a distribution of my python package with the following setup.py #!/usr/bin/env python from setuptools import setup setup(name='mypackagename', version='0.1', description='Tool ....', author='Peter Smit', aut...
Why does my python egg not work? - No distributions at all found for
I have made a distribution of my python package with the following setup.py #!/usr/bin/env python from setuptools import setup setup(name='mypackagename', version='0.1', description='Tool ....', author='Peter Smit', author_email='lala@lala.com', packages=['mypackagename'], package_...
[ "pip cannot install from eggs.\nIf you want your package to be available on PyPI, you need to register and account there and upload it. You can then simply say pip install myproject. It will search PyPI, find it, download and install it. \nIf you have your setup.py ready and want to install your application locally...
[ 2, 2, 2 ]
[]
[]
[ "distribution", "egg", "pip", "python" ]
stackoverflow_0006291875_distribution_egg_pip_python.txt
Q: Image Download with PycURL gets me broken Images I'm struggling with pycurl. These are my headers: headers.append('User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0') headers.append('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') headers.append('Accept-Language:...
Image Download with PycURL gets me broken Images
I'm struggling with pycurl. These are my headers: headers.append('User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0') headers.append('Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') headers.append('Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3') headers.append(...
[ "Okay, now where I have finally meditated over this by posting this question I got the solution.\nI needed to open the file in binary mode.\nf = open(\"temp/resources/%s\" % (filename,), 'wb')\n\nI hope this Question helps someone else, sometime, anyhow.\nThanks stackoverflow for making me meditate on this. :)\n" ]
[ 5 ]
[]
[]
[ "curl", "download", "image", "pycurl", "python" ]
stackoverflow_0006292438_curl_download_image_pycurl_python.txt
Q: How can i find the ips in network in python How can i find the TCP ips in network with the range(i.e 132.32.0.3 to 132.32.0.44) through python programming and also want to know the which ips are alive and which are dead. please send me.. thanks for the repliers... A: Part 1 - "Finding IPs" Your example range, 1...
How can i find the ips in network in python
How can i find the TCP ips in network with the range(i.e 132.32.0.3 to 132.32.0.44) through python programming and also want to know the which ips are alive and which are dead. please send me.. thanks for the repliers...
[ "Part 1 - \"Finding IPs\"\nYour example range, 132.32.0.3 to 132.32.0.44 doesn't match any subnet, which is curious.\nTypically applications for checking whether hosts are up and down are normally scoped within a subnet, e.g. 192.168.0.0/28 (host addresses: 192.168.0.1 to 192.168.0.14).\nIf you wanted to calculate ...
[ 1 ]
[]
[]
[ "python", "sockets", "tcp" ]
stackoverflow_0006291238_python_sockets_tcp.txt
Q: pyparsing Regex as Word I'm building a syntax parser to perform simple actions on objects identified using dotted notation, something like this: DISABLE ALL; ENABLE A.1 B.1.1 C but in DISABLE ALL the keyword ALL is instead matched as 3 Regex(r'[a-zA-Z]') => 'A', 'L', 'L' I use to match arguments. How can I make a...
pyparsing Regex as Word
I'm building a syntax parser to perform simple actions on objects identified using dotted notation, something like this: DISABLE ALL; ENABLE A.1 B.1.1 C but in DISABLE ALL the keyword ALL is instead matched as 3 Regex(r'[a-zA-Z]') => 'A', 'L', 'L' I use to match arguments. How can I make a Word using regex? AFAIK I ca...
[ "Is this the problem?\n#match any of the above\nitem = area ^ category ^ criteria\n#keyword to perform action on ALL items\nall_ = pp.CaselessLiteral(\"all\")\n\nShould be:\n#keyword to perform action on ALL items\nall_ = pp.CaselessLiteral(\"all\")\n#match any of the above\nitem = area ^ category ^ criteria ^ all_...
[ 4 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0006291311_pyparsing_python.txt
Q: Mixing cython and turbogears 2.1 Is it possible to integrate Cython and TG2? I have one computation (written in python) which is heavily numerical and would largly benefit from rewriting into C or cython. A: Without you having additionally specificity in your question and not knowing what exactly you mean by 'in...
Mixing cython and turbogears 2.1
Is it possible to integrate Cython and TG2? I have one computation (written in python) which is heavily numerical and would largly benefit from rewriting into C or cython.
[ "Without you having additionally specificity in your question and not knowing what exactly you mean by 'integrate', all I can offer is that cython provides a fairly simple way of (often dramatically) speeding up certain code written in python either via static typing or calling external c/c++ libraries. If there is...
[ 2 ]
[]
[]
[ "cython", "python", "turbogears", "turbogears2" ]
stackoverflow_0006292320_cython_python_turbogears_turbogears2.txt
Q: What is the difference between an 'sdist' .tar.gz distribution and an python egg? I am a bit confused. There seem to be two different kind of Python packages, source distributions (setup.py sdist) and egg distributions (setup.py bdist_egg). Both seem to be just archives with the same data, the python source files....
What is the difference between an 'sdist' .tar.gz distribution and an python egg?
I am a bit confused. There seem to be two different kind of Python packages, source distributions (setup.py sdist) and egg distributions (setup.py bdist_egg). Both seem to be just archives with the same data, the python source files. One difference is that pip, the most recommended package manager, is not able to insta...
[ "setup.py sdist creates a source distribution: it contains setup.py, the source files of your module/script (.py files or .c/.cpp for binary modules), your data files, etc. The result is an archive that can then be used to recompile everything on any platform.\nsetup.py bdist (and bdist_*) creates a built distribut...
[ 73, 23 ]
[]
[]
[ "egg", "python", "sdist" ]
stackoverflow_0006292652_egg_python_sdist.txt
Q: wx.EVT_IDLE set custom waiting time I'm currently using a binding to wx.EVT_IDLE to constantly redraw my scene. However I noticed this only redraws once every second. Is there any way to set the time it has to wait in order to consider an idle event to 0.1 sec or 0.01 sec? Regards, Bogdan A: In your OnIdle(self...
wx.EVT_IDLE set custom waiting time
I'm currently using a binding to wx.EVT_IDLE to constantly redraw my scene. However I noticed this only redraws once every second. Is there any way to set the time it has to wait in order to consider an idle event to 0.1 sec or 0.01 sec? Regards, Bogdan
[ "In your OnIdle(self, event) handler, you can use event.RequestMore() to keep generating idle events. This should allow you to redraw as fast as you can process the events. See http://www.wxpython.org/docs/api/wx.IdleEvent-class.html#RequestMore\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006293026_python_wxpython.txt
Q: Decode this type of string in python =?UTF-8?B?TmV3IFBlcnNvbmFsIE1lc3NhZ2U6IE1vbmcgYW5oIHTDrG0gbOG6oWkgY2h1eWVudGIub3JnIQ==?= Hi, I have this string which is what returned from an IMAP command - do anyone know how to decode this in python so I'll have the proper UTF-8 string? A: >>> print unicode(base64.decodest...
Decode this type of string in python
=?UTF-8?B?TmV3IFBlcnNvbmFsIE1lc3NhZ2U6IE1vbmcgYW5oIHTDrG0gbOG6oWkgY2h1eWVudGIub3JnIQ==?= Hi, I have this string which is what returned from an IMAP command - do anyone know how to decode this in python so I'll have the proper UTF-8 string?
[ ">>> print unicode(base64.decodestring('TmV3IFBlcnNvbmFsIE1lc3NhZ2U6IE1vbmcgYW5oIHTDrG0gbOG6oWkgY2h1eWVudGIub3JnIQ=='), \"utf-8\")\nNew Personal Message: Mong anh tìm lại chuyentb.org!\n>>> \n\n", "I guess the best way to decode this Encoded-Word is via email.header.decode_header(). It'll return you a list in whi...
[ 4, 4 ]
[]
[]
[ "decode", "imap", "python", "string", "utf_8" ]
stackoverflow_0006283481_decode_imap_python_string_utf_8.txt
Q: Python import syntax Does this: import foo as bar do the same thing as this? bar = __import__('foo') Is there ever a reason to use the latter one? I'm reading through someone elses code, I found the latter one and am not sure why they didn't use the prior syntax A: The two statements do the same thing. The o...
Python import syntax
Does this: import foo as bar do the same thing as this? bar = __import__('foo') Is there ever a reason to use the latter one? I'm reading through someone elses code, I found the latter one and am not sure why they didn't use the prior syntax
[ "The two statements do the same thing. The only reason to use the latter syntax is not knowing the module name in advance.\n", "\nDirect use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.\n\nsource\n", "From Importing Python Modules by Fredrik L...
[ 6, 6, 2, 1 ]
[]
[]
[ "import", "python", "syntax" ]
stackoverflow_0006293333_import_python_syntax.txt
Q: How to verify domains faster in Python? Is there any way how to improve scripts verification speed? Or there is another (not a sw) solution? I tried something like this (but its slow and useless): import urllib from socket import * import string, re strings = string.ascii_lowercase digits = string.digits def va...
How to verify domains faster in Python?
Is there any way how to improve scripts verification speed? Or there is another (not a sw) solution? I tried something like this (but its slow and useless): import urllib from socket import * import string, re strings = string.ascii_lowercase digits = string.digits def validate(url): try: targetIP = geth...
[ "Since your program typically waits for network activity, you can probably get a speed-up by threading your program. \nHaving said that, if you can do this in another way, that would probably be preferrable.\nWhat problem are you really trying to solve?\nDo you just want to find out what domain names are free accor...
[ 2, 1 ]
[]
[]
[ "dns", "python", "urllib", "verify" ]
stackoverflow_0006293459_dns_python_urllib_verify.txt
Q: Python: Performance test, ensuring cleanup I am executing some performance tests on a messaging framework within python, and I am trying to make sure that the code is properly cleaning up after itself. Is there a way to monitor the current number of threads owned by the process? Is there a better way to tell if I...
Python: Performance test, ensuring cleanup
I am executing some performance tests on a messaging framework within python, and I am trying to make sure that the code is properly cleaning up after itself. Is there a way to monitor the current number of threads owned by the process? Is there a better way to tell if I am leaking threads? Just to make sure I clarif...
[ "This function will tell you how many threads are currently alive: threading.activeCount(). You can also enumerate those threads using the threading.enumerate() function. \n", "Use python profiler to generate stats files,\nthen use gprof2dot to generate graph\ngprof2dot -f pstats output.pstats | dot -Tpng -o outp...
[ 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0005464187_python.txt
Q: pymysql vs. pyodbc - pymysql is sloooooooooooow I've been having an issue trying to get my simple data analysis program that uses MySQL to work correctly. On my Windows 7 computer I use pyodbc and the program runs fine, using pyodbc to connect to MySQL. On Snow Leopard, couldn't get pyodbc to install correctly so ...
pymysql vs. pyodbc - pymysql is sloooooooooooow
I've been having an issue trying to get my simple data analysis program that uses MySQL to work correctly. On my Windows 7 computer I use pyodbc and the program runs fine, using pyodbc to connect to MySQL. On Snow Leopard, couldn't get pyodbc to install correctly so I'm using pymysql instead... After finally getting py...
[ "First you should make sure you are actually comparing the same things.\nsockets 'recv' method means that the program is waiting for something, so if your program actually does the same thing on both the W7 machine and the Mac, that could mean that the network latency is different.\n(For example if your Mac is usin...
[ 0 ]
[]
[]
[ "mysql", "pyodbc", "python" ]
stackoverflow_0005879161_mysql_pyodbc_python.txt
Q: django sign item with some extra values i recently posted a question on here and now need another answer on this based on an alteration that needs to be done based on extra params. previously I had the following that gave me a correct signature. signature = hashlib.sha1("i=myusername&v=%s&t=7087db23de5ef07b5723" %...
django sign item with some extra values
i recently posted a question on here and now need another answer on this based on an alteration that needs to be done based on extra params. previously I had the following that gave me a correct signature. signature = hashlib.sha1("i=myusername&v=%s&t=7087db23de5ef07b5723" % timestamp) Now I need to add the following ...
[ "Use %% in format string to get % symbol\n'&p=myvar%%3D%s' % 'value'\n\nI hope I understand you.\nAlso you can use urllib.urlencode\n>>>urllib.urlencode({'i':'fundedbyme', 'p':'myvar=%s' % myvalue})\n'i=fundedbyme&p=myvar%3Dmyvalue'\n\n" ]
[ 3 ]
[]
[]
[ "authentication", "digital_signature", "django", "python" ]
stackoverflow_0006292817_authentication_digital_signature_django_python.txt
Q: Assigning elements from a for loop to another list How would I get the elements iterated by a for loop to a list where I can print them out later in the my code? For example: for fname in dirlist: if fname.endswith(('.tgz','.tar')): print fname fname only shows all the elements from dirlist only in th...
Assigning elements from a for loop to another list
How would I get the elements iterated by a for loop to a list where I can print them out later in the my code? For example: for fname in dirlist: if fname.endswith(('.tgz','.tar')): print fname fname only shows all the elements from dirlist only in the loop. I would like to view the elements at other areas...
[ "You can use a list comprehension:\ntarfiles = [fname for fname in dirlist if fname.endswith(('.tgz','.tar'))]\n\nto print the filenames, use\nprint \"\\n\".join(tarfiles)\n\nor\nfor fname in tarfiles:\n print fname\n\n" ]
[ 6 ]
[]
[]
[ "for_loop", "list", "loops", "python" ]
stackoverflow_0006294113_for_loop_list_loops_python.txt
Q: Submitting a post request to an aspx page I have an ASPX page at https://searchlight.cluen.com/E5/CandidateSearch.aspx with a form on it, that I'd like to submit and parse for information. Using Python's urllib and urllib2 I created a post request with the proper headers and user agent. But the resulting html res...
Submitting a post request to an aspx page
I have an ASPX page at https://searchlight.cluen.com/E5/CandidateSearch.aspx with a form on it, that I'd like to submit and parse for information. Using Python's urllib and urllib2 I created a post request with the proper headers and user agent. But the resulting html response does not contain the expected table of re...
[ "ASP.Net uses a security feature that protects against tampering with the ViewState by embedding specific information in it.\nMore than likely, the server is rejecting your request because the ViewState is being treated as though it were tampered with. I can't say this with absolute certainty, but ASP.Net has sever...
[ 7, 2 ]
[]
[]
[ "asp.net", "httpwebrequest", "python" ]
stackoverflow_0006269064_asp.net_httpwebrequest_python.txt
Q: Python is converting double quotes to single quotes in new variable I'm trying to save a variable with double quotes in python, because I need to pass the double quoted JSON to a template and single quotes wont work with what I'm doing. So I set the variable in python to: json = { "auth": { "key": "auth-cod...
Python is converting double quotes to single quotes in new variable
I'm trying to save a variable with double quotes in python, because I need to pass the double quoted JSON to a template and single quotes wont work with what I'm doing. So I set the variable in python to: json = { "auth": { "key": "auth-code-here" }, "template_id": "id-here", "redirect_url": "url-here", } ...
[ "You should use a JSON module to do that. To Python, double- and single-quotes are interchangeable.\nPython has JSON abilities built in.\n" ]
[ 21 ]
[]
[]
[ "python" ]
stackoverflow_0006294501_python.txt
Q: Python New to Object Oriented Programming I was wondering how to fix this problem I am having with my first piece of OOP code. The problem lies within the attack method of the Snake class. I have two snakes in the game and am trying to get the snake to attack the other one. At the moment I am using two variables t...
Python New to Object Oriented Programming
I was wondering how to fix this problem I am having with my first piece of OOP code. The problem lies within the attack method of the Snake class. I have two snakes in the game and am trying to get the snake to attack the other one. At the moment I am using two variables to note which Snake's turn it is, then use this ...
[ "in \"attack\" you try to access \"opposite.hp\", but this method is called with a string instead of an object:\nopposite=\"alpha\"\ncurrent=\"beta\"\n\n=> change this to\nopposite=alpha\ncurrent=beta\n\nalso, there is a field and a method with the same name in the class: attack. I suggest renaming the field to \"a...
[ 2, 2, 1 ]
[]
[]
[ "object", "oop", "python" ]
stackoverflow_0006294386_object_oop_python.txt
Q: wxpython - Need help adjusting GUI Working on a program (found here, the files are longer, so posting them here would take up much space). My problem with it is that the main panel of gui_step_1.py is way off center from where it should be. I have tried numerous things, including adding it to a sizer to straighten...
wxpython - Need help adjusting GUI
Working on a program (found here, the files are longer, so posting them here would take up much space). My problem with it is that the main panel of gui_step_1.py is way off center from where it should be. I have tried numerous things, including adding it to a sizer to straighten it out, but because of my program struc...
[ "I didn't sort through everything, but I think self.v.Center() in your controller class in gui_step_1.py is repositioning a Panel within its Frame instead of centering the Frame. Get rid of that, and things seem to line up properly. If you want to add the panel to a sizer, you'll probably have to retrieve it from...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006293967_python_wxpython.txt
Q: Traversing a "list" tree and get the type(item) list with same structure in python? "tree" structured list: [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1")))] # may be more complex How to traversing it and print each item - I means the 1 and the "1"? How to generate type list with same structure? [('int','int',(...
Traversing a "list" tree and get the type(item) list with same structure in python?
"tree" structured list: [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1")))] # may be more complex How to traversing it and print each item - I means the 1 and the "1"? How to generate type list with same structure? [('int','int',('int','int',('int','str'))),('int','int','int'),('int',),'int',('int',('int',('str')))] ...
[ "You can create a generator that will traverse the tree for you for (1).\ndef traverse(o, tree_types=(list, tuple)):\n if isinstance(o, tree_types):\n for value in o:\n for subvalue in traverse(value):\n yield subvalue\n else:\n yield o\n\ndata = [(1,1,(1,1,(1,\"1\"))),...
[ 4, 3, 0 ]
[]
[]
[ "list", "python", "traversal", "tree" ]
stackoverflow_0006290105_list_python_traversal_tree.txt
Q: Python function calling I have the following class class GUI( QtGui.QMainWindow ): ''' classdocs ''' """**********************************************************************""" """ Constructor """ """*********************************...
Python function calling
I have the following class class GUI( QtGui.QMainWindow ): ''' classdocs ''' """**********************************************************************""" """ Constructor """ """**************************************************************...
[ "You have two objects that need to communicate with each other, which is a fairly standard communication problem. There's a number of ways that this problem can be solved:\n(1) Dependency Injection - Make your MCUDP() class require the MCGUI class at construction time.\nYou'll then have it available whenever you n...
[ 6, 1, 0 ]
[]
[]
[ "class", "pyqt", "python" ]
stackoverflow_0006294172_class_pyqt_python.txt
Q: Get related models in SQLAlchemy I have various models chained in SQLAlchemy (has many, belongs to, etc.). Is there a way of finding the related models given ones instance? Something like: usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users (orders, ...
Get related models in SQLAlchemy
I have various models chained in SQLAlchemy (has many, belongs to, etc.). Is there a way of finding the related models given ones instance? Something like: usersModelInstance.getRelatedTables() // This should provide an array or something with the related tables of users (orders, logins, posts, etc.).
[ "I'm not sure quite what you want -- a list of tables or a list of mapped classes?\nIn either case, first build a list of properties for your mapped object:\n# Import sqlalchemy so we can use it\nimport sqlalchemy as sa\n\n# Rename the OP's object to `obj`\nobj = usersModelInstance\n\n# Build a list of only relatio...
[ 9 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006221145_python_sqlalchemy.txt
Q: Looping through a list from a specific key to the end of the list in Python how do i loop through list starting at a key and not the beginning. e.g. l = ['a','b','c','d'] loop through l but starting at b e.g. l[1] A: The straightforward answer Just use slicing: >>> l = ['a','b','c','d'] >>> for i in l[1:]: ... ...
Looping through a list from a specific key to the end of the list
in Python how do i loop through list starting at a key and not the beginning. e.g. l = ['a','b','c','d'] loop through l but starting at b e.g. l[1]
[ "The straightforward answer\nJust use slicing:\n>>> l = ['a','b','c','d']\n>>> for i in l[1:]:\n... print(i)\n... \nb\nc\nd\n\nIt will generate a new list with the items before 1 removed:\n>>> l[1:]\n['b', 'c', 'd']\n\nA more efficient alternative\nAlternatively, if your list is huge, or you are going to slice ...
[ 38, 5, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006295185_python.txt
Q: `choice == 1` is False even when user enters "1" I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin. Here is my script: import sys print "********************************************...
`choice == 1` is False even when user enters "1"
I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin. Here is my script: import sys print "********************************************************************" print "** 1) This is menu c...
[ "You're comparing a string to an integer. Try converting the string into an integer:\nif int(choice.strip()) == 1:\n\n", "\nUse raw_input() instead of sys.stdin.readline()\nChange choice == 1 to choice == '1'\n\n", "The problem is that readline returns a string, but your if statement expects an int. To convert ...
[ 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006295296_python.txt
Q: Learning Algorithms Possible Duplicate: Learning efficient algorithms I recently came across an problem that was solved by applying the correct algorithm: Calculating plugin dependencies While I was eventually able to understand the logic of the prescribed algorithm, it was not an easy task for me. The only rea...
Learning Algorithms
Possible Duplicate: Learning efficient algorithms I recently came across an problem that was solved by applying the correct algorithm: Calculating plugin dependencies While I was eventually able to understand the logic of the prescribed algorithm, it was not an easy task for me. The only reason I was able to come u...
[ "\"Art of Computer Programming\" by Donald Knuth is a Very Useful Book.\n", "A great book is \"Introduction to Algorithms\" by Cormen, Leiserson, Rivest and Stein.\nProbably not the easiest one but it is very good indeed.\n", "I found useful for myself the following sources:\n\n\"Analysis of Algorithms : An Act...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "algorithm", "c", "python" ]
stackoverflow_0006295481_algorithm_c_python.txt
Q: Signals in PyQT4 I have I GUI and I want to estamblish some communication between two class . . . mainWidget = QtGui.QWidget() mainWidget.setLayout( mainLayout ) self.setCentralWidget( mainWidget ) self.show() """ Creating class """ self.server = MCCommunication.M...
Signals in PyQT4
I have I GUI and I want to estamblish some communication between two class . . . mainWidget = QtGui.QWidget() mainWidget.setLayout( mainLayout ) self.setCentralWidget( mainWidget ) self.show() """ Creating class """ self.server = MCCommunication.MCCommunication() s...
[ "You need to initialize the underlying QObject in your MCCommunication class. Add this line to the beginning of the __init__ method:\nsuper(MCCommunication,self).__init__()\n\n", "I don't use old style syntax for Signal and Slots.\nYou can use the new style:\nclass MCCommunication( QtCore.QObject ):\n textUpd...
[ 4, 2 ]
[]
[]
[ "pyqt", "python", "signals" ]
stackoverflow_0006295631_pyqt_python_signals.txt
Q: Tkinter events outside of the mainloop? The program I am writing has a tkinter window that is constantly being fed with data manually rather than being part of a mainloop. It also needs to track mouse location. I havn't found a workaround for tracking the mouse outside of mainloop yet, but if you have one please d...
Tkinter events outside of the mainloop?
The program I am writing has a tkinter window that is constantly being fed with data manually rather than being part of a mainloop. It also needs to track mouse location. I havn't found a workaround for tracking the mouse outside of mainloop yet, but if you have one please do tell. from Tkinter import * import random i...
[ "There is no way. Mouse movement is presented to the GUI as a series of events. In order to process events, the event loop must be running. \nAlso, you should pretty much never do a sleep inside a GUI application. All that does is freeze the GUI during the sleep. \nAnother hint: you only need to create an icicle on...
[ 6 ]
[]
[]
[ "python", "root", "tkinter" ]
stackoverflow_0006295419_python_root_tkinter.txt
Q: New to Python... Python 3 and Matplotlib I want to learn Python. I have a course to do in Python 3. However, I will need to use mainly the matplotlib and Numpy, and these libraries are not yet compatible with Python 3. Is it worth doing the course in Python 3 or will be a waste of time to learn Python 3 and then c...
New to Python... Python 3 and Matplotlib
I want to learn Python. I have a course to do in Python 3. However, I will need to use mainly the matplotlib and Numpy, and these libraries are not yet compatible with Python 3. Is it worth doing the course in Python 3 or will be a waste of time to learn Python 3 and then came back to Python 2.x? What would you do?
[ "FYI, Matplotlib is now ported to Python 3.\n", "You won't have a problem going back to Python 2.x after learning Python 3, or vice versa. There aren't too many differences. (Some standard library changes, print is a function, all strings are unicode -- you'll never notice most of them).\nRealistically, if you le...
[ 14, 13, 4, 0 ]
[]
[]
[ "matplotlib", "numpy", "python", "python_3.x" ]
stackoverflow_0004844462_matplotlib_numpy_python_python_3.x.txt
Q: Initializing multiples super classes python How could I initialize multiples super classes in python.. For example: class A (B, C): def __init__(self, param): B.__init__(self) C.__init__(self, param) # # A: Your original code works. It is very clear and readable. The call signature is cle...
Initializing multiples super classes python
How could I initialize multiples super classes in python.. For example: class A (B, C): def __init__(self, param): B.__init__(self) C.__init__(self, param) # #
[ "Your original code works. It is very clear and readable. The call signature is clear, and allows you to instantiate A with either A(p) or A(param=p).\nclass A(B, C):\n def __init__(self, param):\n B.__init__(self)\n C.__init__(self, param)\n\nIt is also possible to use super. It offers the appeali...
[ 6 ]
[]
[]
[ "class", "python" ]
stackoverflow_0006294326_class_python.txt
Q: django automated dateTime field Hello i'm working on a blog app and I have a model: class Post(models.Model): title = models.CharField(max_length=255) <..> is_published = models.BooleanField(default=False) time_publish = models.DateTimeField() time_edit = model...
django automated dateTime field
Hello i'm working on a blog app and I have a model: class Post(models.Model): title = models.CharField(max_length=255) <..> is_published = models.BooleanField(default=False) time_publish = models.DateTimeField() time_edit = models.DateTimeField(auto_now=True) ti...
[ "The simplest solution (and django compliant) is to override your model's save method.\nclass Post(models.Model):\n ...\n\n def save(self, *args, **kwargs):\n if self.is_published:\n self.time_publish = datetime.now() # don't forget import datetime\n super(Post, self).save(*args, **kw...
[ 1 ]
[]
[]
[ "automation", "datetime", "django", "python" ]
stackoverflow_0006296584_automation_datetime_django_python.txt
Q: basic python indentation/dedentation question Why does the following code produce indentation error in the Python console (version 2.6.5 in my case)? I was convinced the following was a valid piece of code: if True: print '1' print 'indentation error on this line' If I insert a blank line between the if-block...
basic python indentation/dedentation question
Why does the following code produce indentation error in the Python console (version 2.6.5 in my case)? I was convinced the following was a valid piece of code: if True: print '1' print 'indentation error on this line' If I insert a blank line between the if-block and the last print, the error goes away: if True: ...
[ "The problem is due to the usage of the Python console, not the Python language. If you put everything in a method, it works.\nExample:\n>>> if True:\n... print '1'\n... print 'indentation error on this line'\n File \"<stdin>\", line 3\n print 'indentation error on this line'\n ^\nSyntaxError: invali...
[ 5, 5 ]
[]
[]
[ "indentation", "python", "syntax" ]
stackoverflow_0006296799_indentation_python_syntax.txt
Q: Extending and loading the right content type with django models I inherited an application from another developer...and... class LowLevelModel(models.Model): content = models.TextField() def get_absolute_url(self): from foo.pages.models import DynamicPage from django.contrib.contenttypes.models import Conte...
Extending and loading the right content type with django models
I inherited an application from another developer...and... class LowLevelModel(models.Model): content = models.TextField() def get_absolute_url(self): from foo.pages.models import DynamicPage from django.contrib.contenttypes.models import ContentType my_type = ContentType.objects.get_for_model(self) try:...
[ "I don't know if it's what your looking for but I wrote a little weird extensions called django_subclass on github https://github.com/anthony-tresontani/django-subclass and it allows to get back the right object class when you call the base class manager (LowLevel... in this case)\nYou just have to register your su...
[ 1, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0006296000_django_models_python.txt
Q: Problems killing a process with Python on Solaris I have a C++ program, called C, that is designed to shut down when it receives a SIGINT signal. I've written a Python program P that runs C as a subprocess. I want P to stop C. I tried 3 things and I'd like to know why some of them didn't work. Attempt #1: import...
Problems killing a process with Python on Solaris
I have a C++ program, called C, that is designed to shut down when it receives a SIGINT signal. I've written a Python program P that runs C as a subprocess. I want P to stop C. I tried 3 things and I'd like to know why some of them didn't work. Attempt #1: import subprocess import signal import os p = subprocess.Pop...
[ "The first fails because os.killpg kills a process group, identified by its leader; you have a simple process, not a process group. Try os.kill instead. The second fails because the shell builtin kill understands symbolic signals, but the external command on Solaris doesn't (whereas on *BSD and Linux it does); us...
[ 5, 1 ]
[]
[]
[ "kill", "python", "solaris" ]
stackoverflow_0006296979_kill_python_solaris.txt
Q: Iterating though Dictionary values is not working for me in Django on GAE Data is a sorted Dict from django.utils.datastructures import SortedDict {'test1': '-10', 'quiz1': '65', 'quiz2': '40', 'quiz3': '55'} This Template Code: {% for key1 in Data %} <td>key: {{ key1|capfirst }} - value: {{Data.key1}} - D...
Iterating though Dictionary values is not working for me in Django on GAE
Data is a sorted Dict from django.utils.datastructures import SortedDict {'test1': '-10', 'quiz1': '65', 'quiz2': '40', 'quiz3': '55'} This Template Code: {% for key1 in Data %} <td>key: {{ key1|capfirst }} - value: {{Data.key1}} - Data: {{ Data }}</td> {% endfor %} Yields: key: Quiz1 - value: - Data: {'test1'...
[ "{% for key, value in Data.items %}\n <td>key: {{ key|capfirst }} - value: {{ value }} - Data: {{ Data }}</td>\n{% endfor %}\n\n", "Try this . Previous solution will work only with django >1.0\n{% for data in Data.items %}\n <td>key: {{ data.0 }}: value: {{ data.1 }}</td> \n{% endfor %}\n\n" ]
[ 1, 0 ]
[ "If i'm not wrong, SortedDict inherits from Dict, i think you can use it in this way:\n{% for key, value in Data %}\n <td>key: {{ key|capfirst }} - value: {{value}}</td>\n{% endofr %}\n\nBut i'm afraid is not clear What are the values in your dict.\n" ]
[ -1 ]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006294123_django_google_app_engine_python.txt
Q: New to OOP & Python -- Question About Storing Lots of Objects I've just started out with Python and programming and I have a general question about storing many objects. My understanding of objects so far is thus: I can define an object like: class Meal: And have functions on it such that I can find out about ...
New to OOP & Python -- Question About Storing Lots of Objects
I've just started out with Python and programming and I have a general question about storing many objects. My understanding of objects so far is thus: I can define an object like: class Meal: And have functions on it such that I can find out about it for example Meal.drink returns 'soda' and Meal.main returns 'piz...
[ "It depends what you are going for. Every piece of code can be written more efficiently, but the question you should always ask yourself first is: Why does this code have to be faster?\nIf there is no reason to make that method faster (because the count is not used that much, the list of meals has just a hundred en...
[ 6, 1, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0006296831_oop_python.txt
Q: HTML Table -- Putting a Link in the Header for Sorting? (No JavaScript) I'm dynamically generating a table, as well as the column headers. How do I make the columns clickable (NO JavaScript!), so that when they're clicked, they add a sort=columnNameHere entry to the query, and reload the current page with that que...
HTML Table -- Putting a Link in the Header for Sorting? (No JavaScript)
I'm dynamically generating a table, as well as the column headers. How do I make the columns clickable (NO JavaScript!), so that when they're clicked, they add a sort=columnNameHere entry to the query, and reload the current page with that query?
[ "It would be helpful to know your server-side language, but since you didn't include that, you'll want the code to output html as follows...\n<table>\n <thead>\n <th><a href=\"test.html?sort=Name\">Name</a></th>\n <th><a href=\"test.html?sort=Location\">Location</a></th>\n </thead>\n <tr>\n <td...
[ 3, 0 ]
[]
[]
[ "django", "html", "hyperlink", "python" ]
stackoverflow_0006297149_django_html_hyperlink_python.txt
Q: unicode in dictionary gives hex output I have a dictionary (key, value) pair. The key is 'ASCII' (e.g. 'hello'), the value is not English (e.g. Chinese 輸入曲目). Some code: t_t = {} s_0 = 'hello' s_v = '輸入曲目' print s_v # gives the Chinese 輸入曲目 t_t[s_0] = s_v print t_t.values() The ou...
unicode in dictionary gives hex output
I have a dictionary (key, value) pair. The key is 'ASCII' (e.g. 'hello'), the value is not English (e.g. Chinese 輸入曲目). Some code: t_t = {} s_0 = 'hello' s_v = '輸入曲目' print s_v # gives the Chinese 輸入曲目 t_t[s_0] = s_v print t_t.values() The output is in hex (e.g. '\x39\xef') Even access...
[ "You'll need to walk the values manually. The print is turning it in to hex because you're asking it to print the whole tuple, and print sees your string as arbitrary binary data. So as to not totally mess up some folks terminals, it encodes potentially unprintable characters as hex. The contents of the string isn'...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0006297146_python.txt
Q: How to structure re-used code between modules I'm pretty new to Python and, in writing an app, have ended up with a structure that's a bit of a mess. The example below should illustrate what I'm trying to do. The issue is that I can't call the login method from common.py because it is only defined in website1.py o...
How to structure re-used code between modules
I'm pretty new to Python and, in writing an app, have ended up with a structure that's a bit of a mess. The example below should illustrate what I'm trying to do. The issue is that I can't call the login method from common.py because it is only defined in website1.py or website2.py. Module common.py class Browser(): ...
[ "First of all, why static methods? You could just do def login at the global level.\nSecond of all, you could pass a class reference to the Browser class. (or a module reference if you take my first suggestion)\nclass Browser(object):\n def __init__(self, loginCls):\n self.loginCls = loginCls\n\n def l...
[ 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0006297313_module_python.txt
Q: python read(4) returning a string of length 1 not 4 I have a large binary file of ieee 32bit floating point numbers. In python I use: f = file.read(4) while f !='': if len(f) == 4: data =struct.unpack('>f', f) print data f = file.read(4) to read it 4 bytes at a time However, o...
python read(4) returning a string of length 1 not 4
I have a large binary file of ieee 32bit floating point numbers. In python I use: f = file.read(4) while f !='': if len(f) == 4: data =struct.unpack('>f', f) print data f = file.read(4) to read it 4 bytes at a time However, occasionally f would be size 1, and struct.unpack would co...
[ "Did you open the file in binary mode?\nAnyway, a much better way to read your file is to use array.fromfile() or NumPy.\n", "First of all, i recommend against the use of the word file as a variable, as it is a __builtin__ function. \nSecondly, binary mode or ascii mode?\n", "See this page: file.read\nSpecifica...
[ 4, 3, 3 ]
[]
[]
[ "binaryfiles", "floating_point", "io", "python" ]
stackoverflow_0006297380_binaryfiles_floating_point_io_python.txt
Q: Generator decorator in Python PEP343 defines a “Generator Decorator,” and says “A robust implementation of this decorator will be made part of the standard library.” Where is this in the standard library? Does anyone use it? A: It's here: contextlib.contextmanager. I never used it.
Generator decorator in Python
PEP343 defines a “Generator Decorator,” and says “A robust implementation of this decorator will be made part of the standard library.” Where is this in the standard library? Does anyone use it?
[ "It's here: contextlib.contextmanager. I never used it.\n" ]
[ 2 ]
[]
[]
[ "decorator", "generator", "python" ]
stackoverflow_0006297482_decorator_generator_python.txt
Q: Sorting entities and filtering ListProperty without incurring in exploding indexes I'm developing a simple Blogging/Bookmarking platform and I'm trying to add a tags-explorer/drill-down feature a là delicious to allow users to filter the posts specifying a list of specific tags. Something like this: Posts are rep...
Sorting entities and filtering ListProperty without incurring in exploding indexes
I'm developing a simple Blogging/Bookmarking platform and I'm trying to add a tags-explorer/drill-down feature a là delicious to allow users to filter the posts specifying a list of specific tags. Something like this: Posts are represented in the datastore with this simplified model: class Post(db.Model): title = ...
[ "What if you inverted the relationship? Instead of a post with a list of tags you would have a tag entity with a list of posts.\nclass Tag(db.Model):\n tag = db.StringProperty()\n posts = db.ListProperty(db.Key, indexed=False)\n\nTo search for tags you would do tags = Tag.all().filter('tag IN', ['python','blog','...
[ 3, 3, 2, 0 ]
[]
[]
[ "explode", "google_app_engine", "google_cloud_datastore", "indexing", "python" ]
stackoverflow_0006108051_explode_google_app_engine_google_cloud_datastore_indexing_python.txt
Q: Inheritance from models.User: how to escape a situation when user data kept in 2 tables in a database? The situation is: we need a model class storing user profile data (his profession, country, region, city, etc.). According to official Django documentation we should do something like the next: ... class MyUser( ...
Inheritance from models.User: how to escape a situation when user data kept in 2 tables in a database?
The situation is: we need a model class storing user profile data (his profession, country, region, city, etc.). According to official Django documentation we should do something like the next: ... class MyUser( models.User ): profession = models.CharField( max_length = 64 ) # other fields... ... The problem is: t...
[ "As recommended in the docs you can use a \"user profile\" to store additional information about users:\nclass UserProfile(models.Model):\n user = models.ForeignKey(User, unique=True)\n\n profession = models.CharField( max_length = 64 )\n # other fields...\n\nYou can access it by user.get_profile().profess...
[ 1 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0006296654_django_postgresql_python.txt
Q: How do I read the arguments in "args" passed to a builtin function in Python [source]? Example (builtinmodule.c): static PyObject * builtin___import__(PyObject *self, PyObject *args, PyObject *kwds) { ... } How do I go about getting the arguments, args, in string format? I believe it would be similar to findi...
How do I read the arguments in "args" passed to a builtin function in Python [source]?
Example (builtinmodule.c): static PyObject * builtin___import__(PyObject *self, PyObject *args, PyObject *kwds) { ... } How do I go about getting the arguments, args, in string format? I believe it would be similar to finding the name of a function (if a callable PyObject was a function: PyString_AsString(PyObjec...
[ "The easiest thing to do is just get the repr of the object, since it's a tuple.\n" ]
[ 2 ]
[]
[]
[ "cpython", "python", "python_2.6" ]
stackoverflow_0006297634_cpython_python_python_2.6.txt
Q: How to check if this is the index page in Django? How can I check of the present page is the index page in a Django template? {% if What Goes Here??? %} // whatever {% endif %} A: TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', ... ) {% if request.path == "/" %} ... {% en...
How to check if this is the index page in Django?
How can I check of the present page is the index page in a Django template? {% if What Goes Here??? %} // whatever {% endif %}
[ "TEMPLATE_CONTEXT_PROCESSORS = (\n 'django.core.context_processors.request',\n ...\n)\n\n\n{% if request.path == \"/\" %}\n ...\n{% endif %}\n\n", "You can just add your template code to the index page template itself.\n" ]
[ 14, -2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006298003_django_python.txt
Q: How to start python programs with appropriate python version? Given a set of python programs: /tool/a.py /tool/b.py /tool/c.py /tool/d.py ... that are stored in a shared network directory, executed in a mixed environment (Solaris and different flavors of Linux) and that all requires a specific python version that...
How to start python programs with appropriate python version?
Given a set of python programs: /tool/a.py /tool/b.py /tool/c.py /tool/d.py ... that are stored in a shared network directory, executed in a mixed environment (Solaris and different flavors of Linux) and that all requires a specific python version that may not be in the users $PATH and may not be installed in the same...
[ "\nI know this isn't quite the answer you are looking for, but I'd just make sure the python executables are in the PATH and then use env to find them. In the long run, I think this will be a lot less maintenance and headache. E.g.\n#!/usr/bin/env python2.5\nprint \"Hello from python 2.5!\"\n\n \n#!/usr/bin/env pyt...
[ 4, 1, 1, 1 ]
[]
[]
[ "bash", "execve", "python", "shebang", "wrapper" ]
stackoverflow_0006298138_bash_execve_python_shebang_wrapper.txt
Q: Is there a buildout recipe that uses pip but does not install virtualenv? I would like to use buildout rather than virtualenv. This decision means that I don't want virtualenv to be snuck into my kit, so I am looking for either a way to tell gp.recipe.pip not to install the virtualenv meme virus, or, a way to ins...
Is there a buildout recipe that uses pip but does not install virtualenv?
I would like to use buildout rather than virtualenv. This decision means that I don't want virtualenv to be snuck into my kit, so I am looking for either a way to tell gp.recipe.pip not to install the virtualenv meme virus, or, a way to install packages from git repos for use with django/djangorecipe. Ideas?
[ "Sure,\nYou want to use mr.developer in your buildout.\nSpecifically, (taken from the mr.developer page), something like:\n[buildout]\nextensions = mr.developer\nauto-checkout = my.package\n\n[sources]\nmy.package = svn http://example.com/svn/my.package/trunk update=true\nsome.other.package = git git://example.com/...
[ 5 ]
[]
[]
[ "buildout", "pip", "python", "virtualenv" ]
stackoverflow_0001859421_buildout_pip_python_virtualenv.txt
Q: Python multiprocessing.Queue deadlocks on put and get I'm having deadlock problems with this piece of code: def _entropy_split_parallel(data_train, answers_train, weights): CPUS = 1 #multiprocessing.cpu_count() NUMBER_TASKS = len(data_train[0]) processes = [] multi_list = zip(data_train, answers_...
Python multiprocessing.Queue deadlocks on put and get
I'm having deadlock problems with this piece of code: def _entropy_split_parallel(data_train, answers_train, weights): CPUS = 1 #multiprocessing.cpu_count() NUMBER_TASKS = len(data_train[0]) processes = [] multi_list = zip(data_train, answers_train, weights) task_queue = multiprocessing.Queue() ...
[ "I think the problem is the parent thread joining a child thread to which it has passed a Queue. This is discussed the the multiprocessing module's programming guidelines section.\nAt any rate, I encountered the same symptom that you describe, and when I refactored my logic so that the master thread did not join th...
[ 4, 0 ]
[]
[]
[ "concurrency", "deadlock", "multiprocessing", "python", "queue" ]
stackoverflow_0003121622_concurrency_deadlock_multiprocessing_python_queue.txt
Q: python: parsing strings from serial.read() I'm communicating between a python script on a PC and embedded c. I have the following issue: From the mcu (embedded c), I'm sending the binary representation of integers and floats. Using Br@y's terminal, I have verified that the binary representation of the numbers ar...
python: parsing strings from serial.read()
I'm communicating between a python script on a PC and embedded c. I have the following issue: From the mcu (embedded c), I'm sending the binary representation of integers and floats. Using Br@y's terminal, I have verified that the binary representation of the numbers are being sent from the mcu. In the python script,...
[ "Are you sure the \\x is in the string? That looks like Python's representation string (repr) for binary data, but the characters \\x are not actually in the string. \nThe struct module can unpack the binary data.\ns = '\\x10\\x00\\x00\\x00'\ni = struct.unpack(\"I\", s)[0]\n\ni is now 16 (int).\n", "Python always...
[ 2, 2 ]
[]
[]
[ "ascii", "hex", "pyserial", "python" ]
stackoverflow_0006298219_ascii_hex_pyserial_python.txt
Q: Python ctypes: How do I flush output from stderr? I've written some function callbacks using python's ctypes to access functions in a DLL. The code used to build that DLL has some debugging print statements in it using fprintf to stderr. However, when I run my python code, I don't see that output to stderr consi...
Python ctypes: How do I flush output from stderr?
I've written some function callbacks using python's ctypes to access functions in a DLL. The code used to build that DLL has some debugging print statements in it using fprintf to stderr. However, when I run my python code, I don't see that output to stderr consistently. Only rarely I will see it flush the output fr...
[ "It's all the same stderr.\nsys.stderr.flush()\n\n" ]
[ 22 ]
[]
[]
[ "ctypes", "dll", "python", "windows" ]
stackoverflow_0006298940_ctypes_dll_python_windows.txt
Q: re.findall how to return matches with repeated ones I have list of IP:PORT in html and when i use findall to search all ip i get the list of all ip becouse IP are unique , some of ports are the same and i get by example list of 100 IP's and only 87 ports. How to find all ports with the repeated ones ? proxies = r...
re.findall how to return matches with repeated ones
I have list of IP:PORT in html and when i use findall to search all ip i get the list of all ip becouse IP are unique , some of ports are the same and i get by example list of 100 IP's and only 87 ports. How to find all ports with the repeated ones ? proxies = re.findall("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}...
[ "Without seeing the source file, I can only make some basic points.\n\nPort numbers are not limited to 3 digits, so you are excluding any port over 999\nDo the port numbers only show up as a list of 4 ports? You said the format was a list of IP:PORT, but that is not what you are checking for.\n\nEDIT:\nLook at the ...
[ 2, 0 ]
[]
[]
[ "findall", "python" ]
stackoverflow_0006298444_findall_python.txt
Q: How can I use Django with MySQL in MAMP stack? I have difficulty especially in installing MySQLdb module (MySQL-python-1.2.3c1), to connect to the MySQL in MAMP stack. I've done a number of things such as copying the mysql include directory and library (including plugin) from a fresh installation of mysql (version...
How can I use Django with MySQL in MAMP stack?
I have difficulty especially in installing MySQLdb module (MySQL-python-1.2.3c1), to connect to the MySQL in MAMP stack. I've done a number of things such as copying the mysql include directory and library (including plugin) from a fresh installation of mysql (version 5.1.47) to the one inside MAMP (version 5.1.37). No...
[ "How are you installing MySQL-Python? I just tested in a fresh virtualenv and pip install mysql-python seems to have done the trick.\nUPDATE:\npip is sort of like a package manager for Python packages.\nBy default, pip installs to your current site-packages directory, which is on your $PYTHONPATH. This lets other l...
[ 1, 0 ]
[]
[]
[ "django", "mamp", "mysql", "python" ]
stackoverflow_0002900088_django_mamp_mysql_python.txt
Q: Python: exec statement and unexpected garbage collector behavior I found a problem with exec (It happened in a system that has to be extensible with user written scripts). I could reduce the problem itself to this code: def fn(): context = {} exec ''' class test: def __init__(self): self.buf = ...
Python: exec statement and unexpected garbage collector behavior
I found a problem with exec (It happened in a system that has to be extensible with user written scripts). I could reduce the problem itself to this code: def fn(): context = {} exec ''' class test: def __init__(self): self.buf = '1'*1024*1024*200 x = test()''' in context fn() I expected that memo...
[ "The reason that you're seeing it take up 200Mb of memory for longer than you expect is because you have a reference cycle: context is a dict referencing both x and test. x references an instance of test, which references test. test has a dict of attributes, test.__dict__, which contains the __init__ function for t...
[ 5, 0 ]
[]
[]
[ "exec", "garbage_collection", "python" ]
stackoverflow_0006297047_exec_garbage_collection_python.txt
Q: Python: Extract video stream link from a page I wonder if there is a way to extract a video stream link from a page. For example in Youtube and in the page http://www.youtube.com/watch?v=he5fpsmH_2g extract the actual download link of the video and download it, just like what VideoGet does. Thanks in advance. A: ...
Python: Extract video stream link from a page
I wonder if there is a way to extract a video stream link from a page. For example in Youtube and in the page http://www.youtube.com/watch?v=he5fpsmH_2g extract the actual download link of the video and download it, just like what VideoGet does. Thanks in advance.
[ "Have a look in the src-code for clive to see how it can be done from a script.\n" ]
[ 1 ]
[]
[]
[ "python", "video_streaming" ]
stackoverflow_0006299518_python_video_streaming.txt
Q: How do I close an ssh Tunnel opened through Popen in python I need to create an ssh tunnel, then do something, then tear the tunnel down. I have been trying to do it like this: def runCmd(self,cmd): args = shlex.split(cmd) return subprocess.Popen(args) def openTunnel cmd = 'ssh -f -N -L 1313:localhost...
How do I close an ssh Tunnel opened through Popen in python
I need to create an ssh tunnel, then do something, then tear the tunnel down. I have been trying to do it like this: def runCmd(self,cmd): args = shlex.split(cmd) return subprocess.Popen(args) def openTunnel cmd = 'ssh -f -N -L 1313:localhost:1313 userid@server.com' self.TunnelObj = self.runCmd(cmd) T...
[ "Part of the problem is that the tunnel process is a subprocess of self.TunnelObj. You can try to omit the -f flag so you hold the tunnel process directly.\nAnother option would be to look at the paramiko library and this question.\n" ]
[ 2 ]
[]
[]
[ "popen", "python", "ssh_tunnel" ]
stackoverflow_0006298482_popen_python_ssh_tunnel.txt
Q: Haversine's formula in sqlalchemy I'm having the following lines in my code query = "SELECT id, " \ "( 3959 * acos( cos( radians(37) ) * cos( radians( %(lat)i ) ) * " \ "cos( radians( %(lng)i ) - radians(-122) ) + sin( radians(37) ) * " \ "sin( radians( %(lat)i ) ) ) ) AS `distance` fro...
Haversine's formula in sqlalchemy
I'm having the following lines in my code query = "SELECT id, " \ "( 3959 * acos( cos( radians(37) ) * cos( radians( %(lat)i ) ) * " \ "cos( radians( %(lng)i ) - radians(-122) ) + sin( radians(37) ) * " \ "sin( radians( %(lat)i ) ) ) ) AS `distance` from message where" \ " `distance`...
[ "You cannot reference the named expression (distance) in the WHERE clause (I don't know if this is generally true for all database systems, but it is at least so for MySQL). You can use HAVING instead (see option C).\nOptions:\nA. Repeat the expression again in the where clause:\nSELECT id, (long_formula) as distan...
[ 5, 0 ]
[]
[]
[ "haversine", "python", "sql", "sqlalchemy" ]
stackoverflow_0006299273_haversine_python_sql_sqlalchemy.txt
Q: How can I pass a Python StringIO() object to a ZipFile(), or is it not supported? I have a StringIO() file-like object, and I am trying to write it to a ZipFile(), but I get this TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found Here is a sample of the code I am using: file_like = Str...
How can I pass a Python StringIO() object to a ZipFile(), or is it not supported?
I have a StringIO() file-like object, and I am trying to write it to a ZipFile(), but I get this TypeError: coercing to Unicode: need string or buffer, cStringIO.StringI found Here is a sample of the code I am using: file_like = StringIO() archive = zipfile.ZipFile(file_like, 'w', zipfile.ZIP_DEFLATED) # my_file is a...
[ "To add a string to a ZipFile you need to use the writestr method and pass the string from StringIO using getvalue method of the StringIO instance\ne.g.\narchive.writestr(\"name of file in zip\", my_file.getvalue())\n\nNote you also need to give the name of the string to say where it is placed in the zip file.\n" ]
[ 13 ]
[]
[]
[ "python", "python_zipfile", "stringio" ]
stackoverflow_0006299724_python_python_zipfile_stringio.txt
Q: Unlabeled exception in threading I have a chunk of code like this def f(x): try: g(x) except Exception, e: print "Exception %s: %d" % (x, e) def h(x): thread.start_new_thread(f, (x,)) Once in a while, I get this: Unhandled exception in thread started by Error in sys.excepthook: Origin...
Unlabeled exception in threading
I have a chunk of code like this def f(x): try: g(x) except Exception, e: print "Exception %s: %d" % (x, e) def h(x): thread.start_new_thread(f, (x,)) Once in a while, I get this: Unhandled exception in thread started by Error in sys.excepthook: Original exception was: Unlike the code sam...
[ "The error you're seeing means the interpreter was exiting (because the main thread exited) while another thread was still executing Python code. Python will clean up its environment, cleaning out and throwing away all of the loaded modules (to make sure as many finalizers as possible execute) but unfortunately tha...
[ 5 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006300006_multithreading_python.txt
Q: How to uncollapse a list with coma separated columns in python? I'm working in a code and I have a list like: listA = ( ['name1', 'A11,A12,A13', 'B11,B12,B13', 'C11,C12,C13'], ['name2', 'A21,A22', 'B21,B22', 'C21,C22'], ['name3', 'A31,A32,A33,A34,A35', 'B31,B32,B33,B34,B35', 'C31,C32,C33,C34,C35' ], ) ...
How to uncollapse a list with coma separated columns in python?
I'm working in a code and I have a list like: listA = ( ['name1', 'A11,A12,A13', 'B11,B12,B13', 'C11,C12,C13'], ['name2', 'A21,A22', 'B21,B22', 'C21,C22'], ['name3', 'A31,A32,A33,A34,A35', 'B31,B32,B33,B34,B35', 'C31,C32,C33,C34,C35' ], ) and I need to get: listA = ( ['name1', 'A11', 'B11', 'C11'], ...
[ "list_b = []\nfor x in list_a:\n i = iter(x)\n name = next(i)\n list_b.extend((name,) + t for t in zip(*(y.split(\",\") for y in i)))\n\n", "Kinda ugly, but...\nlistB = []\nfor tup in listA:\n tmptup = []\n for elt in tup:\n splt = elt.split(',')\n for n in splt:\n tmptup.append(n)\n listB....
[ 4, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006300461_list_python.txt
Q: What can be done about "The command is too long to execute" error in MATLAB? I am calling a Python program from MATLAB and passing an array to the program. I am writing the following lines in MATLAB workspace: % Let us assume some random array num1 = ones(1,100); % I am forced to pass parameters as string due...
What can be done about "The command is too long to execute" error in MATLAB?
I am calling a Python program from MATLAB and passing an array to the program. I am writing the following lines in MATLAB workspace: % Let us assume some random array num1 = ones(1,100); % I am forced to pass parameters as string due to the MATLAB-Python interaction. num2 = num2str(num1); % The function is s...
[ "On Windows, the command passed to the dos function is limited to 32768 characters. This limitation comes from the Windows limitation on the lpCommandLine parameter to CreateProcess.\nI think Fredrik's idea of writing the data to a file and reading it from Python is your best alternative.\n" ]
[ 8 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0006298619_matlab_python.txt
Q: 'Unstarring' posts using Google Reader API Does anybody know how to remove stars for articles starred in Google Reader using its unofficial API? I found this one but it doesn't work: http://www.niallkennedy.com/blog/2005/12/google-reader-api.html Neither does the pyrfeed module in Python, I get the IOError except...
'Unstarring' posts using Google Reader API
Does anybody know how to remove stars for articles starred in Google Reader using its unofficial API? I found this one but it doesn't work: http://www.niallkennedy.com/blog/2005/12/google-reader-api.html Neither does the pyrfeed module in Python, I get the IOError exception every time.
[ "Try using:\nr=user%2F[user ID]%2Fstate%2Fcom.google%2Fstarred \n\ninstead of\na=user%2F[user ID]%2Fstate%2Fcom.google%2Fstarred \n\nwhen invoking edit-tag.\n", "I don't have Python code for this (I have Java), but the problem you're stumbling with is pretty much independent from the language you use, and it is a...
[ 1, 0 ]
[]
[]
[ "google_reader", "python" ]
stackoverflow_0001018626_google_reader_python.txt
Q: Django - queryset and general SQL questions Firstly, given a model Foo and it's m2m pointing to Bar, how does the following query work (when nothing really is NULL per se (join and first part ommited): >> print Foo.objects.get(bar__isnull=True).query ...WHERE "barapp_bar"."id" IS NULL The null stuff throws me off...
Django - queryset and general SQL questions
Firstly, given a model Foo and it's m2m pointing to Bar, how does the following query work (when nothing really is NULL per se (join and first part ommited): >> print Foo.objects.get(bar__isnull=True).query ...WHERE "barapp_bar"."id" IS NULL The null stuff throws me off with regards to filtering by related m2m. Second...
[ "The ommitted joins are important. If you look at the full query, you will see that Django does two Left Outer Joins from the foo table to the joining table foo_bar and to the bar table.\nConsider two foos and two bars. Let foo_1 be related to bar_1 and bar_2, and foo_2 not be related to any bars.\nThe query below ...
[ 0 ]
[]
[]
[ "django", "django_queryset", "python", "query_optimization" ]
stackoverflow_0006299903_django_django_queryset_python_query_optimization.txt
Q: Django template and XML question I have this Django view that does render_to_response(rss.xml, {"list":list}) with this list: <a href="link.html">description</a> <a href="link2.html">description2</a> <a href="link3.html">description3</a> the rss.xml template is the following: <?xml version="1.0" encoding="UTF-8"?...
Django template and XML question
I have this Django view that does render_to_response(rss.xml, {"list":list}) with this list: <a href="link.html">description</a> <a href="link2.html">description2</a> <a href="link3.html">description3</a> the rss.xml template is the following: <?xml version="1.0" encoding="UTF-8"?><rss version="0.92"> {% for i...
[ "You should surround the for block with autoescape tags like so:\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss version=\"0.92\">\n{% autoescape off %}\n {% for item in list%}\n {{item}}\n {% endfor %}\n{% endautoescape %}\n\ndjango won't escape the characters between the autoescape tags\nsee here:\nhttps...
[ 5, 3 ]
[]
[]
[ "django", "python", "xml" ]
stackoverflow_0006300896_django_python_xml.txt
Q: find the dot product of sub-arrays in numpy In numpy, the numpy.dot() function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where Z[i] == numpy.dot(X[i], Y[i]) for all i. Is this possible to do non-iteratively? A: How abo...
find the dot product of sub-arrays in numpy
In numpy, the numpy.dot() function can be used to calculate the matrix product of two 2D arrays. I have two 3D arrays X and Y (say), and I'd like to calculate the matrix Z where Z[i] == numpy.dot(X[i], Y[i]) for all i. Is this possible to do non-iteratively?
[ "How about:\nfrom numpy.core.umath_tests import inner1d\nZ = inner1d(X,Y)\n\nFor example:\nX = np.random.normal(size=(10,5))\nY = np.random.normal(size=(10,5))\nZ1 = inner1d(X,Y)\nZ2 = [np.dot(X[k],Y[k]) for k in range(10)]\nprint np.allclose(Z1,Z2)\n\nreturns True\nEdit Correction since I didn't see the 3D part of...
[ 8 ]
[]
[]
[ "matrix_multiplication", "numpy", "python" ]
stackoverflow_0006299770_matrix_multiplication_numpy_python.txt
Q: "Unrolling" a recursive function? I'm writing a path tracer in C++ and I'd like to try and implement the most resource-intensive code into CUDA or OpenCL (I'm not sure which one to pick). I've heard that my graphics card's version of CUDA doesn't support recursion, which is something my path tracer utilizes heavil...
"Unrolling" a recursive function?
I'm writing a path tracer in C++ and I'd like to try and implement the most resource-intensive code into CUDA or OpenCL (I'm not sure which one to pick). I've heard that my graphics card's version of CUDA doesn't support recursion, which is something my path tracer utilizes heavily. As I have it coded both in Python an...
[ "In a recursive function, each time a recursive call occurs, the state of the caller is saved to a stack, then restored when the recursive call is complete. To convert a recursive function to an iterative one, you need to turn the state of the suspended function into an explicit data structure. Of course, you can...
[ 20, 3, 1 ]
[]
[]
[ "cuda", "opencl", "python", "recursion" ]
stackoverflow_0006300695_cuda_opencl_python_recursion.txt
Q: How to receive socket information if you don't know how much data is coming through? I am working on a GUI interface based on Python to interact with a robot running Python and an Arduino Mega as a motor controller and sensor controller. Originally, I was going to use a remote desktop to load my GUI from the robot...
How to receive socket information if you don't know how much data is coming through?
I am working on a GUI interface based on Python to interact with a robot running Python and an Arduino Mega as a motor controller and sensor controller. Originally, I was going to use a remote desktop to load my GUI from the robot. This turned out to be very slow because of the remote desktop. I decided that a server ...
[ "I think I found three problems in this code; the first is wasteful, and the second is probably why you came here today, and the third is why you think you came in today. :)\nBusy Waiting\nThis code is busy waiting for data to come in on the connection:\nconnection.setblocking(0)\nprint \"Connected by\", addr[0]\nw...
[ 5 ]
[]
[]
[ "arduino", "beagleboard", "python" ]
stackoverflow_0006300919_arduino_beagleboard_python.txt
Q: django, location based searches Excuse my ignorance, I am not even sure of the correct term for this. What I want to do is search by city and state or zip code in my django application and also include results within certain distances of the location (25, 50, 75 miles). I am guessing you probably need to convert ...
django, location based searches
Excuse my ignorance, I am not even sure of the correct term for this. What I want to do is search by city and state or zip code in my django application and also include results within certain distances of the location (25, 50, 75 miles). I am guessing you probably need to convert the city and state or zip code to lat...
[ "You could use GeoDjango, which already includes these features. Otherwise you can do exactly as you said: geocode addresses to get latitude and longitude, then just do the math ;-)\n", "You can also use MongoDB which will have better optimization, cf. Python geocode filtering by distance\nhttp://www.mongodb.org/...
[ 7, 2 ]
[]
[]
[ "django", "geodjango", "geolocation", "python" ]
stackoverflow_0002045318_django_geodjango_geolocation_python.txt
Q: Python Yield Statement does not appear to continue where it left off I must be overlooking the obvious, but I cannot for the life of me figure out why this yield statement does not continually give me a new datetime value that is 15 minutes later than the previous one. The gettime function is behaving more like a...
Python Yield Statement does not appear to continue where it left off
I must be overlooking the obvious, but I cannot for the life of me figure out why this yield statement does not continually give me a new datetime value that is 15 minutes later than the previous one. The gettime function is behaving more like a function that "returns" rather than "yields". import datetime #function ...
[ "It's because you're calling the generator each time, starting it anew.\nHere is a fixed version:\ndates = gettime(nextdate)\nfor i in range(0, 25):\n print dates.next() # note that you're not initializing it each time here\n # just calling next()\n\nThat gives me:\n2011-08-22 11:00:00\...
[ 15, 3, 0 ]
[]
[]
[ "python", "yield" ]
stackoverflow_0006301249_python_yield.txt
Q: Python API to Access Trash Folder I am looking for a good python API to access the Trash folder in Linux. This is part of a simple productivity software that will help user organize their files, and empty their trash folder on a regular basis. I want to make this work for GNOME, but I would like to expand it to ot...
Python API to Access Trash Folder
I am looking for a good python API to access the Trash folder in Linux. This is part of a simple productivity software that will help user organize their files, and empty their trash folder on a regular basis. I want to make this work for GNOME, but I would like to expand it to other desktop environment. Do you have an...
[ "I don't think that there is an API for that. I think (or rather, the voices in my head on the internet say) \"Empty Trash\" is a map to rm -rf ~/.Trash/*. (Actually, that should be true for both KDE and Gnome, but I don't know about XFCE, Slim or XKCD. Of course, if you have XKCD as a windows manager, I don't thin...
[ 1 ]
[]
[]
[ "api", "freedesktop.org", "linux", "python" ]
stackoverflow_0006300870_api_freedesktop.org_linux_python.txt
Q: How can I get specific elements from XML data? I have some code to retrieve XML data: import cStringIO import pycurl from xml.etree import ElementTree _API_KEY = 'my api key' _ima = '/the/path/to/a/image' sock = cStringIO.StringIO() upl = pycurl.Curl() values = [ ("key", _API_KEY), ("im...
How can I get specific elements from XML data?
I have some code to retrieve XML data: import cStringIO import pycurl from xml.etree import ElementTree _API_KEY = 'my api key' _ima = '/the/path/to/a/image' sock = cStringIO.StringIO() upl = pycurl.Curl() values = [ ("key", _API_KEY), ("image", (upl.FORM_FILE, _ima))] upl.setopt(upl.URL, "...
[ "Your find() call is trying to find an immediate child of the top of the tree with a tag named original, not a tag at any lower level than that. Use:\nurl = tree.find('.//original').text\n\nif you want to find all elements in the tree with the tag named original. The pattern matching rules for ElementTree's find() ...
[ 2 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0006301700_python_xml_xml_parsing.txt
Q: SQLite Concurrency with Python? Suppose that I have a huge SQLite file (say, 500[MB]). Can 10 different python instances access this file at the same time and update different records of it?. Note, the emphasis here is on different records. For example, suppose that the SQLite file has say 1M rows: instance 1 will...
SQLite Concurrency with Python?
Suppose that I have a huge SQLite file (say, 500[MB]). Can 10 different python instances access this file at the same time and update different records of it?. Note, the emphasis here is on different records. For example, suppose that the SQLite file has say 1M rows: instance 1 will deal with (and update) rows 0 - 1000...
[ "Updated, thanks to André Caron. \nYou can do that, but only read operations supports concurrency in SQLite, since entire database is locked on any write operation. SQLite engine will return SQLITE_BUSY status in this situation (if it exceeds default timeout for access). Also consider that this heavily depends on h...
[ 4, 4 ]
[]
[]
[ "concurrency", "python", "sqlite" ]
stackoverflow_0006301816_concurrency_python_sqlite.txt
Q: Precision of cdf in scipy.stats I'm using chi2 distribution as a theoretical problem for a simulation system. For a given interval, I need to estimate this distribution as a PMF defined as the integral of the PDF inside that interval. This value should be near the value of the PDF at the center of the interval, bu...
Precision of cdf in scipy.stats
I'm using chi2 distribution as a theoretical problem for a simulation system. For a given interval, I need to estimate this distribution as a PMF defined as the integral of the PDF inside that interval. This value should be near the value of the PDF at the center of the interval, but can be slightly different, dependin...
[ "cdf is within floating point precision equal to one, but sf is close to zero, so tiny differences, 1e-20, are not covered up by the big 1. (see JABS reference)\n>>> probs_from_cdf = np.diff(stats.chi2.cdf(np.arange(nbins+1), 10))\n>>> probs_from_sf = np.diff(stats.chi2.sf(np.arange(nbins+1)[::-1], 10))[::-1]\n>>> ...
[ 8, 7 ]
[]
[]
[ "cdf", "numpy", "precision", "python", "scipy" ]
stackoverflow_0006298105_cdf_numpy_precision_python_scipy.txt
Q: How do I reverse an itertools.chain object? My function creates a chain of generators: def bar(num): import itertools some_sequence = (x*1.5 for x in range(num)) some_other_sequence = (x*2.6 for x in range(num)) chained = itertools.chain(some_sequence, some_other_sequence) return chained My fu...
How do I reverse an itertools.chain object?
My function creates a chain of generators: def bar(num): import itertools some_sequence = (x*1.5 for x in range(num)) some_other_sequence = (x*2.6 for x in range(num)) chained = itertools.chain(some_sequence, some_other_sequence) return chained My function sometimes needs to return chained in rever...
[ "if num < 0:\n lst = list(chained)\n lst.reverse()\n return lst\nelse:\n return chained\n\nreversed() needs an actual sequence, because it iterates it backwards by index, and that wouldn't work for a generator (which only has the notion of \"next\" item).\nSince you will need to unroll the whole generat...
[ 12, 11, 4, 1, 0, 0, 0 ]
[]
[]
[ "generator", "python", "python_itertools" ]
stackoverflow_0005008921_generator_python_python_itertools.txt
Q: Filtering a query by an entity's child in app engine (python) I have a question model and a response model whos parent is set to a specific question like such: class Question(db.Model): myQuestion = db.StringProperty() class Response(db.Model): responder = db.ReferenceProperty(reference_class = User, collecti...
Filtering a query by an entity's child in app engine (python)
I have a question model and a response model whos parent is set to a specific question like such: class Question(db.Model): myQuestion = db.StringProperty() class Response(db.Model): responder = db.ReferenceProperty(reference_class = User, collection_name = 'my_responses') myResponse = db.StringProperty() def c...
[ "One solution would be to keep a list of questions the user has responded to. You could Keep these lists in the user's entity group, and use the current month (for example) as the key name.\nclass QuestionsAnswered(db.Model):\n answered = db.ListProperty(db.Key)\n\nSet QuestionsAnswered entity's key-names to th...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006301454_google_app_engine_google_cloud_datastore_python.txt
Q: Retrieve tweets of a twitter account starting from certain date to current date I want to write a script that retrieve the tweets from a twitter account. Here is the scenario that I would like to achieve: my script should be able to retrieve all tweets of a user starting from certain date (can be set by the user t...
Retrieve tweets of a twitter account starting from certain date to current date
I want to write a script that retrieve the tweets from a twitter account. Here is the scenario that I would like to achieve: my script should be able to retrieve all tweets of a user starting from certain date (can be set by the user to any date as long as it's older than current date), until current date. Example: I ...
[ "If you're happy with a limit of 3000 statuses you could look at this method. Keep repeating this call to the next page until the first tweet of one of the pages is earlier than the date you're trying to map from.\nAll you need to do then is iterate through the list while date >= 01/01/2011, and slice it at that po...
[ 1 ]
[]
[]
[ "python", "python_twitter", "twitter", "workflow" ]
stackoverflow_0006302408_python_python_twitter_twitter_workflow.txt
Q: adding string to a string I have a problem adding a string to another string. I am new to Python. The string cannot remember the previous values I added. Anyone who can help me? The following is the code snippet in Python. My problem is in the while loop of encrypt(). THANKS IN ADVANCE. class Cipher: def __in...
adding string to a string
I have a problem adding a string to another string. I am new to Python. The string cannot remember the previous values I added. Anyone who can help me? The following is the code snippet in Python. My problem is in the while loop of encrypt(). THANKS IN ADVANCE. class Cipher: def __init__(self): self.alpha...
[ "Python strings are immutable, so you should reassign the variable name to a new string. \nFunctions with \"__\" in them are not normally what you really want to use. Let the interpreter make that call for you by using the built in operators/functions (in this case the \"+\" operator).\nSo, instead of:\nself.finmi...
[ 3, 1, 0 ]
[]
[]
[ "add", "python", "string" ]
stackoverflow_0006302580_add_python_string.txt
Q: Best pythonic way to populate the list containing the date type data? I have the following list data. data = [['2009-01-20', 3000.0], ['2011-03-01', 6000.0], ['2008-12-15', 6000.0], ['2002-02-15', 6000.0], ['2009-04-20', 6000.0], ['2010-08-01', 4170.0], ['2002-07-15', 6000.0], ['2008-08-15', 6000.0], ['2010-12-01'...
Best pythonic way to populate the list containing the date type data?
I have the following list data. data = [['2009-01-20', 3000.0], ['2011-03-01', 6000.0], ['2008-12-15', 6000.0], ['2002-02-15', 6000.0], ['2009-04-20', 6000.0], ['2010-08-01', 4170.0], ['2002-07-15', 6000.0], ['2008-08-15', 6000.0], ['2010-12-01', 6000.0], ['2011-02-01', 8107.0], ['2011-04-01', 8400.0], ['2011-05-15', 9...
[ "from collections import defaultdict\n\nyeartotal = defaultdict(float)\nmonthtotal = defaultdict(float)\nfor s in data:\n d = s[0].split('-')\n yeartotal[d[0]] += s[1]\n monthtotal[d[1]] += s[1]\n\n\nIn [37]: [item for item in yeartotal.iteritems()]\nOut[37]: \n[('2002', 12000.0),\n ('2005', 6000.0),\n ('2...
[ 11, 3, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006302447_list_python.txt
Q: Python boolean expression always true (when it shouldn't be) I have a method that is intended to grab all img elements from some html and to add a css style to ensure the image is resized if it is large. It works great until the final test : largest_size < img_size - I have tried all manner of different ways to ex...
Python boolean expression always true (when it shouldn't be)
I have a method that is intended to grab all img elements from some html and to add a css style to ensure the image is resized if it is large. It works great until the final test : largest_size < img_size - I have tried all manner of different ways to express this simple thing, and yet it always evaluates to true - whi...
[ "int is always less than str. Turn your header value into an int first. And remember, debug with repr(), not str().\n", "img_size is a string not an int:\n>>> 30720 < '0'\nTrue\n\n" ]
[ 4, 0 ]
[]
[]
[ "comparison", "if_statement", "python" ]
stackoverflow_0006302880_comparison_if_statement_python.txt
Q: Django Login Form with "Remember Me" Option, What would be the best way? I am developing a django application and i would like some suggestions on what would be the best way to provide "Remember Me" option with the Login Form. I am really concerned about the performance of the application and am not sure if using ...
Django Login Form with "Remember Me" Option, What would be the best way?
I am developing a django application and i would like some suggestions on what would be the best way to provide "Remember Me" option with the Login Form. I am really concerned about the performance of the application and am not sure if using sessions would be a good choice. Please Suggest What you think.
[ "Have it provide a cookie with no expire date or a very large one. \n", "See this question: \ndjango-registration \"remember me\"\n" ]
[ 3, 0 ]
[]
[]
[ "authentication", "django", "python", "remember_me" ]
stackoverflow_0005642592_authentication_django_python_remember_me.txt
Q: Ball Physics problem Python I am trying to make a ball bounce within a box correctly, specifically handling corners at specific angles and handling a corner head on. I have a problem, because my ball keeps coming out of the box. I have this function that tells if my ball is out of the box and it handles corners an...
Ball Physics problem Python
I am trying to make a ball bounce within a box correctly, specifically handling corners at specific angles and handling a corner head on. I have a problem, because my ball keeps coming out of the box. I have this function that tells if my ball is out of the box and it handles corners and walls. The code is this: if...
[ "Rewrite this code. It is way too complex for the simple problem you're trying to solve. \nFirst, a 2D motion of a ball is just 2 1D problems. You can completely separate X and Y. For example, hitting a corner is completely equivalent of hitting a wall in X axis + hitting a wall in Y axis. Hitting a wall in X just ...
[ 7, 1 ]
[]
[]
[ "game_physics", "physics", "python" ]
stackoverflow_0006302835_game_physics_physics_python.txt
Q: help with winsys module i am trying to use the WinSys module to get the event logs of my system(windows). But i dont know why the following code doesnt run: from winsys import event_logs print len (event_logs.event_log ("Application")) or for logs in event_logs.event_logs(computer='.'): print logs these yie...
help with winsys module
i am trying to use the WinSys module to get the event logs of my system(windows). But i dont know why the following code doesnt run: from winsys import event_logs print len (event_logs.event_log ("Application")) or for logs in event_logs.event_logs(computer='.'): print logs these yield errors Traceback (most rec...
[ "As I can see from RegConnectRegistry documentation here:\n\ncomputerName : string\n The name of the remote computer, of the form \\\\computername. If None, the local\n computer is used.\n\nThus the default computer name value \".\" cannot be used in this function. It seems like there is bug in Winsys version you...
[ 0 ]
[]
[]
[ "event_log", "python", "windows" ]
stackoverflow_0006301498_event_log_python_windows.txt
Q: multiprocessing imap_unordered in python I am making a program that reads multiple files and writes a summary of each file to an ouput file. The size of the output file is rather big, so keeping it in memory is not a good idea. I am trying to develop a multiprocessing way of doing it. So far, the simplest way I wa...
multiprocessing imap_unordered in python
I am making a program that reads multiple files and writes a summary of each file to an ouput file. The size of the output file is rather big, so keeping it in memory is not a good idea. I am trying to develop a multiprocessing way of doing it. So far, the simplest way I was able to come with is: pool = Pool(processes=...
[ "processes=4 means that multiprocessing will start a pool with four worker processes and send the work items to them. Ideally, if you system supports it, i.e. either you have four cores, or the workers are not totally CPU-bound, 4 work items will be processed in parallel. \nI don't know the implementation of multip...
[ 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0006302284_multiprocessing_python.txt
Q: Django throws an ImportError on Mac OS X I'm trying to get a work project that I git-cloned from work (used in numerous other places, I know the project works fine) to run on my MacBook. I installed Django (via sudo python setup.py install), as well as MySQL, the Python MySQL wrapper, and also virtualenv with virt...
Django throws an ImportError on Mac OS X
I'm trying to get a work project that I git-cloned from work (used in numerous other places, I know the project works fine) to run on my MacBook. I installed Django (via sudo python setup.py install), as well as MySQL, the Python MySQL wrapper, and also virtualenv with virtualenvwrapper. After creating a virtualenv for...
[ "First try to import this library from python or ./manage.py shell.\nIf that fails import sys and check if your lib is in sys path print sys.path\n" ]
[ 0 ]
[]
[]
[ "django", "macos", "python", "virtualenv", "virtualenvwrapper" ]
stackoverflow_0006300783_django_macos_python_virtualenv_virtualenvwrapper.txt
Q: Use of the Python Language I have been studying Python at work for a week now and it seems very interesting, I started using it in order to create Extra Search functions for Splunk. My Question is, what else can you do with it?, is it only a Script Language?, if so what type of scripts can I create and use? To wha...
Use of the Python Language
I have been studying Python at work for a week now and it seems very interesting, I started using it in order to create Extra Search functions for Splunk. My Question is, what else can you do with it?, is it only a Script Language?, if so what type of scripts can I create and use? To what extent should I learn Python i...
[ "You can pretty much do anything with Python that you can do with ksh, only easier (shells have a lot of stuff built in but many scripts will \"reach out\" to helpers like grep, sed awk, and so forth, to do grunt work).\nPython also comes with an insanely large library (just like Java and C#) and plenty of add-on m...
[ 6, 5, 4, 2 ]
[]
[]
[ "programming_languages", "python", "scripting", "shell", "splunk" ]
stackoverflow_0006302691_programming_languages_python_scripting_shell_splunk.txt