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 stop repetition in my code? This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive. The code is: numP = 1 x = 3 y = int(input('Enter number of primes to be found: ')) while numP<=y: for n in range(2, x): ...
How to stop repetition in my code?
This code executes primes upto a given number. It works correctly as far as the prime generation is concerned but the output is painfully repetitive. The code is: numP = 1 x = 3 y = int(input('Enter number of primes to be found: ')) while numP<=y: for n in range(2, x): for b in range(2, n): if ...
[ "If you store the data in a set, you will avoid repetitions\n", "There's no reason to loop n from 2..x. Get rid of that loop, and replace all references to 'n' with 'x'. I.e.:\ndef find_primes(y):\n x = 3\n numP = 0\n while True:\n for b in range(2, x):\n if x % b == 0:\n ...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007571509_python_python_3.x.txt
Q: Django Template Arithmetic In my template, I am looping through a list, trying to make a two-column layout. Because of the desired two-column layout, the markup I need to write in the for loop is dependent on whether forloop.counter0 is even or odd. If I had the full power of Python in the template language, de...
Django Template Arithmetic
In my template, I am looping through a list, trying to make a two-column layout. Because of the desired two-column layout, the markup I need to write in the for loop is dependent on whether forloop.counter0 is even or odd. If I had the full power of Python in the template language, determining the parity of forloop....
[ "You should probably use cycle here instead. As for your question, there is a filter called divisibleby.\nThe philosophy behind Django's template system is to avoid doing any serious logic in the template. Thus they only provide tools to do fairly basic calculations for cases like drawing grids etc.\n", "You can ...
[ 7, 2, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007571534_django_django_templates_python.txt
Q: "undefined symbol: _PyObject_NextNotImplemented" error when loading psycopg2 module environment: Ubuntu 10.04 LTS build Python 2.7.2 with ./configure --with-zlib --enable-unicode=ucs4 postgresql-9.0 wsgi Django 1.3 virtualenv apache I am trying to build Ubuntu Django App Server. The installation completed with no...
"undefined symbol: _PyObject_NextNotImplemented" error when loading psycopg2 module
environment: Ubuntu 10.04 LTS build Python 2.7.2 with ./configure --with-zlib --enable-unicode=ucs4 postgresql-9.0 wsgi Django 1.3 virtualenv apache I am trying to build Ubuntu Django App Server. The installation completed with no error message. The exact installation method was successful with Ubuntu 11.04. However,...
[ "You mention 'wsgi' as a tag. If that means you are using Apache/mod_wsgi then be aware that mod_wsgi must be compiled against the same Python version/installation and you need to verify that mod_wsgi is picking up the same libpython.so at run time as it is mod_wsgi that dictates the Python library linked in.\n", ...
[ 4, 2, 1 ]
[]
[]
[ "django", "psycopg2", "python", "wsgi" ]
stackoverflow_0007561221_django_psycopg2_python_wsgi.txt
Q: Building Sphinx Autodoc on a Google App Engine project I have a Google App Engine project that I am trying to document with Sphinx. I am trying to use the autodoc feature for many of my modules/classes/functions. My Sphinx reST markup: .. automodule:: urls :members: Urls When I run make html, I get the error:...
Building Sphinx Autodoc on a Google App Engine project
I have a Google App Engine project that I am trying to document with Sphinx. I am trying to use the autodoc feature for many of my modules/classes/functions. My Sphinx reST markup: .. automodule:: urls :members: Urls When I run make html, I get the error: WARNING: autodoc can't import/find module 'urls', it repor...
[ "You can download the AppEngine SDK and then set your PYTHONPATH before calling make html.\nFor example, I downloaded the SDK and can do this:\n$ ls /home/jterrace/Downloads/google_appengine/google/\nappengine __init__.py net pyglib storage\n$ PYTHONPATH=\"/home/jterrace/Downloads/google_appengine/google\" pyth...
[ 3 ]
[]
[]
[ "autodoc", "google_app_engine", "python", "python_sphinx" ]
stackoverflow_0007571116_autodoc_google_app_engine_python_python_sphinx.txt
Q: Cygwin and Windows path conflict; using both Windows and cygwin Python I've installed cygwin on Windows XP. Mercurial on cygwin stopped working after I installed some software on Windows. The symptom can be simplified to python not being able to locate modules in its library: >>> import os Traceback (most recent c...
Cygwin and Windows path conflict; using both Windows and cygwin Python
I've installed cygwin on Windows XP. Mercurial on cygwin stopped working after I installed some software on Windows. The symptom can be simplified to python not being able to locate modules in its library: >>> import os Traceback (most recent call last): file "<stdin>", line 1, in <module> ImportError: No module name...
[ "Unfortunately my colleague who also had the problem already uninstalled the csvn thing, so I can't check. But reading the doc suggests the culpable variable might be $PYTHONHOME. Check whether it's set and try unsetting it!\n", "Have you tried the solutions found in this other SO post? Seems like a similar probl...
[ 6, 0 ]
[]
[]
[ "cygwin", "mercurial", "python", "svn" ]
stackoverflow_0006600758_cygwin_mercurial_python_svn.txt
Q: Calling Python script that creates a subprocess over ssh hangs I have a bunch of scripts that are used to start similar processes across a number of servers. I'd like to condense them down to one Python script called 'START', but something weird is happening when it's run over ssh. $ ./START APP_A works as expect...
Calling Python script that creates a subprocess over ssh hangs
I have a bunch of scripts that are used to start similar processes across a number of servers. I'd like to condense them down to one Python script called 'START', but something weird is happening when it's run over ssh. $ ./START APP_A works as expected: APP_A is launched and begins doing its thing. Control is return...
[ "Don't use shlex to call in conjunction with subprocess. It doesn't do what you expect. Instead, give subprocess a Python list of the command, like\nsubprocess.Popen(['/some/program', 'arg1', 'arg2', 'arg3'])\n\n", "When you do:\nssh some_host remote_command remote_cmd_param\n\nthen it is normal that ssh does not...
[ 0, 0, 0 ]
[]
[]
[ "python", "ssh", "subprocess" ]
stackoverflow_0007571796_python_ssh_subprocess.txt
Q: Multi threading for my MFC C++ .dll Currently I am accessing my MFC C++ dll using my python script and everything works well so far. My next step is to continuously access my .dll and carry on various operations with it simultaneously from which I feel "Multi-threading" is a very good option. Could you guys sugges...
Multi threading for my MFC C++ .dll
Currently I am accessing my MFC C++ dll using my python script and everything works well so far. My next step is to continuously access my .dll and carry on various operations with it simultaneously from which I feel "Multi-threading" is a very good option. Could you guys suggest me any good links to learn on multi-thr...
[ "On which side of things are you interested in multi-threading, Python or MFC? If Python, consider multi-process, because of the Python GIL issue.\nhttp://www.dabeaz.com/python/UnderstandingGIL.pdf\nhttp://wiki.python.org/moin/GlobalInterpreterLock\nIf windows, I can help you a little bit from memory. If you tell m...
[ 2, 1 ]
[]
[]
[ "dll", "mfc", "multithreading", "python" ]
stackoverflow_0007446562_dll_mfc_multithreading_python.txt
Q: Procedure execute inside SQL Developer, but not inside a script I had a procedure that was not working. If I tried to run: "BEGIN proc_name; END;" in SQL Developer or via script I had the same error. I've fixed the procedure and now when I run that same command in SQL Developer, it's fine, but the script returns a...
Procedure execute inside SQL Developer, but not inside a script
I had a procedure that was not working. If I tried to run: "BEGIN proc_name; END;" in SQL Developer or via script I had the same error. I've fixed the procedure and now when I run that same command in SQL Developer, it's fine, but the script returns an error. When I try: ... sql = """EXEC proc_name""" con = connection....
[ "Try using the callproc() or callfunc() method on the cursor, instead of execute(). They are not exactly Py DB API compatible, but should do the job for cx_Oracle...\n" ]
[ 0 ]
[]
[]
[ "oracle", "oracle10g", "python", "stored_procedures" ]
stackoverflow_0007571130_oracle_oracle10g_python_stored_procedures.txt
Q: RuntimeWarning: in python 2.6 while importing python-pycrypto-2.3-1.el3.pp I have installed "python-pycrypto-2.3-1.el3.pp" and "python-paramiko-1.7.6-1.el3.rf" in red hat linux and using python2.6 version. And when I import paramiko, I get below RuntimeWarning mismatch: /usr/local/lib/python2.6/site-packages/Crypt...
RuntimeWarning: in python 2.6 while importing python-pycrypto-2.3-1.el3.pp
I have installed "python-pycrypto-2.3-1.el3.pp" and "python-paramiko-1.7.6-1.el3.rf" in red hat linux and using python2.6 version. And when I import paramiko, I get below RuntimeWarning mismatch: /usr/local/lib/python2.6/site-packages/Crypto/Random/Fortuna/SHAd256.py:38: RuntimeWarning: Python C API version mismatch f...
[ "The EL3 packages are for EL3 Python. Since you've installed Python from source yourself, perform a source installation of those modules.\n" ]
[ 1 ]
[]
[]
[ "paramiko", "pycrypto", "python", "ssh" ]
stackoverflow_0007572178_paramiko_pycrypto_python_ssh.txt
Q: Is there a way to create Eclipse plugins with Python? As far as I understand Eclipse doesn't provide user with python bindings by default. Nor any projects of such kind was I able to find with google. Are there any third-party plugins for that? Any tutorial? May be with Jython?.. A: As far as I know, you need to...
Is there a way to create Eclipse plugins with Python?
As far as I understand Eclipse doesn't provide user with python bindings by default. Nor any projects of such kind was I able to find with google. Are there any third-party plugins for that? Any tutorial? May be with Jython?..
[ "As far as I know, you need to use Java. Eclipse is written in Java, and even the vanilla application is made up of several Java components glued together by the core plugin loader. Jython might work if:\n\nyou can cross-compile Python to Java bytecode (indeed you can, thanks to sayth for pointing that out), and\...
[ 7 ]
[]
[]
[ "eclipse", "eclipse_plugin", "jython", "python" ]
stackoverflow_0007571235_eclipse_eclipse_plugin_jython_python.txt
Q: Learning wxPython, basic thing I want to display a button that when I click adds to the main panel a static text that automatic adds to the BoxSizer of the panel. I have this code but dosen't work good. Anyone can help me? I am desperate. Thanks import wx class MyApp(wx.App): def OnInit(self): self.fr...
Learning wxPython, basic thing
I want to display a button that when I click adds to the main panel a static text that automatic adds to the BoxSizer of the panel. I have this code but dosen't work good. Anyone can help me? I am desperate. Thanks import wx class MyApp(wx.App): def OnInit(self): self.frame = MainFrame(None,title='') ...
[ "If your problem is that your text initially shows up behind the button when it is clicked, you can force the sizer to update by adding a call to your Panel's Layout method.\nclass MainPanel(wx.Panel):\n def __init__(self, parent):\n super(MainPanel, self).__init__(parent)\n\n #Atributos\n b...
[ 4 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007572243_python_wxpython.txt
Q: Behaviour of generator in lambda safe against future changes? I have the following function: | def line_reader_iter(file_object): | while True: | a_line = file_object.readline() | if len(a_line)==0: raise StopIteration | yield a_line[:-1] and somewhere I say: | line_reade...
Behaviour of generator in lambda safe against future changes?
I have the following function: | def line_reader_iter(file_object): | while True: | a_line = file_object.readline() | if len(a_line)==0: raise StopIteration | yield a_line[:-1] and somewhere I say: | line_reader = lambda: next(line_reader_iter(infile)) Clearly, the lambda onl...
[ "I think you are actually misunderstanding why this works. Each time you call line_reader() a new line_reader_iter generator is created. It appears to work because you use the same infile each time, and each call to readline() will return the next line of the file.\nConsider the following simpler example:\n>>> co...
[ 7 ]
[]
[]
[ "generator", "lambda", "python", "readline", "yield" ]
stackoverflow_0007572626_generator_lambda_python_readline_yield.txt
Q: Nginx configuration for static sites in root directory, Flask apps in subdirectories I'd like to have a static site in my root public_html directory, then Flask apps in their own subdirectories (e.g. public_html/foo). The static root directory functions as expected. I have spent hours editing the nginx configurati...
Nginx configuration for static sites in root directory, Flask apps in subdirectories
I'd like to have a static site in my root public_html directory, then Flask apps in their own subdirectories (e.g. public_html/foo). The static root directory functions as expected. I have spent hours editing the nginx configuration to get the Flask apps working, but always end up back in the same place, namely that th...
[ "Got an answer from mitsuhiko (Flask lead dev):\nhttp://flask.pocoo.org/snippets/35/\nYou need to define a ReverseProxied class in your Flask app and add several proxy-set-header lines to the location /foo block in the nginx config.\n" ]
[ 12 ]
[]
[]
[ "flask", "gunicorn", "nginx", "python" ]
stackoverflow_0007558249_flask_gunicorn_nginx_python.txt
Q: Python datetime randomly breaking This isn't the first time this has happened to me so now I'm looking for an answer because I'm completely stumped. I have code running in a production environment for over 3 months now and it worked absolutely fine, then out of no where I started to get errors in python. 'method_d...
Python datetime randomly breaking
This isn't the first time this has happened to me so now I'm looking for an answer because I'm completely stumped. I have code running in a production environment for over 3 months now and it worked absolutely fine, then out of no where I started to get errors in python. 'method_descriptor' object has no attribute 'tod...
[ "Your code is importing datetime.datetime somewhere, instead of just datetime, e.g. from datetime import datetime.\n>>> import datetime\n>>> datetime.datetime.date.today()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'method_descriptor' object has no attribute 'today...
[ 7, 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007572690_datetime_python.txt
Q: django templating system inheritance issue i am having issues with my django templating system, i have a base.html file, which contains the content which will be common on all the web pages of the web site, the base.html file fetches some dynamic content, like the categories and the archives, which are passed to i...
django templating system inheritance issue
i am having issues with my django templating system, i have a base.html file, which contains the content which will be common on all the web pages of the web site, the base.html file fetches some dynamic content, like the categories and the archives, which are passed to it by a python file, which fetches the categories...
[ "Most likely you have one (or both) of these issues:\n\nThe block in base.html is being overridden with a block in the index.html, and you haven't used {{block.super}} to include the content from the base template.\nThe view function that invokes index.html isn't creating the proper context variables to give the te...
[ 2, 0 ]
[]
[]
[ "django", "inheritance", "python", "templates" ]
stackoverflow_0002658650_django_inheritance_python_templates.txt
Q: Python/html- Combine multiple html's into one I've written a python script to convert a text file to html file. But that is kind of useless if I can't put them all together. What I'm supposed to do is display all the reports onto the website (the server part is not my problem). Now I can convert each file to an ht...
Python/html- Combine multiple html's into one
I've written a python script to convert a text file to html file. But that is kind of useless if I can't put them all together. What I'm supposed to do is display all the reports onto the website (the server part is not my problem). Now I can convert each file to an html but I just realize it's a huge library of files....
[ "Create a list of tuples in Python. Then sort them in place. Then iterate over the list and produce your homepage HTML. Below an example. You need to fill in the URLs and the date for each report (either as a date object or as a string, example: '09-12-2011')\nreport_tuples = [\n ('http://www.myreport.com/report...
[ 6 ]
[]
[]
[ "html", "python" ]
stackoverflow_0007572901_html_python.txt
Q: How to stop multiprocess python-program cleanly after exception? I have a Python program that has several processes (for now only 2) and threads (2 per process). I would like to catch every exception and especially shut down my program cleanly on Ctrl+c but I can't get it to work. Everytime an Exception occurs the...
How to stop multiprocess python-program cleanly after exception?
I have a Python program that has several processes (for now only 2) and threads (2 per process). I would like to catch every exception and especially shut down my program cleanly on Ctrl+c but I can't get it to work. Everytime an Exception occurs the program stops but does not shut down correctly, leaving me with an un...
[ "The problem (I expect) is that the exceptions are raised inside the processes not in the join calls.\nI suggest you try wrapping each process's main method in try-except loop. Then have a flag (e.g. an instance of multiprocessing.Value) that the except statement sets to False. Each process could check the value of...
[ 1 ]
[]
[]
[ "exception_handling", "multiprocessing", "python" ]
stackoverflow_0007560230_exception_handling_multiprocessing_python.txt
Q: Oracle SQL loader Error while loading really huge log files I have a python script which loops through log files in a directory and uses oracle sqlloader to load the log files to the oracle database. the script works properly and even the sqlloader.. But after loading around some 200k records,the loading fails wi...
Oracle SQL loader Error while loading really huge log files
I have a python script which loops through log files in a directory and uses oracle sqlloader to load the log files to the oracle database. the script works properly and even the sqlloader.. But after loading around some 200k records,the loading fails with this exception.. Record 11457: Rejected - Error on table USAGE...
[ "Post your controlfile contents. What version of Oracle are you using?\nThe ORA-42338 error is the one I would focus on. Are you doing any sort of data transformation in your job? Calling functions or similar?\n" ]
[ 0 ]
[]
[]
[ "ora_03114", "oracle", "oracle10g", "python", "sql_loader" ]
stackoverflow_0007570574_ora_03114_oracle_oracle10g_python_sql_loader.txt
Q: Delete item from list in Python while iterating over it I'm writing a round robin algorithm for a tournament app. When the number of players is odd, I add 'DELETE' to the list of players, but later, when I want to delete all items from schedule list that contain 'DELETE', I can't -- one is always left. Please tak...
Delete item from list in Python while iterating over it
I'm writing a round robin algorithm for a tournament app. When the number of players is odd, I add 'DELETE' to the list of players, but later, when I want to delete all items from schedule list that contain 'DELETE', I can't -- one is always left. Please take a look at the code -- the problem is simple and I suppose i...
[ "schedule[:] = [x for x in schedule if 'DELETE' not in x]\n\nSee the other questions about deleting from a list while iterating over it.\n", "To remove elements from a list while iterating over it, you need to go backwards:\nif delLater == True:\n for x in schedule[-1::-1]):\n if 'DELETE' in x:\n ...
[ 7, 4, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007573115_list_python.txt
Q: Convert Unicode Object to Python Dict A request object that I'm dealing with has the following value for the key "address": u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}" I need to operate on this unicode object as a dictionary. Unfortunately, json.loads() fails because it is n...
Convert Unicode Object to Python Dict
A request object that I'm dealing with has the following value for the key "address": u"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}" I need to operate on this unicode object as a dictionary. Unfortunately, json.loads() fails because it is not a json compatible object. Is there any ...
[ ">>> ast.literal_eval(u\"{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}\")\n{u'city': u'new-york', u'name': u'Home', u'display_value': u'2 Main Street'}\n\n" ]
[ 15 ]
[]
[]
[ "json", "python", "serialization" ]
stackoverflow_0007573822_json_python_serialization.txt
Q: Is it possible to find average color of an image from its histogram? I took the average of each color by this method and wrote the average of red, green and blue to database. Here are the images sorted by "-blue". As you can see the 5th image has the most blue. Am I doing something wrong, or is it not possible to...
Is it possible to find average color of an image from its histogram?
I took the average of each color by this method and wrote the average of red, green and blue to database. Here are the images sorted by "-blue". As you can see the 5th image has the most blue. Am I doing something wrong, or is it not possible to get average color from the histogram? This is the handler where I create ...
[ "Actually, the fifth image doesn't have the most blue. Note that white is (255, 255, 255) as rgb, so an image that is completely white has just as much blue as an image that is completely blue. A darker blue has a smaller blue component than white.\n" ]
[ 5 ]
[]
[]
[ "colors", "histogram", "image", "python" ]
stackoverflow_0007574078_colors_histogram_image_python.txt
Q: Python: Using CVXOPT for quadratic programming I'm using CVXOPT to do quadratic programming to compute the optimal weights of a potfolio using mean-variance optimization. There is a great example at http://abel.ee.ucla.edu/cvxopt/userguide/coneprog.html#quadratic-programming. However, the arguments are in a regula...
Python: Using CVXOPT for quadratic programming
I'm using CVXOPT to do quadratic programming to compute the optimal weights of a potfolio using mean-variance optimization. There is a great example at http://abel.ee.ucla.edu/cvxopt/userguide/coneprog.html#quadratic-programming. However, the arguments are in a regularized form (according to the author). The example is...
[ "I read the docs and I think you have to use the function with the following parameters. I assume that x has size n:\nP = S\nq = (0,....0)\n\nA = (1, ...... 1)\nb = (0)\n\nG is vertically stacked from\n -a\n +I_n\n -I_n\n\nwhere I_n is the identity matrix of size n x n . And the corresponding right hand side h is\n...
[ 1 ]
[]
[]
[ "optimization", "python", "quadratic" ]
stackoverflow_0007572698_optimization_python_quadratic.txt
Q: Filenames and paths trouble The following example "walks" through a directory, prints the names of all the files, and calls itself recursively on all the directories. import os def walk(dir): for name in os.listdir(dir): path = os.path.join(dir,name) if os.path.isfile(path): print ...
Filenames and paths trouble
The following example "walks" through a directory, prints the names of all the files, and calls itself recursively on all the directories. import os def walk(dir): for name in os.listdir(dir): path = os.path.join(dir,name) if os.path.isfile(path): print path else: wa...
[ "You need to add the result of your recursion to what you already have.\n", "Here's an annotated version with a small fix to the recursion.\ndef walk1(dir):\n res = []\n # for all entries in the folder,\n for name in os.listdir(dir):\n # compute the path relative to `dir`\n path = os.path.j...
[ 1, 1, 1 ]
[]
[]
[ "filenames", "path", "python" ]
stackoverflow_0007563205_filenames_path_python.txt
Q: how to use logging inside Gevent? I have a code like: log = logging.getLogger(__file__) def func(): print "1" log.debug("Printed") g = gevent.spawn(func) g.join() but when I ran it my log doesn't show in shell. Any ideas? Is there a better way to do logging inside gevent based coroutines? A: It is unr...
how to use logging inside Gevent?
I have a code like: log = logging.getLogger(__file__) def func(): print "1" log.debug("Printed") g = gevent.spawn(func) g.join() but when I ran it my log doesn't show in shell. Any ideas? Is there a better way to do logging inside gevent based coroutines?
[ "It is unrelated to gevent. You should configure logging e.g.,\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s %(msg)s\")\n\n" ]
[ 7 ]
[]
[]
[ "gevent", "python" ]
stackoverflow_0007574813_gevent_python.txt
Q: SELECT DISTINCT, ORDER BY created by Django works in MySQL and SQLite, not PostgreSQL I just switched from mysql to postgres (yay!) but now on my postgres server (only) I'm getting an error that: SELECT DISTINCT, ORDER BY expressions must appear in select list It's the same query: SELECT DISTINCT * FROM table ORDE...
SELECT DISTINCT, ORDER BY created by Django works in MySQL and SQLite, not PostgreSQL
I just switched from mysql to postgres (yay!) but now on my postgres server (only) I'm getting an error that: SELECT DISTINCT, ORDER BY expressions must appear in select list It's the same query: SELECT DISTINCT * FROM table ORDER BY '?' BTW this is a query auto-generated by django. Alternatively, any way to get djan...
[ "I'd expect all SQL platforms that comply with SQL standards to raise a similar error.\nThink about it this way.\nCREATE TABLE test (\n id INTEGER NOT NULL,\n c CHAR(1) NOT NULL,\n PRIMARY KEY (id, c)\n);\n\nINSERT INTO test VALUES \n (1, 'a'),\n (1, 'z'),\n (2, 'b');\n\nSELECT * FROM test ORDER B...
[ 2, 0 ]
[]
[]
[ "django", "migration", "postgresql", "python" ]
stackoverflow_0004823888_django_migration_postgresql_python.txt
Q: Writing Escape Characters to a Csv File in Python I'm using the csv module in python and escape characters keep messing up my csv's. For example, if I had the following: import csv rowWriter = csv.writer(open('bike.csv', 'w'), delimiter = ",") text1 = "I like to \n ride my bike" text2 = "pumpkin sauce" rowWrite...
Writing Escape Characters to a Csv File in Python
I'm using the csv module in python and escape characters keep messing up my csv's. For example, if I had the following: import csv rowWriter = csv.writer(open('bike.csv', 'w'), delimiter = ",") text1 = "I like to \n ride my bike" text2 = "pumpkin sauce" rowWriter.writerow([text1, text2]) rowWriter.writerow(['chicken...
[ "The problem is not with writing them to the file. The problem is that \\n is a line break when inside '' or \"\". What you really want is either 'I like to \\\\n ride my bike' or r'I like to \\n ride my bike' (notice the r prefix).\n", "Firstly, it is not obvious why you want r\"\\n\" (two bytes) to appear in yo...
[ 3, 0 ]
[]
[]
[ "csv", "escaping", "file", "python" ]
stackoverflow_0007571642_csv_escaping_file_python.txt
Q: how to make python script self-executable Possible Duplicate: Calling a python script from command line without typing “python” first I've tried bash$ chmod +x script.py doesn't work. I also remember to put #!usr/bin/env python at the beginning of the script. bash$ ./script.py Does nothing, it just...
how to make python script self-executable
Possible Duplicate: Calling a python script from command line without typing “python” first I've tried bash$ chmod +x script.py doesn't work. I also remember to put #!usr/bin/env python at the beginning of the script. bash$ ./script.py Does nothing, it just changes my cursor to a cross lol UPDATE: I'v...
[ "Here is the list of things to try, in rough order of likelihood:\n\nEnsure that the shebang line has correct syntax (you've done this already, #!/usr/bin/python).\nMake sure the shebang is the first line in the file (not even a blank line or a comment above it).\nVerify that /usr/bin/python actually exists and wor...
[ 18, 11 ]
[]
[]
[ "python" ]
stackoverflow_0007562716_python.txt
Q: Comparing strings in python to find errors I have a string that is the correct spelling of a word: FOO I would allow someine to mistype the word in such ways: FO, F00, F0O ,FO0 Is there a nice way to check for this ? Lower case should also be seen as correct, or convert to upper case. What ever would be the pret...
Comparing strings in python to find errors
I have a string that is the correct spelling of a word: FOO I would allow someine to mistype the word in such ways: FO, F00, F0O ,FO0 Is there a nice way to check for this ? Lower case should also be seen as correct, or convert to upper case. What ever would be the prettiest.
[ "One approach is to calculate the edit distance between the strings. You can for example use the Levenshtein distance, or invent your own distance function that considers 0 and O more close than 0 and P, for example.\nAnother is to transform each word into a canonical form, and compare canonical forms. You can for ...
[ 6, 2, 1 ]
[]
[]
[ "python", "string_comparison" ]
stackoverflow_0007573952_python_string_comparison.txt
Q: write formatted file I want to to write np.double to formatted file: import numpy as np a='12 45 87 34 65'; s=np.double(a.split()) fid=open('qqq.txt','wt') fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4])) fid.close() Can this "write" row be written in a shorter way? fid.write('%5.1f %5.1f %...
write formatted file
I want to to write np.double to formatted file: import numpy as np a='12 45 87 34 65'; s=np.double(a.split()) fid=open('qqq.txt','wt') fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4])) fid.close() Can this "write" row be written in a shorter way? fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],...
[ "One way is this\nIn [48]: ''.join('%5.1f ' % n for n in s)\nOut[48]: ' 12.0 45.0 87.0 34.0 65.0 '\n\nAnother way is\nIn [49]: ('%5.1f ' * len(s)) % tuple(s)\nOut[49]: ' 12.0 45.0 87.0 34.0 65.0 '\n\n", "fid.write(''.join(map('{:5.1f} '.format, s)))\n\n", "This is the fastest way:\nfid.write(''.join(map...
[ 6, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007575736_python.txt
Q: Finding the regex for ///? This was posted to me <*@google.com> wrote: Hi Niklas, If you just want to map this: /region/city/category/ supposing its only this valid characters: [a-zA-Z0-9_] you can do the following: - main.py application = webapp.WSGIApplication([('/([-\w]+)/([-\w]+)/([-\...
Finding the regex for ///?
This was posted to me <*@google.com> wrote: Hi Niklas, If you just want to map this: /region/city/category/ supposing its only this valid characters: [a-zA-Z0-9_] you can do the following: - main.py application = webapp.WSGIApplication([('/([-\w]+)/([-\w]+)/([-\w]+)', handler)],debug=True)...
[ "After you have given more details, I can now propose another regex pattern:\nimport re\n\nreg = re.compile('(?:/[^/]+(?=/[^/]+/[^/]+/?\\Z)' # this partial RE matches the\n # first of 3 groups, if 3\n '|' # OR\n ')' # nothing is ca...
[ 2, 1, 1, 1 ]
[]
[]
[ "google_app_engine", "python", "regex", "yaml" ]
stackoverflow_0007538803_google_app_engine_python_regex_yaml.txt
Q: Change python source while running Is it possible to change python source file while running an application and have this changes reflected immediately in the application? Let say I have a foo.py file with a class Foo. In other module I'm calling functions on the Foo on user action. Now, I would like to change sou...
Change python source while running
Is it possible to change python source file while running an application and have this changes reflected immediately in the application? Let say I have a foo.py file with a class Foo. In other module I'm calling functions on the Foo on user action. Now, I would like to change source of the Foo without restarting the ap...
[ "Yes, but it ill advised — code which changes itself (although necessary in some cases) is notoriously hard to debug. You're looking for the reload method. The way that you would get it to work would be to modify the source file and then call reload on the module, then repeat.\nYou do have the option of re-assignin...
[ 12, 9 ]
[]
[]
[ "python" ]
stackoverflow_0007573599_python.txt
Q: Python simplejson.dumps still returns string Input : {"id": null, "type": null, "order_for": null, "name": "Name"} code : input_map = simplejson.dumps(eval(line)) print type(input_map) returns <type 'str'> what is wrong in here? Thank you A: Perhaps you meant: print(input_map) Also, if you use nul...
Python simplejson.dumps still returns string
Input : {"id": null, "type": null, "order_for": null, "name": "Name"} code : input_map = simplejson.dumps(eval(line)) print type(input_map) returns <type 'str'> what is wrong in here? Thank you
[ "Perhaps you meant:\nprint(input_map) \n\nAlso, if you use null in line, eval should have raised a NameError.\nYou could use simplejson.loads instead:\nimport simplejson\nline='{\"id\": null, \"type\": null, \"order_for\": null, \"name\": \"Name\"}'\ninput_map = simplejson.loads(line) \nprint(input_map) \n# {u'o...
[ 4 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0007576143_python_simplejson.txt
Q: Efficient Way to Create Numpy Arrays from Binary Files I have very large datasets that are stored in binary files on the hard disk. Here is an example of the file structure: File Header 149 Byte ASCII Header Record Start 4 Byte Int - Record Timestamp Sample Start 2 Byte Int - Data Stream 1 Sample 2 Byte Int - Da...
Efficient Way to Create Numpy Arrays from Binary Files
I have very large datasets that are stored in binary files on the hard disk. Here is an example of the file structure: File Header 149 Byte ASCII Header Record Start 4 Byte Int - Record Timestamp Sample Start 2 Byte Int - Data Stream 1 Sample 2 Byte Int - Data Stream 2 Sample 2 Byte Int - Data Stream 3 Sample 2 Byte ...
[ "Some hints: \n\nDon't use the struct module. Instead, use Numpy's structured data types and fromfile. Check here: http://scipy-lectures.github.com/advanced/advanced_numpy/index.html#example-reading-wav-files\nYou can read all of the records at once, by passing in a suitable count= to fromfile.\n\nSomething like th...
[ 15, 2, 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007569563_numpy_python.txt
Q: Structure a python project with 2 different applications I am planning to write a visitors' kiosk in python/GTK. The project will have two applications, the frontend for the kiosk and the backend for management linked to a MySQL DB. I want both applications to have common code. I was thinking of structuring the p...
Structure a python project with 2 different applications
I am planning to write a visitors' kiosk in python/GTK. The project will have two applications, the frontend for the kiosk and the backend for management linked to a MySQL DB. I want both applications to have common code. I was thinking of structuring the project like so: project.common - for common code project.front...
[ "You can have multiple directories (i.e. common/project, frontend/project, and backend/project directories) in your PYTHONPATH with overlapping hierarchies (i.e. each has project top level package), but by default Python will not be happy with this, because it uses the first matching directory it finds and does no...
[ 2 ]
[]
[]
[ "linux", "pygtk", "python", "windows" ]
stackoverflow_0007576368_linux_pygtk_python_windows.txt
Q: Format an SQL query in Python without executing it Python has all sort of libraries to interface with databases, which provide a nice way to build SQL queries without worrying about SQL injections. For instance, with sqlite3: for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSO...
Format an SQL query in Python without executing it
Python has all sort of libraries to interface with databases, which provide a nice way to build SQL queries without worrying about SQL injections. For instance, with sqlite3: for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM...
[ "\nThere has to be a way to get the formatted queries without actually connecting to a database and running them\n\nNot really.\nThe RDBMS handles this internally with \"prepared queries\" and \"bind variables\". The \"formatted\" doesn't actually exist. Anywhere.\n" ]
[ 5 ]
[]
[]
[ "code_injection", "prepared_statement", "python", "sql", "sqlite" ]
stackoverflow_0007576451_code_injection_prepared_statement_python_sql_sqlite.txt
Q: How do I use Python's pprint module to pretty print out dictionary key value pairs nested with in a list? I would like to pretty print out each key value pair from dictionaries which are nested in a list. So here is what I am working with: [{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net...
How do I use Python's pprint module to pretty print out dictionary key value pairs nested with in a list?
I would like to pretty print out each key value pair from dictionaries which are nested in a list. So here is what I am working with: [{"updated_at":"2011/09/26 22:39:18 +0000","url":"http://diveintopython.net/http_web_services/redirects.html","annotations":[],"user":"name","shared":"yes","tags":"python,handler,opener,...
[ "One possibility comes to mind. Are you supplying a JSON string to pprint? If so, you should first decode it:\npprint(json.loads(data))\n\n", "It um... works right for me. (I cut and pasted your example!) What Python and OS are you using? And are you sure you didn't accidentally add some additional quotes somew...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "pprint", "pretty_print", "python" ]
stackoverflow_0007576513_dictionary_list_pprint_pretty_print_python.txt
Q: Zipping commands and directory (Windows) Troubles The problem is 'I want a program which creates a backup of all my important files'. This lesson is located at: http://www.ibiblio.org/g2swap/byteofpython/read/problem-solving.html import os import time # 1. The files and directories to be backed up are specifie...
Zipping commands and directory (Windows) Troubles
The problem is 'I want a program which creates a backup of all my important files'. This lesson is located at: http://www.ibiblio.org/g2swap/byteofpython/read/problem-solving.html import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swa...
[ "You can get a zip program from http://info-zip.org/Zip.html but I would recommend just using Python's zipfile module.\nAlso, there's no standard backup file location. You'll just have to make one up.\n" ]
[ 1 ]
[]
[]
[ "python", "zip", "ziparchive" ]
stackoverflow_0007576862_python_zip_ziparchive.txt
Q: Inline if statement escapes HTML characters So I'm playing with Mako on Pyramid and I'm trying to do inline if statements. <li>${'<a href="#">Opinions</a></li>' if whichnav == 'opinions' else 'Opinions'} Outputs: <li>&lt;a href=&#34;#&#34;&gt;Opinions&lt;/a&gt;&lt;/li&gt; Whereas: % if whichnav =='opinions': ...
Inline if statement escapes HTML characters
So I'm playing with Mako on Pyramid and I'm trying to do inline if statements. <li>${'<a href="#">Opinions</a></li>' if whichnav == 'opinions' else 'Opinions'} Outputs: <li>&lt;a href=&#34;#&#34;&gt;Opinions&lt;/a&gt;&lt;/li&gt; Whereas: % if whichnav =='opinions': <li><a href="#">Opinions</a></li> % else: ...
[ "Looks like your HTML is being escaped. What happens if you change your inline if to this:\n${'<a href=\"#\">Opinions</a></li>' if whichnav == 'opinions' else 'Opinions' | n}\n\n(Edit: Put the | n to disable the filtering AFTER the conditional).\n" ]
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0007577048_mako_python.txt
Q: Identifying a Specific Face in an Image Using OpenCV's HaarDetectObjects with haarcascade_frontalface_default.xml, I've found I can detect a face fairly reliably. However, is anyone aware of any libraries or methods for identifying a face (i.e. labeling it with a name)? A: Check out PyVision. It's part of a rese...
Identifying a Specific Face in an Image
Using OpenCV's HaarDetectObjects with haarcascade_frontalface_default.xml, I've found I can detect a face fairly reliably. However, is anyone aware of any libraries or methods for identifying a face (i.e. labeling it with a name)?
[ "Check out PyVision. It's part of a research project out of Colorado State University but it's fairly mature. I've had good success using it, though I've never used the face-labeling parts.\n" ]
[ 1 ]
[]
[]
[ "computer_vision", "image_processing", "opencv", "python" ]
stackoverflow_0007577025_computer_vision_image_processing_opencv_python.txt
Q: How to change the From address in Django Email? As noted in the docs, the SERVER_EMAIL setting is supposed to change the 'From' address in crash emails sent to ADMINS from the Django (1.3.1) server. But it's not. Does this work for you in 1.3.1? (Or any Django version) Django insists on just using my EMAIL_HOST_US...
How to change the From address in Django Email?
As noted in the docs, the SERVER_EMAIL setting is supposed to change the 'From' address in crash emails sent to ADMINS from the Django (1.3.1) server. But it's not. Does this work for you in 1.3.1? (Or any Django version) Django insists on just using my EMAIL_HOST_USER - my email login/actual address - as the from addr...
[ "The problem is Gmail. All the way down to the smtplib library, the correct 'from' address is specified, and this library sends the right address to Gmail.\nThis Gmail Support page implies (especially near the bottom under \"Note for POP/IMAP\" users) that you need to add an address as an 'additional email address...
[ 3, 1 ]
[]
[]
[ "django", "email", "gmail", "python" ]
stackoverflow_0007573798_django_email_gmail_python.txt
Q: Matplotlib: Using a colorbar in conjunction with the extent keyword produces off-center images in figure window I'm using matplotlib to do some plotting. I'd like to be able to use the extent keyword to control the aspect ratio of my plots as well as display the size of the image along the axis tick marks. My pro...
Matplotlib: Using a colorbar in conjunction with the extent keyword produces off-center images in figure window
I'm using matplotlib to do some plotting. I'd like to be able to use the extent keyword to control the aspect ratio of my plots as well as display the size of the image along the axis tick marks. My problem is that if I try to make an image that is longer in the row direction than it is in the column direction, and th...
[ "I don't know why this happen, but you can use cax argument of colorbar() to set the axe which contain the colorbar.\nimport numpy\nfrom matplotlib import pyplot\npyplot.imshow(numpy.random.random( (100,100) ), extent = [0,50, 100, 0] )\ncax = pyplot.axes([0.80, 0.1, 0.04, 0.8])\npyplot.colorbar(cax=cax)\npyplot.sh...
[ 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0007572988_matplotlib_numpy_python.txt
Q: Why are appengine database keys sorted differently than strings I found this interesting, and am curious to know why db keys are ordered differently than strings .. If you test the following example in the Python development environment (true for server as well), you will see the following (somewhat unexpected) b...
Why are appengine database keys sorted differently than strings
I found this interesting, and am curious to know why db keys are ordered differently than strings .. If you test the following example in the Python development environment (true for server as well), you will see the following (somewhat unexpected) behaviour str1 = 'agpyb21hbmNlYXBwchILEglVc2VyTW9kZWwY4-agBgw' str2 = ...
[ "They use a different collation in extraction operator. I guess the db.Key() has strong probabilities to bind to DB properties.\nSo the < operator 'sees' different data, the first being (say) Ut8 source based, the second some weird db collation based, where the dash has specific meaning (unknown until we can get th...
[ 2, 2 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0007572386_database_google_app_engine_python.txt
Q: Getting a Python Modules Dierctory from Inside Itself I have a Python module and I'd like to get that modules directory from inside itself. I want to do this because I have some files that I'd like to reference relative to the module. A: First you need to get a reference to the module inside itself. mod = sys._...
Getting a Python Modules Dierctory from Inside Itself
I have a Python module and I'd like to get that modules directory from inside itself. I want to do this because I have some files that I'd like to reference relative to the module.
[ "First you need to get a reference to the module inside itself.\nmod = sys.__modules__[__name__]\n\nThen you can use __file__ to get to the module file.\nmod.__file__\n\nIts directory is a dirname of that.\n", "As you are inside the module all you need is this:\nimport os\npath_to_this_module = os.path.dirname(__...
[ 3, 3, 2, 1 ]
[]
[]
[ "directory", "module", "path", "python" ]
stackoverflow_0007576968_directory_module_path_python.txt
Q: PySide Signal "duplicating" behavior from PySide.QtCore import * class Eggs(QObject): evt_spam = Signal() print "Loaded" a = Eggs() b = Eggs() print a.evt_spam print b.evt_spam print a.evt_spam is b.evt_spam outputs: Loaded <PySide.QtCore.Signal object at 0xa2ff1a0> <PySide.QtCore.Signal object at 0xa2f...
PySide Signal "duplicating" behavior
from PySide.QtCore import * class Eggs(QObject): evt_spam = Signal() print "Loaded" a = Eggs() b = Eggs() print a.evt_spam print b.evt_spam print a.evt_spam is b.evt_spam outputs: Loaded <PySide.QtCore.Signal object at 0xa2ff1a0> <PySide.QtCore.Signal object at 0xa2ff1b0> False "Loaded" only printing once (...
[ "It's not being printed when you create a class instance, but rather when the class scope is executed. This code will print \"Loaded\", even though I never made an instance of \"Test\".\nclass Test:\n print \"Loaded\"\n\nIf you want to run code when the class is initialized, take a look at __init__(). This code ...
[ 3 ]
[]
[]
[ "pyqt", "pyside", "python", "qt", "qt_signals" ]
stackoverflow_0007577290_pyqt_pyside_python_qt_qt_signals.txt
Q: How slice Numpy array by column value I have an array like this numpy array dd =[[0.567 2 0.611] [0.469 1 0.479] [0.220 2 0.269] [0.480 1 0.508] [0.324 1 0.324]] I need 2 seperate array dd[:,1] ==1 and dd[:,1] ==2 These array are what I am after: na =[[0.469 1 0.479] [0.480 1 0.508...
How slice Numpy array by column value
I have an array like this numpy array dd =[[0.567 2 0.611] [0.469 1 0.479] [0.220 2 0.269] [0.480 1 0.508] [0.324 1 0.324]] I need 2 seperate array dd[:,1] ==1 and dd[:,1] ==2 These array are what I am after: na =[[0.469 1 0.479] [0.480 1 0.508] [0.324 1 0.324]] na2 =[[0.567 2 0...
[ "You could use numpy fancy indexing: \n[~/repo/py]\n|32>dd[dd[:,1] == 1]\n[32] \narray([[ 0.469, 1. , 0.479],\n [ 0.48 , 1. , 0.508],\n [ 0.324, 1. , 0.324]])\n\n[~/repo/py]\n|33>dd[dd[:,1] == 2]\n[33] \narray([[ 0.567, 2. , 0.611],\n [ 0.22 , 2. , 0.269]])\n\nAlternatively you...
[ 7 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007577443_numpy_python.txt
Q: How do I hide all columns in a treelistitem? I'm using the HyperTreeList to display a list of items with the name in the first column, and a "Remove" button in the second column. I wrote a function to filter what is displayed in the tree by some text in a TextCtrl. To hide the TreeListItems, I'm doing this: treeli...
How do I hide all columns in a treelistitem?
I'm using the HyperTreeList to display a list of items with the name in the first column, and a "Remove" button in the second column. I wrote a function to filter what is displayed in the tree by some text in a TextCtrl. To hide the TreeListItems, I'm doing this: treelist.HideItem(branch, True) where treelist is a Hyp...
[ "According to the docs, this should work:\ntreelist.SetColumnShown(column_index, False)\n\nbut this will hide that column for everything. If I understand what you're saying, the row you are trying to hide doesn't actually disappear, just the value of the first column. In that case, you might have to refresh the wid...
[ 0 ]
[]
[]
[ "python", "treelist", "wxpython" ]
stackoverflow_0007577032_python_treelist_wxpython.txt
Q: Critique my Python Package Structure I'm in the process of finishing up a Python package I've been writing. However, before I release it I'd like to get some feedback on the overall structure of the package as well as the __init__.py file. This should give an idea of what my __init__.py file looks like. ''' A doc...
Critique my Python Package Structure
I'm in the process of finishing up a Python package I've been writing. However, before I release it I'd like to get some feedback on the overall structure of the package as well as the __init__.py file. This should give an idea of what my __init__.py file looks like. ''' A docsting describing the package. ''' __autho...
[ "You should use absolute imports instead of relative imports, e.g. import mypackage.mypath as mypath.\n" ]
[ 1 ]
[]
[]
[ "init", "module", "package", "python" ]
stackoverflow_0007577651_init_module_package_python.txt
Q: Python3 print statement doesn't work as expected I am using Python 3.2.2 >>> s = 'hhh' >>> print s SyntaxError: invalid syntax >>> print(s) hhh >>> print 2*2 SyntaxError: invalid syntax >>> print(2*2) 4 Why do I have to use print("...") to print something? If I dno't it complains with 'SyntaxError'. A: As of p...
Python3 print statement doesn't work as expected
I am using Python 3.2.2 >>> s = 'hhh' >>> print s SyntaxError: invalid syntax >>> print(s) hhh >>> print 2*2 SyntaxError: invalid syntax >>> print(2*2) 4 Why do I have to use print("...") to print something? If I dno't it complains with 'SyntaxError'.
[ "As of python 3.0, print is a function. See: \nhttp://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function\n" ]
[ 21 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007577678_python_python_3.x.txt
Q: OpenWRT XMPP client library? is there any python XMPP client library for OpenWRT? tnx. A: You'll probably have to cross-compile xmpppy yourself using the OpenWRT SDK.
OpenWRT XMPP client library?
is there any python XMPP client library for OpenWRT? tnx.
[ "You'll probably have to cross-compile xmpppy yourself using the OpenWRT SDK.\n" ]
[ 1 ]
[]
[]
[ "openwrt", "python" ]
stackoverflow_0006727471_openwrt_python.txt
Q: lowest possible timeuuid in php (phpcassa) pycassa has pycassa.util.convert_time_to_uuid(time_arg, lowest_val=True, randomize=False) phpcassa has static string uuid1 ([string $node = null], [int $time = null]) Can phpcassa's uuid1 be used to get lowest/highest uuids like in pycassa? If not, what's the best approac...
lowest possible timeuuid in php (phpcassa)
pycassa has pycassa.util.convert_time_to_uuid(time_arg, lowest_val=True, randomize=False) phpcassa has static string uuid1 ([string $node = null], [int $time = null]) Can phpcassa's uuid1 be used to get lowest/highest uuids like in pycassa? If not, what's the best approach to ensure you get everything between two given...
[ "I believe that if you have a column with a type of UUID version 1, Cassandra will ignore the 'unique' component of the UUID and just use the time part for the range.\n", "Strictly speaking, Cassandra sorts primarily by the timestamp component of a v1 UUID, and in the case of a tie, it sorts by the remaining byte...
[ 1, 0 ]
[]
[]
[ "cassandra", "php", "python" ]
stackoverflow_0007573938_cassandra_php_python.txt
Q: Python: Preventing "if" staircases? Whenever I'm coding something that requires a lot of conditionals, I end up doing this: if foo: if bar: if foobar: if barfoo: if foobarfoo: if barfoobar: # And forever and ever and ever I can't write if foo and bar and foobar and ... be...
Python: Preventing "if" staircases?
Whenever I'm coding something that requires a lot of conditionals, I end up doing this: if foo: if bar: if foobar: if barfoo: if foobarfoo: if barfoobar: # And forever and ever and ever I can't write if foo and bar and foobar and ... because I check for the value list elements...
[ "\nI can't write if foo and bar and foobar and ... because I call list elements inside of an if somewhere down the line, and if the list index don't exist, I get an error.\n\nin python,and short circuits. If the left side of the expression is false, the right side is not evaluated at all. \nfoo = dict()\n\nif 'bar...
[ 9, 5, 3, 2, 1, 0, 0 ]
[]
[]
[ "if_statement", "list", "python" ]
stackoverflow_0004975457_if_statement_list_python.txt
Q: How to encode for a dict I have the following dict: dict = {"es-ES": "Capítulo "}. However, when I try to use the dict, I get the following error: SyntaxError: Non-ASCII character '\xc3' in file.. I looked into the massive Python unicode docs ( http://docs.python.org/howto/unicode.html ), but haven't been able t...
How to encode for a dict
I have the following dict: dict = {"es-ES": "Capítulo "}. However, when I try to use the dict, I get the following error: SyntaxError: Non-ASCII character '\xc3' in file.. I looked into the massive Python unicode docs ( http://docs.python.org/howto/unicode.html ), but haven't been able to figure this out yet. How wou...
[ "Add the following line:\n# -*- coding: utf-8 -*-\n\n(Assuming you are using UTF-8), to the top of your Python file and you will be able to use Unicode without issue. See the Python docs on unicode.\n* Also, don't use dict as a variable name - you'll shadow the built-in type of the same name\n" ]
[ 4 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0007578347_encoding_python.txt
Q: Make a .sis file (Symbian S60 3rd edition) from python(v2.6) script. I'm new to mobile programming and I would like to make a mobile app for symbian in python. I read that for S60 3rd edition I should use ensymble but the thing is that I'm using Python v2.6 and it seems that it isn't yet supported in ensymble. Doe...
Make a .sis file (Symbian S60 3rd edition) from python(v2.6) script.
I'm new to mobile programming and I would like to make a mobile app for symbian in python. I read that for S60 3rd edition I should use ensymble but the thing is that I'm using Python v2.6 and it seems that it isn't yet supported in ensymble. Does anyone know of other software and maybe some tutorials?? Thanks!
[ "well you should start with these:\nhttp://www.samontab.com/web/2011/06/create-installable-applications-sis-files-from-your-python-scripts-for-symbian/\nhttp://www.developer.nokia.com/Community/Wiki/PyS60_1.4.5_Quick_Start\nbook: Mobile Python Rapid Prototyping of Applications on the Mobile Platform \nthis book is ...
[ 1 ]
[]
[]
[ "mobile", "python", "s60", "symbian" ]
stackoverflow_0007215408_mobile_python_s60_symbian.txt
Q: Does there exist a Python IDE that allows one to emulate C#-like intellisense for autocompleting method calls on an object? For example, suppose I have the code: class Foo(object): def bar(self, x): '''blah blah blah''' return x+1 And suppose I am creating another class, that has a method that takes an ...
Does there exist a Python IDE that allows one to emulate C#-like intellisense for autocompleting method calls on an object?
For example, suppose I have the code: class Foo(object): def bar(self, x): '''blah blah blah''' return x+1 And suppose I am creating another class, that has a method that takes an instance of a Foo object and does something: class Baz(object): def goo(self, foo): foo.bar(1) ### I am a 'Foo' object. Aut...
[ "If you just have def goo(self, foo): with nobody calling it, there's no way to know what type foo will be. However, if you call goo in your code with a known Foo, the IDE can figure out that goo is always passed a Foo and autocomplete can work. This is how the Python Tools for Visual Studio works.\nNote that this ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007578074_python.txt
Q: Python expand OSX path with spaces in it I'm trying to modify the plist file at: /Volumes/MacintoshHD/Users/christian/Library/Application Support/iPhone Simulator/4.3.2/Library/Preferences/com.apple.Accessibility.plist Here's my noob python script: import plistlib import os.path #set path prefs_path = os.path.ex...
Python expand OSX path with spaces in it
I'm trying to modify the plist file at: /Volumes/MacintoshHD/Users/christian/Library/Application Support/iPhone Simulator/4.3.2/Library/Preferences/com.apple.Accessibility.plist Here's my noob python script: import plistlib import os.path #set path prefs_path = os.path.expanduser("~/Library/Application\ Support/iPhon...
[ "The expat error means that you've gotten to the file, but there's something wrong with it. Open the file and verify that it's not been corrupted.\nEDIT:\nAaah, it's a binary plist. Yeah, plistlib can't handle those. You want libplist instead.\n" ]
[ 3 ]
[]
[]
[ "ios_simulator", "plist", "python", "xcode" ]
stackoverflow_0007578850_ios_simulator_plist_python_xcode.txt
Q: Encoding Japanese characters How would I encode the following: chapter_mapping = {'chapter': ' チャプター'} so I can call chapter_mapping['chapter']. Thank you. A: You'll also need to add a header to your file in python 2: # -*- coding: utf-8 -*- chapter_mapping = {'chapter': u'チャプター'} A: Always use unicode litera...
Encoding Japanese characters
How would I encode the following: chapter_mapping = {'chapter': ' チャプター'} so I can call chapter_mapping['chapter']. Thank you.
[ "You'll also need to add a header to your file in python 2:\n# -*- coding: utf-8 -*-\nchapter_mapping = {'chapter': u'チャプター'}\n\n", "Always use unicode literals.\nchapter_mapping = {'chapter': u' チャプター'}\n\n" ]
[ 2, 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0007578854_encoding_python.txt
Q: question about python GUI So I am taking a digital image processing class that requires implementing some image filters, reconstruction, enhancements. I plan to use python for it but my professor wants to have a simple GUI with two canvas for pre- and post-processing images, a drop down box for filter selection, s...
question about python GUI
So I am taking a digital image processing class that requires implementing some image filters, reconstruction, enhancements. I plan to use python for it but my professor wants to have a simple GUI with two canvas for pre- and post-processing images, a drop down box for filter selection, some textboxes for filter value/...
[ "I recommend writing the processing code separately, then writing a GUI wrapper around it.\nThere are many choices, however I'd consider the big three below:\n\nTkinter, in the standard install, simple but a bit clunky.\nwxPython, a better choice, higher quality but a bit more complicated. Uses native widgets.\nPy...
[ 3 ]
[ "Look at Phatch. It is a Python Photo Batch Processor with a nice graphical user interface. It is based on PIL imaging library which you'll probably want to use.\n" ]
[ -1 ]
[ "python", "user_interface" ]
stackoverflow_0007578008_python_user_interface.txt
Q: SQL Update fails - pyodbc - informix Updates to an informix database via a python script using pyodbc are silently failing. I am using the syntax as provided in the pyodbc wiki and tried manual commit as well as autocommit cursor= conn.cursor() cursor.execute("update eqpt set notes='BOB' where serialno='SAM'...
SQL Update fails - pyodbc - informix
Updates to an informix database via a python script using pyodbc are silently failing. I am using the syntax as provided in the pyodbc wiki and tried manual commit as well as autocommit cursor= conn.cursor() cursor.execute("update eqpt set notes='BOB' where serialno='SAM'") conn.commit() conn.close() I p...
[ "Two ideas:\n\nCheck how many records was changed (it is retured by execute()), and how many records should be changed (using SELECT count(*) ... WHERE...:\ncursor= conn.cursor()\n\nrs = c.execute(\"SELECT count(*) FROM eqpt WHERE serialno='SAM'\")\nfor txt in c.fetchall():\n print('before %s' % (txt[0]))\n\nrow...
[ 1 ]
[]
[]
[ "informix", "pyodbc", "python" ]
stackoverflow_0007538730_informix_pyodbc_python.txt
Q: Automatically append some text to every log message An application I'm working on uses the logging module to log errors etc. In such a case it would be nice to be able to include the HTTP referer, GET/POST arguments etc. in the log entry. While it would be possible to append it to the message before calling .error...
Automatically append some text to every log message
An application I'm working on uses the logging module to log errors etc. In such a case it would be nice to be able to include the HTTP referer, GET/POST arguments etc. in the log entry. While it would be possible to append it to the message before calling .error() etc, I'm looking for a way to do it at a central locat...
[ "I've never tried it, but I think that you can do it by specifying a FORMAT with logging.basicConfig. \nFrom the logging documentation:\n\nFORMAT = \"%(asctime)-15s %(clientip)s %(user)-8s %(message)s\"\nlogging.basicConfig(format=FORMAT)\nd = {'clientip': '192.168.0.1', 'user': 'fbloggs'}\nlogging.warning(\"Protoc...
[ 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0007400169_logging_python.txt
Q: Inconsistency of Python plus operator In [26]: l=[] In [27]: s="asdsad" In [28]: l+=s In [29]: l Out[29]: ['a', 's', 'd', 's', 'a', 'd'] However, In [30]: l+s --------------------------------------------------------------------------- TypeError Traceback (most recent call last) ...
Inconsistency of Python plus operator
In [26]: l=[] In [27]: s="asdsad" In [28]: l+=s In [29]: l Out[29]: ['a', 's', 'd', 's', 'a', 'd'] However, In [30]: l+s --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/xiaohan/code/proteincrawler/id_crawl...
[ "This is explained here. Copied from the link:\n\nIt's because the += operator is doing the equivalent of calling the extend method, which treats its argument as a generic sequence, and doesn't enforce type.\n\n" ]
[ 8 ]
[]
[]
[ "operators", "python" ]
stackoverflow_0007579719_operators_python.txt
Q: How to call to a python handler from jquery ajax? How to call to a python handler from jquery ajax? can any one give me an example? A: $.ajax({ url: "/resultshandler", type: 'POST', data: data, success: function(data, status){ //check status //do something with data } }); may this post will he...
How to call to a python handler from jquery ajax?
How to call to a python handler from jquery ajax? can any one give me an example?
[ "$.ajax({\n url: \"/resultshandler\",\n type: 'POST',\n data: data,\n success: function(data, status){\n //check status\n //do something with data\n }\n});\n\nmay this post will help you jquery.ajax post request to get data from app engine server\n" ]
[ 1 ]
[]
[]
[ "html", "jquery", "python", "tipfy" ]
stackoverflow_0007579729_html_jquery_python_tipfy.txt
Q: Map a set of values in python What would be the best approach to do the following: if lang=="en-US": chapter="chapter" if lang=="fr-FR": chapter="chapitre" # etc. Essentially I'm looking for a mapping that would do something like: lang = ['en-US', 'fr-FR', ...] --> chapter = ['chapter', 'chapitre', ...] ...
Map a set of values in python
What would be the best approach to do the following: if lang=="en-US": chapter="chapter" if lang=="fr-FR": chapter="chapitre" # etc. Essentially I'm looking for a mapping that would do something like: lang = ['en-US', 'fr-FR', ...] --> chapter = ['chapter', 'chapitre', ...] How would I accomplish this? Thank ...
[ "I always use a dictionary for that.\nlangs = {\n \"en-US\" : \"chapter\",\n \"fr-FR\" : \"chapitre\"\n}\n\ntest = langs['en-US']\n\nBut for translations, you should also consider gettext.\n", "Dictionaries are good for this.\n>>> chapter = {\n... \"en-US\": \"chapter\",\n... \"fr-FR\": \"chapitre\",\n....
[ 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007578037_python.txt
Q: Post picture to Tumblr using Python I'm trying to post a picture to tumblr, using python, in particular: http://code.google.com/p/python-tumblr/ #!/usr/bin/python from tumblr import Api import sys BLOG='example.tumblr.com' USER='example@example.com' PASSWORD='example' api = Api(BLOG,USER,PASSWORD) post_data = "pi...
Post picture to Tumblr using Python
I'm trying to post a picture to tumblr, using python, in particular: http://code.google.com/p/python-tumblr/ #!/usr/bin/python from tumblr import Api import sys BLOG='example.tumblr.com' USER='example@example.com' PASSWORD='example' api = Api(BLOG,USER,PASSWORD) post_data = "picture.png" title = "Title of my entry"...
[ "You aren't actually sending the image data, you're just sending a string with the filename in it, so that's not too surprising. The write_regular call allows HTML so if you can upload the photo somewhere, you should be able to use an <img src=\"...\" /> tag in your post text to have the image displayed within you...
[ 2, 2, 1 ]
[]
[]
[ "python", "tumblr" ]
stackoverflow_0004938203_python_tumblr.txt
Q: Website / App sizes What would you consider a micro, small, medium and large site based on unique visitors etc. Assuming all sites are very basic like: Django, blogging, photo uploading, etc. No special apps doing any crazy processing, just normal business website. Im trying to figure out how many Django sites wou...
Website / App sizes
What would you consider a micro, small, medium and large site based on unique visitors etc. Assuming all sites are very basic like: Django, blogging, photo uploading, etc. No special apps doing any crazy processing, just normal business website. Im trying to figure out how many Django sites would be comfortable on a Li...
[ "\nMicro <= 1k unique visitors/month and <= 5k pageviews\nSmall = 5k unique visitors/month and = 25k pageviews\nMedium = 25k unique visitors/month and = 150k pageviews\nLarge >= 200k unique visitors/month and >= 1M - 1.5M pageviews\n\nIt is hard to tell how many users you will fit on your Django site, because we ha...
[ 4 ]
[]
[]
[ "django", "python", "shared_hosting", "virtualhost" ]
stackoverflow_0007579682_django_python_shared_hosting_virtualhost.txt
Q: Filtering list of tuples based on the availability of a member in a list I want to filter a list of tuples like [(1,22,1),(5,1,8),(8,3,4),(7,5,6)] using a list like [1,7] which would eventually give me the result [(1,22,1),(5,1,8),(7,5,6)]; since (8,3,4) does not have either 1 or 7, it is eliminated. I can write a...
Filtering list of tuples based on the availability of a member in a list
I want to filter a list of tuples like [(1,22,1),(5,1,8),(8,3,4),(7,5,6)] using a list like [1,7] which would eventually give me the result [(1,22,1),(5,1,8),(7,5,6)]; since (8,3,4) does not have either 1 or 7, it is eliminated. I can write a comprehensive function for this. But I am looking for a short list comprehens...
[ ">>> tup_list = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]\n>>> filter_list = [1,7]\n>>> [tup for tup in tup_list if any(i in tup for i in filter_list)]\n[(1, 22, 1), (5, 1, 8), (7, 5, 6)]\n\n", "try with this one : \nitems = [(1,22,1),(5,1,8),(8,3,4),(7,5,6)]\nresult = [ item for item in items if (set([1,7]) & set(item)...
[ 8, 2 ]
[]
[]
[ "list", "list_comprehension", "python", "tuples" ]
stackoverflow_0007580052_list_list_comprehension_python_tuples.txt
Q: Paramiko starts a SSH proccess and it dies..why? Below is my code. When log into the server and I run ps aux | grep python I see all of the process start and then die after a second or two. If I run the command in the server..it works. I have tried with nohup.whithout nohup etc I am out of an explanation. Thi...
Paramiko starts a SSH proccess and it dies..why?
Below is my code. When log into the server and I run ps aux | grep python I see all of the process start and then die after a second or two. If I run the command in the server..it works. I have tried with nohup.whithout nohup etc I am out of an explanation. This is a long process that should take hours. key = para...
[ "Try checking the output of the command. There may be an error been written, and you won't see it with your current code. Try doing:\nstdin, stdout, stderr = ssh.exec_command('python /home/ubuntu/Optimization/pvServer2.py')\nprint 'exit_code: %d' % stdout.channel.recv_exit_status()\nprint stdout.read()\nprint stder...
[ 1 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0007578546_paramiko_python_ssh.txt
Q: How to add multiple records into a google app engine datastore I am trying to update a datastore by uploading a formatted file(contains multiple lines). Each line in the file will create a new record in google app engine datastore. I am not sure how to add multiple rows to the datastore within a for loop. I tried:...
How to add multiple records into a google app engine datastore
I am trying to update a datastore by uploading a formatted file(contains multiple lines). Each line in the file will create a new record in google app engine datastore. I am not sure how to add multiple rows to the datastore within a for loop. I tried: class Records(db.Model): something = db.StringProperty() .....
[ "for line in lines will keep the newline characters at the end of the lines; newlines aren't allowed in a StringProperty unless it's designated as multiline.\ntry record.something = line.rstrip() to remove the newlines.\n", "You can use the bulk loader to load data from a file into the datastore.\nhttp://code.goo...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007577129_google_app_engine_google_cloud_datastore_python.txt
Q: Checking a list of objects against another list of objects I have a user profile that contains a manytomany field which points to a set of favorite objects. I have a queryset that returns an set of those types of objects, independent of the favorites (though it may contain favorites). What I want to do is this: {...
Checking a list of objects against another list of objects
I have a user profile that contains a manytomany field which points to a set of favorite objects. I have a queryset that returns an set of those types of objects, independent of the favorites (though it may contain favorites). What I want to do is this: {% for object in objects %} <p>{% if user.get_profile.favorit...
[ "in\n", "Have you tried object in user.get_profile.favorites?\nIn any case, do your processing in your views, not in your templates.\n" ]
[ 7, 1 ]
[]
[]
[ "django", "django_queryset", "django_templates", "python" ]
stackoverflow_0007580358_django_django_queryset_django_templates_python.txt
Q: Using pandas, how do I subsample a large DataFrame by group in an efficient manner? I am trying to subsample rows of a DataFrame according to a grouping. Here is an example. Say I define the following data: from pandas import * df = DataFrame({'group1' : ["a","b","a","a","b","c","c","c","c", ...
Using pandas, how do I subsample a large DataFrame by group in an efficient manner?
I am trying to subsample rows of a DataFrame according to a grouping. Here is an example. Say I define the following data: from pandas import * df = DataFrame({'group1' : ["a","b","a","a","b","c","c","c","c", "c","a","a","a","b","b","b","b"], 'group2' : [1,2,3,4,1,3,5,6,5,4...
[ "I tested with apply, it seems that when there are many sub groups, it's very slow. the groups attribute of grouped is a dict, you can choice index directly from it:\nsubsampled = df.ix[(choice(x) for x in grouped.groups.itervalues())]\n\nEDIT: As of pandas version 0.18.1, itervalues no longer works on groupby obje...
[ 9 ]
[]
[]
[ "data.table", "numpy", "pandas", "python", "r" ]
stackoverflow_0007577546_data.table_numpy_pandas_python_r.txt
Q: How to install PyGObject with Python 3 support I've been trying to install PyGObject using a variety of methods. First, using apt-get but that only installs it for Python 2.x. Next I attempted to compile it myself but I have been having problems getting it to compile for Python 3. Does anyone know how to install i...
How to install PyGObject with Python 3 support
I've been trying to install PyGObject using a variety of methods. First, using apt-get but that only installs it for Python 2.x. Next I attempted to compile it myself but I have been having problems getting it to compile for Python 3. Does anyone know how to install it?
[ "First you need to install python3 and the development headers.\nThen you need to tell configure to use python3:\nPYTHON=python3 ./configure\n\nCompile and install normally\nmake\nmake install\n\nYou should then be able to use pygobject from python3.\n" ]
[ 5 ]
[]
[]
[ "linux", "pygobject", "python", "python_3.x" ]
stackoverflow_0007065310_linux_pygobject_python_python_3.x.txt
Q: Django Try Except Not Working I have this code, try: print "what" newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0]) print newClassName except: print "HAHA" This always prints "HAHA", despite the fact that I've...
Django Try Except Not Working
I have this code, try: print "what" newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0]) print newClassName except: print "HAHA" This always prints "HAHA", despite the fact that I've run the newClassName = ... code in...
[ "Please modify the code to this, run it and tell us what exception you are getting:\ntry:\n print \"what\"\n newClassName = CourseNameAndCodeAssociation.objects.get(departmentCode__iexact = nameAndNumberStore[0])\n print newClassName \nexcept Exception as e:\n print \"HAHA\"\n print e\n\nAls...
[ 10, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007580330_django_python.txt
Q: Suspected thread issue with pyinotify I have been working with pyinotify and I am having issues with it where after multiple changes to a folder it simply stops receiving notifications. I have a feeling it is something to do with the the fact that two threads are running; namely the notifier thread and the wxpytho...
Suspected thread issue with pyinotify
I have been working with pyinotify and I am having issues with it where after multiple changes to a folder it simply stops receiving notifications. I have a feeling it is something to do with the the fact that two threads are running; namely the notifier thread and the wxpython thread. The purpose of the app is to esse...
[ "I basically found out that that the issue was indeed the fact that pyinotify's threaded notifier and wxPython's main loop dont play nice together.\nThe solution was to create a custom main loop (something I didn't know you could do in the first place) and place the pyinotify's threaded notifier within that loop. T...
[ 2 ]
[]
[]
[ "inotify", "linux", "pyinotify", "python" ]
stackoverflow_0007404389_inotify_linux_pyinotify_python.txt
Q: ImportError: No module named paramiko I have installed "python-paramiko" and "python-pycrypto" in Red hat linux. But still when i run the sample program i get "ImportError: No module named paramiko". I checked the installed packages using below command and got confirmed. ncmdvstk:~/pdem $ rpm -qa | grep python-p ...
ImportError: No module named paramiko
I have installed "python-paramiko" and "python-pycrypto" in Red hat linux. But still when i run the sample program i get "ImportError: No module named paramiko". I checked the installed packages using below command and got confirmed. ncmdvstk:~/pdem $ rpm -qa | grep python-p python-paramiko-1.7.6-1.el3.rf python-pycry...
[ "Actually all these packages were installed outside the python folder.\nAnd all I did was linking the packages from python folder to packages folder. \nIt worked perfectly.\n" ]
[ 0 ]
[]
[]
[ "paramiko", "python", "redhat" ]
stackoverflow_0007553700_paramiko_python_redhat.txt
Q: exec in Python 3 To take the number of test cases and output all the input numbers, I can do the following in Python 2.5 exec"print input();"*input() How to do it in Python 3, in shortest possible way? A: Your obfuscated code works just fine in Python 3 too, once you have adapted for the changes, which can triv...
exec in Python 3
To take the number of test cases and output all the input numbers, I can do the following in Python 2.5 exec"print input();"*input() How to do it in Python 3, in shortest possible way?
[ "Your obfuscated code works just fine in Python 3 too, once you have adapted for the changes, which can trivially be done by running the code through 2to3.\nexec(\"print(input());\"*eval(input()))\n\n(Although eval should in this case be replaced with int() as that's what you want.)\nObviously, this is all ridicolo...
[ 3, 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005235887_python_python_3.x.txt
Q: Why this local variable can keep its value in the function Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I recently met a problem in Python. Code: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) the output would be [1] [1, 2] [1, 2, 3] but wh...
Why this local variable can keep its value in the function
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument I recently met a problem in Python. Code: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) the output would be [1] [1, 2] [1, 2, 3] but why the value in the local list: L in the function f remains unch...
[ "The default parameters are in fact initialized when the function is defined, so\ndef f(L = []): pass\n\nis quite similar to\nglobal default_L = []\ndef f(L = default_L): pass\n\nYou can see this way that it is the same list object that is used in every invocation of the function.\n", "The list in def f(a, L=[]) ...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007581425_python.txt
Q: how to obtain HTML-free contents for non-div tags I want to find the HTML-free content of all the tags except for tags inside <div id="nav"> For example, with the following HTML: <div id="nav"> <h1>Navigate!</h1> <nav role="navigation"> <h2 class="structural">Main navigation</h2> <ul> ...
how to obtain HTML-free contents for non-div tags
I want to find the HTML-free content of all the tags except for tags inside <div id="nav"> For example, with the following HTML: <div id="nav"> <h1>Navigate!</h1> <nav role="navigation"> <h2 class="structural">Main navigation</h2> <ul> <li><a href="/">Home</a></li> <li><a...
[ "Two alternatives for you:\nprint [t.string for t in div.findAll(match_only_non_divs)]\n# [u'Navigate!', None, u'Main navigation', None, None, u'Home', None, u'About']\n\nprint [t.string for t in div.findAll(match_only_non_divs) if t.string]\n# [u'Navigate!', u'Main navigation', u'Home', u'About']\n\n", "As for t...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0007580266_beautifulsoup_python_screen_scraping.txt
Q: python subprocess dd and stdout I am using subprocess to create a random file from /dev/random using unix dd. Now, if i want the data output of dd to be written to a file instead of stdout. so here's the code am using, import subprocess out_fd = open('test_file','w') def os_system_dd(): global out_fd out_fd....
python subprocess dd and stdout
I am using subprocess to create a random file from /dev/random using unix dd. Now, if i want the data output of dd to be written to a file instead of stdout. so here's the code am using, import subprocess out_fd = open('test_file','w') def os_system_dd(): global out_fd out_fd.write("executing the time dd command\...
[ "dd outputs its debugging information on stderr, not stdout:\nimport subprocess\nout_fd = open('test_file','w')\ndef os_system_dd():\n out_fd.write(\"executing the time dd command\\n\")\n cmd_list = ['time','dd','if=/dev/random', 'of=/home/anand/sys_entropy_random',\n 'bs=1M' ,'count=5...
[ 3, 2 ]
[]
[]
[ "dd", "python", "subprocess" ]
stackoverflow_0007581710_dd_python_subprocess.txt
Q: Python subprocess.Popen and asynchronous output I have simple Python script to execute test suite both under Windows and Linux. Every test writes its output to separate file. I use subprocess.Popen class to execute shell command in a cycle. Every shell command starts like that: def system_execute(self, command, pa...
Python subprocess.Popen and asynchronous output
I have simple Python script to execute test suite both under Windows and Linux. Every test writes its output to separate file. I use subprocess.Popen class to execute shell command in a cycle. Every shell command starts like that: def system_execute(self, command, path, out_file): params_list = command.split(' ') ...
[ "Before f.close(), you have to wait() for our subprocess.\ndef system_execute(self, command, path, out_file):\n params_list = command.split(' ') \n file_path = os.path.join(path, out_file)\n f = open(file_path, \"w\")\n sp = subprocess.Popen(params_list, stdout=f)\n sp.wait()\n f.close()\n\nor jus...
[ 16 ]
[]
[]
[ "asynchronous", "python", "subprocess" ]
stackoverflow_0007581951_asynchronous_python_subprocess.txt
Q: Problem sending data in hybi-10 WebSockets server I'm trying to implement the new hybi-10 protocol in a python server and for now I succeeded in the handshake and receiving data from the client (JavaScript) but now I'm having problems with sending the data to the client. I'm using a bit of a code from websockify ...
Problem sending data in hybi-10 WebSockets server
I'm trying to implement the new hybi-10 protocol in a python server and for now I succeeded in the handshake and receiving data from the client (JavaScript) but now I'm having problems with sending the data to the client. I'm using a bit of a code from websockify (encode_hybi function) to encode the frames according t...
[ "You used \\n\\r\\n\\r\\n at the end of the handshake format, but it should be \\r\\n\\r\\n. Currently the \\n is part of the key.\nAlthough I don't understand how you were still able to open a connection, it looks like removing the first \\n solves the problem.\n" ]
[ 4 ]
[]
[]
[ "javascript", "protocols", "python", "websocket" ]
stackoverflow_0007575339_javascript_protocols_python_websocket.txt
Q: Reading Font Colour Information From a PDF I am working on a piece of software that analyses PDF files and generates HTML based on them. There are a number of things out there that already do this so I know it is possible, I have to write my own for business reasons. I have managed to get all the text information...
Reading Font Colour Information From a PDF
I am working on a piece of software that analyses PDF files and generates HTML based on them. There are a number of things out there that already do this so I know it is possible, I have to write my own for business reasons. I have managed to get all the text information, positions, fonts out of the PDF but I am strug...
[ "The colour for text and other filled graphics is set using one of the g, rg or k operators in the content stream object in the PDF file, as described in section 4.5.7 Color Operators in the PDF reference manual.\nThe example G.3 Simple Graphics Example in the reference manual shows these operators being used to st...
[ 5 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0007581752_pdf_python.txt
Q: Python 2.7.1 Blogger API problem I recently started writing a simple client using the Blogger API to do some basic posting I implemented the client in Python and used the example code verbatim from the Blogger Developer's Guide to login, get the blog id, and make a new post. I ran the script and everything went f...
Python 2.7.1 Blogger API problem
I recently started writing a simple client using the Blogger API to do some basic posting I implemented the client in Python and used the example code verbatim from the Blogger Developer's Guide to login, get the blog id, and make a new post. I ran the script and everything went fine until I got to this line: return b...
[ "The stacktrace is actually pretty clear about this: You're calling decode() on a list instead of a tree element. Try getting the first element from the list and calling decode() on that:\nfirsttext = self.text[0].decode(MEMBER_STRING_ENCODING)\n\n" ]
[ 1 ]
[]
[]
[ "blogger", "python" ]
stackoverflow_0007562780_blogger_python.txt
Q: local_import function does not work local_import function randomly does not import my modules from modules directory. The Error is: ImportError: No module named testapp.modules.mymodule I have this problem when i use web2py with apache (with wsgi). I have no problem when i run locally with "python web2py.py" com...
local_import function does not work
local_import function randomly does not import my modules from modules directory. The Error is: ImportError: No module named testapp.modules.mymodule I have this problem when i use web2py with apache (with wsgi). I have no problem when i run locally with "python web2py.py" command. Any suggestion?
[ "As of version 1.96.1, local_import() has been deprecated. You should be able to do:\nimport mymodule\n\nand it will look in your application's /modules folder before checking sys.path.\n", "I will answer my own question :)\nI started using mod_proxy and everything is ok. \n", "Add testapp to your PYTHONPATH.\n...
[ 1, 1, 0 ]
[]
[]
[ "apache", "python", "web2py", "web2py_modules", "wsgi" ]
stackoverflow_0007525761_apache_python_web2py_web2py_modules_wsgi.txt
Q: How to parse RSS with GB2312 encoding in Python I have a RSS feed shich is encoded in GB2312 When I am trying to parse it using following code: for item in XML.ElementFromURL(feed).xpath('//item'): title = item.find('title').text It is not able to parse the Feed. Any Idea how to parse GB2312 encoded RSS feed...
How to parse RSS with GB2312 encoding in Python
I have a RSS feed shich is encoded in GB2312 When I am trying to parse it using following code: for item in XML.ElementFromURL(feed).xpath('//item'): title = item.find('title').text It is not able to parse the Feed. Any Idea how to parse GB2312 encoded RSS feed The error Log from Plex Media Server is below after ...
[ "Your error message is XMLSyntaxError: switching encoding: encoder error, line 1, column 36. You asked for ideas. Here's a novel idea: Tell us what is in the first 50 or so bytes of \"line 1\". Then somebody may be able to come up with a remedy.\nUpdate: The encoding declaration is incorrect. The data is NOT encode...
[ 2, 1 ]
[]
[]
[ "gb2312", "python", "rss", "unicode", "xml" ]
stackoverflow_0007569256_gb2312_python_rss_unicode_xml.txt
Q: How could I run this python script on my webserver? TorBulkExitList.py I have a web server that can run python scripts, but I have no experience at all with python. I uploaded the file (TorBulkExitList.py) to my server inside the cgi-bin folder and I tried calling it in the browser but it's giving me a 500 Interna...
How could I run this python script on my webserver? TorBulkExitList.py
I have a web server that can run python scripts, but I have no experience at all with python. I uploaded the file (TorBulkExitList.py) to my server inside the cgi-bin folder and I tried calling it in the browser but it's giving me a 500 Internal Server Error. Here's the python script: https://svn.torproject.org/svn/che...
[ "I see that file is a wsgi application (because it implements a application method.) You need to configure apache to send requests to it using mod_wsgi (or some other wsgi server.)\nTry adding this to the site's .htaccess (with the correct file path):\nWSGIScriptAlias /TorBulkExitList /usr/local/www/cgi-bin/TorBulk...
[ 2 ]
[]
[]
[ "apache", "cgi_bin", "mod_wsgi", "python", "wsgi" ]
stackoverflow_0007582521_apache_cgi_bin_mod_wsgi_python_wsgi.txt
Q: What does bare strings in the body of a class definition mean? Here is a snippet of code from django.core.exceptions: class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass Is the bare string in the body of the class a mere literal for documentation ? Or does i...
What does bare strings in the body of a class definition mean?
Here is a snippet of code from django.core.exceptions: class MiddlewareNotUsed(Exception): "This middleware is not used in this server configuration" pass Is the bare string in the body of the class a mere literal for documentation ? Or does it perform some magic ?
[ "It's a doc string: \n\nA docstring is a string literal that occurs as the first statement\n in a module, function, class, or method definition. Such a docstring\n becomes the __doc__ special attribute of that object.\nAll modules should normally have docstrings, and all functions and\n classes exported by a mod...
[ 8, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007582961_python.txt
Q: threading.Timer time precision What does the time accuracy of Python's threading.Timer depend on? Does it depend on the OS used? Does it depend on the Python implementation used? Does it depend on the interval? How can it be benchmarked? Are there already benchmarks out there? A: In CPython, the threading.Timer ...
threading.Timer time precision
What does the time accuracy of Python's threading.Timer depend on? Does it depend on the OS used? Does it depend on the Python implementation used? Does it depend on the interval? How can it be benchmarked? Are there already benchmarks out there?
[ "In CPython, the threading.Timer accuracy (waiting part) is based on a Condition.wait() call.\nThe Condition.wait() (implemented here) is done by successive sleep with a delay of min(delay * 2, remaining, .05) where delay is originally set at 0.0005 # 500 us -> initial delay of 1 ms. According to this implementatio...
[ 7 ]
[]
[]
[ "python", "time_precision", "timer" ]
stackoverflow_0007582752_python_time_precision_timer.txt
Q: Looking for method / module to determine the compiler which was used for building the CPython interpreter When I start the Python interpreter in command line mode I get a message saying which compiler was used for building it. Is there a way to get this information in Python ? I know I could start the interpreter ...
Looking for method / module to determine the compiler which was used for building the CPython interpreter
When I start the Python interpreter in command line mode I get a message saying which compiler was used for building it. Is there a way to get this information in Python ? I know I could start the interpreter with subprocess.Popen and parse the output, but I'm looking for an easier and more elegant method. The backgrou...
[ "Use platform.python_compiler().\n", "You can use the sys.version variable to access this information:\n>>> sys.version\n'2.7.2 (default, Jun 29 2011, 11:17:09) \\n[GCC 4.6.1]'\n\nIt will tell you which compiler was used to compile Python, but it won't ensure the mentioned compiler is installed on the system (thi...
[ 6, 3 ]
[]
[]
[ "cmake", "python" ]
stackoverflow_0007583022_cmake_python.txt
Q: Display custom method field in Admin Display Lets say I have some Django model that has a list of numbers as a field. I compute some statistics on the field using a custom method in the model. These models are displayed on the admin panel as an InlineAdminModel "embedded" in a parent object. Is there a way to disp...
Display custom method field in Admin Display
Lets say I have some Django model that has a list of numbers as a field. I compute some statistics on the field using a custom method in the model. These models are displayed on the admin panel as an InlineAdminModel "embedded" in a parent object. Is there a way to display this custom method value in the admin panel wh...
[ "fields is for editable fields. Use readonly_fields instead.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007581975_django_python.txt
Q: Rendering an iframe from HTML stored in the DB I have a HTML template that I'm rendering using Django. I'm passing in all the necessary context variables — my_heading is the heading, my_html is the mark-safed html. I'd like to display my_html in the iframe. <html> <head> <title>Iframe Example</title> ...
Rendering an iframe from HTML stored in the DB
I have a HTML template that I'm rendering using Django. I'm passing in all the necessary context variables — my_heading is the heading, my_html is the mark-safed html. I'd like to display my_html in the iframe. <html> <head> <title>Iframe Example</title> </head> <body> <p>{% my_heading %}</p...
[ "If I understand you correctly, you just want to show the HTML content that you prepared dynamically with Python within the Django template, correct? If that is the case, you do not need an Iframe. Iframes are only necessary if you would like to integrate parts of a different URI (webpage) as a frame (section on yo...
[ 3, 3, 0 ]
[]
[]
[ "django", "django_templates", "html", "iframe", "python" ]
stackoverflow_0007579573_django_django_templates_html_iframe_python.txt
Q: Pyramid and .ini configuration Each Pyramid application has an associated .ini file that contains its settings. For example, a default might look like: [app:main] use = egg:MyProject pyramid.reload_templates = true pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false ...
Pyramid and .ini configuration
Each Pyramid application has an associated .ini file that contains its settings. For example, a default might look like: [app:main] use = egg:MyProject pyramid.reload_templates = true pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false ... I am wondering if it is possibl...
[ "Sure you can.\nIn your entry point function (main(global_config, **settings) in __init__.py in most cases), your config is accessible in the settings variable.\nFor example, in your .ini:\n[app:main]\nblog.title = \"Custom blog name\"\nblog.comments_enabled = true\n\nIn your __init__.py:\ndef main(global_config, *...
[ 27 ]
[]
[]
[ "configuration_files", "ini", "pyramid", "python" ]
stackoverflow_0007570930_configuration_files_ini_pyramid_python.txt
Q: Python UDP server on ubuntu not working I am trying to run this script on a ubuntu 11.04 box: http://taoofmac.com/space/projects/ReGrowl Its a small script bound to UDP port 9887 designed to relay Growl packets. I can send the script Growl packets from the local machine and it works exactly as expected. However, w...
Python UDP server on ubuntu not working
I am trying to run this script on a ubuntu 11.04 box: http://taoofmac.com/space/projects/ReGrowl Its a small script bound to UDP port 9887 designed to relay Growl packets. I can send the script Growl packets from the local machine and it works exactly as expected. However, when trying to send packets from another machi...
[ "Your code binds the server to localhost, i.e. it only listens to local connections. Replace\nUDPServer.__init__(self,('localhost', GROWL_UDP_PORT), _RequestHandler)\n\nwith\nUDPServer.__init__(self,('', GROWL_UDP_PORT), _RequestHandler)\n\nto accept connections from anywhere.\n" ]
[ 3 ]
[]
[]
[ "growl", "python", "ubuntu_11.04", "udp" ]
stackoverflow_0007582525_growl_python_ubuntu_11.04_udp.txt
Q: How to add something to the index, commit it, then push the master branch to a named remote with dulwich? How can I add something to the index, as in git add . then git commit -m "message" then git push origin master using dulwich? So far I've found this http://www.samba.org/~jelmer/dulwich/apidocs/dulwich.inde...
How to add something to the index, commit it, then push the master branch to a named remote with dulwich?
How can I add something to the index, as in git add . then git commit -m "message" then git push origin master using dulwich? So far I've found this http://www.samba.org/~jelmer/dulwich/apidocs/dulwich.index.Index.html but it doesn't say much, does it? Thanks
[ "This is not a tested answer but it is closer on the push part:\n# set wants to master\ndef wantmaster(haves, wants):\n global repo\n return { \"refs/heads/master\": repo.refs[\"HEAD\"] }\n\nclient, src = dulwich.client.get_transport_and_path(origin_uri) \n\nclient.send_pack(src, wantmaster, repo.object_store.gen...
[ 5, 3 ]
[]
[]
[ "dulwich", "git", "python" ]
stackoverflow_0007575491_dulwich_git_python.txt
Q: Does Python have C#/Java-style interfaces? I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created. I'm about to start on a relatively large project, probably in python (I've written a lot of...
Does Python have C#/Java-style interfaces?
I worked for a few months as a C# programmer, and got used to the idea of generics/templates interfaces, which I could pass to a library without caring how the object was created. I'm about to start on a relatively large project, probably in python (I've written a lot of python before, but mostly my own code for data ...
[ "\nIf the answer's no, that's fine, but in that case what do people generally do instead?\n\nDuck Typing.\nWhat's important is to approach Python by dropping the technical baggage of C#.\nLearn Python as a new language. Don't try to map concepts between Python and C#. That way lies madness.\n\n\n\"INTERFACES, not...
[ 17, 5, 5, 4, 3 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0007572410_oop_python.txt
Q: Problems with python 2.4 and 2.4.4 in struct.unpack and win/lin i'm coding on a Linux debian machine with python 2.4. My neighbour with Windows XP and python 2.4.4 He can run this code: w1, w2, w3 = unpack("LLL", pack("LLHH", localtime, ipddr, counter, aid)) But when i try this code i become this error: w1, w2, w...
Problems with python 2.4 and 2.4.4 in struct.unpack and win/lin
i'm coding on a Linux debian machine with python 2.4. My neighbour with Windows XP and python 2.4.4 He can run this code: w1, w2, w3 = unpack("LLL", pack("LLHH", localtime, ipddr, counter, aid)) But when i try this code i become this error: w1, w2, w3 = unpack("LLL", pack("LLHH", localtime, ipddr, counter, aid)) struc...
[ "Use the I format code instead of L.\nOn your Linux machine, L isn't twice as long as H, it's four times as long -- 8 bytes (64 bits) instead of 4 bytes (32 bits).\nI should be 4 bytes (32 bits) on both.\nEdit: Make sure to read eryksun's comment.\n" ]
[ 4 ]
[]
[]
[ "32bit_64bit", "linux", "python", "python_2.x", "windows" ]
stackoverflow_0007583687_32bit_64bit_linux_python_python_2.x_windows.txt
Q: Environment info in Tornado I've been trying to use Tornado for some part of my application. For that, I want to find out the environment information of the user, that is, the browser and OS of the user. In pylons, I can do that but I am not getting how to do that in Tornado/ A: All that information is stored i...
Environment info in Tornado
I've been trying to use Tornado for some part of my application. For that, I want to find out the environment information of the user, that is, the browser and OS of the user. In pylons, I can do that but I am not getting how to do that in Tornado/
[ "All that information is stored in the request field of the the RequestHandler instance. It can be accessed via self.request from within RequestHandler methods.\nIt's an instance of tornado.httpserver.HTTPRequest. Information about browser, OS etc. will be found in the headers field. \nExample:\nimport tornado.iolo...
[ 1 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0007583900_python_tornado.txt
Q: Obtaining an Access_token to read Page Insights I've been working on using python to get access to Facebook insights information. I was able to get public information (e.g. 'likes' from cocacola's page) in addition to app insights for apps that I have developed. Because I am the admin and developer for both pages...
Obtaining an Access_token to read Page Insights
I've been working on using python to get access to Facebook insights information. I was able to get public information (e.g. 'likes' from cocacola's page) in addition to app insights for apps that I have developed. Because I am the admin and developer for both pages and apps, when I go to facebook.com/insights I will ...
[ "Why not using classic way:\n\nCreate an app and login to it using facebook (JS SDK for example), with the offline_access and read_insights permission.\nThe offline_access will give you a permanent access_token that you can use to access the insights anytime you want.\nThe JS SDK (method FB.login) will return an ob...
[ 1 ]
[]
[]
[ "access_token", "facebook_graph_api", "facebook_insights", "python" ]
stackoverflow_0007434144_access_token_facebook_graph_api_facebook_insights_python.txt
Q: Monkey patching 'datetime' produces strange results I'm trying to make one of my libraries compatible with Python 2.6. It uses the method datetime.timedelta.total_seconds which was added in 2.7, so to make it work with 2.6, I wanted to monkey patch it into timedelta like this: import datetime if not hasattr(datet...
Monkey patching 'datetime' produces strange results
I'm trying to make one of my libraries compatible with Python 2.6. It uses the method datetime.timedelta.total_seconds which was added in 2.7, so to make it work with 2.6, I wanted to monkey patch it into timedelta like this: import datetime if not hasattr(datetime.timedelta, 'total_seconds'): class timedelta(dat...
[ "The datetime module is written entirely in C.\nThis includes the function that subtracts one datetime.datetime object from another. That function -- called new_delta() -- directly instantiates PyDateTime_DeltaType, which is the original datetime.timedelta class (written in C). It won't notice that you've rebound d...
[ 3 ]
[]
[]
[ "datetime", "monkeypatching", "python", "python_datetime" ]
stackoverflow_0007583867_datetime_monkeypatching_python_python_datetime.txt
Q: Sub Process in its own Thread I'm wondering if the following class is sound. I'm using it to launch a bunch of simulators for each test in my test environment. class SubProcessInOwnThread(threading.Thread): def __init__(self, arguments, currentWorkingDirectory): self.arguments = arguments...
Sub Process in its own Thread
I'm wondering if the following class is sound. I'm using it to launch a bunch of simulators for each test in my test environment. class SubProcessInOwnThread(threading.Thread): def __init__(self, arguments, currentWorkingDirectory): self.arguments = arguments self.currentWorkingDir...
[ "I don't see the point of having a separate thread being stuck in wait() here. Working directly on the subprocess would work like\nclass SubProcessWithoutThread(object):\n def __init__(self, arguments, currentWorkingDirectory):\n self.arguments = arguments\n self.currentWorkingDirectory = currentWo...
[ 2 ]
[]
[]
[ "multithreading", "python", "python_3.x" ]
stackoverflow_0007583603_multithreading_python_python_3.x.txt
Q: Python (OpenCV) Median filter trouble I need to do a (fast) median filter of some images from Python, and after some time on Google it seems like OpenCV is the way to go for speed (even in Python). I got OpenCV up and running, and filters like Erode and Dilate works fine: cv.Erode(cv_im,cv_im,None,6) cv.Dilate(cv_...
Python (OpenCV) Median filter trouble
I need to do a (fast) median filter of some images from Python, and after some time on Google it seems like OpenCV is the way to go for speed (even in Python). I got OpenCV up and running, and filters like Erode and Dilate works fine: cv.Erode(cv_im,cv_im,None,6) cv.Dilate(cv_im,cv_im,None,6) The Median filter, howeve...
[ "Looks like you imported pyopencv as \"cv\". So you editting CV_MEDIAN to cv.CV_MEDIAN should help\n" ]
[ 3 ]
[]
[]
[ "median", "opencv", "python" ]
stackoverflow_0007584268_median_opencv_python.txt
Q: Django: how to properly use UserProfile? (Django auth extra information) i finally can make my Django+Auth app works. I add the extra information to the user as the docs say. Now, i've a simple question. When i'm building a model that is related to the user, which user should i relate to? To auth.models.User or to...
Django: how to properly use UserProfile? (Django auth extra information)
i finally can make my Django+Auth app works. I add the extra information to the user as the docs say. Now, i've a simple question. When i'm building a model that is related to the user, which user should i relate to? To auth.models.User or to my accounts.UserProfile? An example: I've a model for Product, and the Produc...
[ "You're doing the right thing.\nUserProfile is just an extension of the User model. \nAnd logically you're making a relation of a object with an object, not a relation of a object with some extra information. \nAlso, as you mentioned, you can always issue the 'get_profile' to get the extra data.\n" ]
[ 3 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0007584450_authentication_django_python.txt