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: I want to take a user submitted string and search for that exact string in a log file and print the line number Currently, I am using a regular expression to search for a pattern of numbers in a log file. I also want to add another search capability, general user submitted ascii string search and print out the lin...
I want to take a user submitted string and search for that exact string in a log file and print the line number
Currently, I am using a regular expression to search for a pattern of numbers in a log file. I also want to add another search capability, general user submitted ascii string search and print out the line number. This is what I have and trying work around (help is appreciated): logfile = open("13.00.log", "r") searchS...
[ "First of all, strings don't have a findall method -- I don't know where you got that. Second, why use a string method or regex at all? For a simple string search of the kind you're describing, in is sufficient, as in if search_string in line:. To get line numbers, a quick solution is the enumerate built-in functio...
[ 4, 1 ]
[]
[]
[ "full_text_search", "pattern_matching", "python" ]
stackoverflow_0005724681_full_text_search_pattern_matching_python.txt
Q: Move required files where they need to go I'm working on a Python script that unzips a compressed directory and installs some files. When you unzip the compressed file, there could be files like ./usr/bin/package or ./var/lib/package. The unzipped directory contains the names of the dirs where they actually need t...
Move required files where they need to go
I'm working on a Python script that unzips a compressed directory and installs some files. When you unzip the compressed file, there could be files like ./usr/bin/package or ./var/lib/package. The unzipped directory contains the names of the dirs where they actually need to go. Lets say the directory structure looks li...
[ "Use the zipfile module to read the zip file and extract(name, dest) to extract each file. For example:\nimport sys\nimport zipfile\n\ndef unzip(path, root='/'):\n zh = zipfile.ZipFile(path, 'r')\n for name in zh.namelist():\n zh.extract(name, root)\n zh.close()\n\nunzip(sys.argv[1])\n\nIf a file w...
[ 3, 0, 0 ]
[]
[]
[ "directory", "file", "move", "python" ]
stackoverflow_0005724940_directory_file_move_python.txt
Q: django | Returned from FormWizard: [{'sender': u'test@test.com', 'subject': u'test'}, {'message': u'ok'}] From this class: class ContactWizard(FormWizard): def done(self, request, form_list): return render_to_response('done.html', { 'form_data': [form.cleaned_data for form in form_list], }) I'm re...
django | Returned from FormWizard: [{'sender': u'test@test.com', 'subject': u'test'}, {'message': u'ok'}]
From this class: class ContactWizard(FormWizard): def done(self, request, form_list): return render_to_response('done.html', { 'form_data': [form.cleaned_data for form in form_list], }) I'm returning to done.html, which is simply: <u1> {{ form_data }} </u1> The output that is returned is [{'sender': ...
[ "form_data is a list of dicts.\n{{ form_data.0.sender }}\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005724928_django_python.txt
Q: How to convert pounds to kilograms in Python I am trying to figure out how to print an output of pounds or kilograms based on the input, here's my code: def conversion(): amount = input("Please specify the amount: ") if type(amount) is int: print "derp" answer = raw_input("Please choose between...
How to convert pounds to kilograms in Python
I am trying to figure out how to print an output of pounds or kilograms based on the input, here's my code: def conversion(): amount = input("Please specify the amount: ") if type(amount) is int: print "derp" answer = raw_input("Please choose between converting FROM kilograms/pounds: ") if answe...
[ "When you want to return multiple data items from a function in Python, you can return a tuple with both data items:\nreturn (amount * 2.2, \"pounds\")\n\nor\nreturn (amount / 2.2, \"kilograms\")\n\nModifying your function slightly:\ndef conversion():\n amount = input(\"Please specify the amount: \")\n if typ...
[ 2, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0005723919_if_statement_python.txt
Q: C++ or Python: Bruteforcing to find text in many webpages Suppose I want to bruteforce webpages: for example, http://www.example.com/index.php?id=<1 - 99999> and search each page to find if there contain a certain text. If the page contains the text, then store it into a string I kind of get it working in python, ...
C++ or Python: Bruteforcing to find text in many webpages
Suppose I want to bruteforce webpages: for example, http://www.example.com/index.php?id=<1 - 99999> and search each page to find if there contain a certain text. If the page contains the text, then store it into a string I kind of get it working in python, but it is quite slow (around 1-2 second per page, which would t...
[ "Most likely your problem has nothing to do with your ability to quickly parse HTML and everything to do with the latency of page retrieval and blocking on sequential tasks.\n1-2 seconds is a reasonable amount of time to retrieve a page. You should be able to find text on the page orders of magnitude faster. Howe...
[ 6, 4 ]
[]
[]
[ "c++", "html", "python", "webpage" ]
stackoverflow_0005724985_c++_html_python_webpage.txt
Q: Possible Fix to deal with Python Memory usage I have the following class: class C1: STORE = [] TYPE = [] ITEMS = [] PRICE = [] def __init__(self,STORE,TYPE,ITEMS,PRICE): self.STORE = STORE self.TYPE = TYPE self.ITEMS = ITEMS self.PRICE = PRICE The purpose of t...
Possible Fix to deal with Python Memory usage
I have the following class: class C1: STORE = [] TYPE = [] ITEMS = [] PRICE = [] def __init__(self,STORE,TYPE,ITEMS,PRICE): self.STORE = STORE self.TYPE = TYPE self.ITEMS = ITEMS self.PRICE = PRICE The purpose of the class is to store all the items in different st...
[ "You might try the array module, it was around in Python 2.3. Other than that, you may want to look into using a proper database for this stuff.\n", "You have a 800 x 30,000 matrix. That's 24 000 000 elements per array. That's already at about 100 MB of space if they're floats, but more because of object overhea...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005722872_python.txt
Q: Tail file into message queue I launch a process on a linux machine via python's subprocess (specifically on AWS EC2) which generates a number of files. I need to "tail -f" these files and send each of the resulting jsonified outputs to their respective AWS SQS queues. How would I go about such a task? Edit As sugg...
Tail file into message queue
I launch a process on a linux machine via python's subprocess (specifically on AWS EC2) which generates a number of files. I need to "tail -f" these files and send each of the resulting jsonified outputs to their respective AWS SQS queues. How would I go about such a task? Edit As suggested by this answer, asyncproc, a...
[ "You can use the subprocess.Popen class to run tail and read its output.\ntry:\n process = subprocess.Popen(['tail', '-f', filename], stdout=PIPE)\nexcept (OSError, ValueError):\n pass # TODO: handle errors\noutput = process.stdout.read()\n\nThe subprocess.check_output function provides this functionality ...
[ 0 ]
[]
[]
[ "asynchronous", "python", "subprocess" ]
stackoverflow_0005724407_asynchronous_python_subprocess.txt
Q: Using JRuby or Python to call some 3rd party Java libraries - architecture question I am evaluating what I will use on the front and back ends of a project. I definitely will need to use some 3rd party Java libraries, but I am curious whether there is a nice way to do the front and back-end layer in something lik...
Using JRuby or Python to call some 3rd party Java libraries - architecture question
I am evaluating what I will use on the front and back ends of a project. I definitely will need to use some 3rd party Java libraries, but I am curious whether there is a nice way to do the front and back-end layer in something like Ruby or Python? Or is it possible to just call the Java libraries from Ruby/Python and ...
[ "I know for a fact that you can call all your Java libraries using JRuby.\nYou can use the ruby programming language on your front and back end via Rails (Rails is a framework written in ruby).\nThe difference between MRI (Matz Ruby) and JRuby is that JRuby runs on the JVM, whereas MRI has its own VM which is diffe...
[ 1, 1 ]
[]
[]
[ "java", "jruby", "jython", "python", "ruby" ]
stackoverflow_0005722739_java_jruby_jython_python_ruby.txt
Q: Problem setting cookies in django I am trying to set and read cookies using the following code cookie_name = 'fbs_%s' % practice_settings.PRACTICE_ID response = HttpResponse( "blah" ) response.set_cookie( cookie_name, "cookie_value" ) value = request.COOKIES.get(cookie_name) print value For some reason value rema...
Problem setting cookies in django
I am trying to set and read cookies using the following code cookie_name = 'fbs_%s' % practice_settings.PRACTICE_ID response = HttpResponse( "blah" ) response.set_cookie( cookie_name, "cookie_value" ) value = request.COOKIES.get(cookie_name) print value For some reason value remains None. Is there something simple tha...
[ "You are setting the cookie in the response object (response.set_cookie( cookie_name, \"cookie_value\")), but trying to retrieve it from the request object (request.COOKIES.get(cookie_name)).\nWhen you set a cookie in the response it will not automatically be populated in the original request. It will be available ...
[ 3 ]
[]
[]
[ "cookies", "django", "httpresponse", "python", "setcookie" ]
stackoverflow_0005725454_cookies_django_httpresponse_python_setcookie.txt
Q: SqlAlchemy: How to create connections between users, i.e. make "friends" I'm trying to use SqlAlchemy to make Sqlite database tables inside of Pylons. I'm using declarative base to create the table, class, and mapper all at once with the following code: class Friends(Base): __tablename__ = 'friends' left_i...
SqlAlchemy: How to create connections between users, i.e. make "friends"
I'm trying to use SqlAlchemy to make Sqlite database tables inside of Pylons. I'm using declarative base to create the table, class, and mapper all at once with the following code: class Friends(Base): __tablename__ = 'friends' left_id = Column(Integer, ForeignKey('facebooks.id'), primary_key=True) right_id...
[ "Where is this much different from 1:N or N:M relationship? Storing the friend relationships in a table isFriend(user1_id, user2_id) is straight forward. If you think of a friendship relationship as graph, check this: http://www.sqlalchemy.org/docs/orm/examples.html#directed-graphs\n" ]
[ 2 ]
[]
[]
[ "database_design", "pylons", "python", "sqlalchemy" ]
stackoverflow_0005725606_database_design_pylons_python_sqlalchemy.txt
Q: how to get this string using python i have a list like this : a=[1000,200,30] and i want to get a list like this : ['01000','00200','00030'] so what can i do , thanks A: >>> a=[1000,200,30] >>> [str(e).zfill(5) for e in a] ['01000', '00200', '00030'] str.zfill A: str.format() is the preferred way to do this...
how to get this string using python
i have a list like this : a=[1000,200,30] and i want to get a list like this : ['01000','00200','00030'] so what can i do , thanks
[ ">>> a=[1000,200,30]\n>>> [str(e).zfill(5) for e in a]\n['01000', '00200', '00030']\n\nstr.zfill\n", "str.format() is the preferred way to do this if you are using Python >=2.6\n>>> a=[1000, 200, 30]\n>>> map(\"{0:05}\".format, a)\n['01000', '00200', '00030']\n\n", "You can do it like this:\na = [1000,200,30]\n...
[ 8, 5, 2, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005726134_python_string.txt
Q: Check if a non-nullable field is null I wanted to write some code like this: class SomeModel(models.Model): field = models.ForeignKey(SomeOtherModel) def __init__(self, *args, **kwargs): super(SomeModel, self).__init__(*args, **kwargs) if self.field is None: self.field = S...
Check if a non-nullable field is null
I wanted to write some code like this: class SomeModel(models.Model): field = models.ForeignKey(SomeOtherModel) def __init__(self, *args, **kwargs): super(SomeModel, self).__init__(*args, **kwargs) if self.field is None: self.field = SomeOtherModel() ... However this rais...
[ "Check if it has the attribute set -\nif hasattr(self, 'field')\n\n", "proper way to refer a field in form is like this:\nself.fields['myfield']\nso, in your case, the null check should go like this\nself.fields['myfield'].value is None \non the other note, don't use reserved/near to reserved words like 'field' f...
[ 10, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005725065_django_django_models_python.txt
Q: No module named urls After hitting the admin page I am getting an error no named url exceptions? Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.2.5 Exception Type: ImportError Exception Value: No module named urls Exception Location: /usr/local/lib/python2.6/dist-packages/dj...
No module named urls
After hitting the admin page I am getting an error no named url exceptions? Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 1.2.5 Exception Type: ImportError Exception Value: No module named urls Exception Location: /usr/local/lib/python2.6/dist-packages/django/utils/importlib.py in...
[ "you need to include admin urls, in your main url file\nfrom django.contrib import admin\nadmin.autodiscover()\n\n(r'^admin/(.*)', admin.site.root)\n\n" ]
[ 5 ]
[]
[]
[ "admin", "django", "import", "python" ]
stackoverflow_0005725667_admin_django_import_python.txt
Q: sendmail from python program In the below code ,the mails that are going from the system are going to a spam folder for the user ,the python code is given below.I suspect that sender from is going as root@. How to correct this def sendmail(to,fr,subject,msg): sendmail_location = "/usr/sbin/sendmail" # sendm...
sendmail from python program
In the below code ,the mails that are going from the system are going to a spam folder for the user ,the python code is given below.I suspect that sender from is going as root@. How to correct this def sendmail(to,fr,subject,msg): sendmail_location = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s...
[ "Why do you use the sendmail binary directly???\nPython has a nice smtplib module for sending mail through arbitrary mail servers\nand an email module for composing proper RFC-822 compliant mails.\nWhat you are doing is unlikely recommended.\n" ]
[ 3 ]
[]
[]
[ "linux", "python", "sendmail" ]
stackoverflow_0005726391_linux_python_sendmail.txt
Q: High Performance Server - what should I Use? I have a large game engine which serves mobile phone clients and a web site. The DB is MSSQL2008 and the engine is written using C#. The web site is built with ASP.NET MVC and the web service for the mobile phones is also built on ASP.NET MVC (probably will be migrated ...
High Performance Server - what should I Use?
I have a large game engine which serves mobile phone clients and a web site. The DB is MSSQL2008 and the engine is written using C#. The web site is built with ASP.NET MVC and the web service for the mobile phones is also built on ASP.NET MVC (probably will be migrated to WCF or pure socket server). The web site and th...
[ "The site you are using to ask this question is also on a very similar stack and they've written about it on blog.stackoverflow.com as well as the serverfault blog. You could probably peek through things they've been doing, but I suspect that what you may need to look into is some sort of cache layer.\n", "Besid...
[ 4, 0 ]
[]
[]
[ "c#", "iis_7", "performance", "python", "sql_server_2008" ]
stackoverflow_0005722992_c#_iis_7_performance_python_sql_server_2008.txt
Q: Regression confidence using SVMs in python I'm using regression SVMs in python and I am wondering if there is any way to get a "confidence-measure" value for its predictions. Previously, when using SVMs for binary classification, I was able to compute a confidence-type value from the 'margin'. Here is some pseudo-...
Regression confidence using SVMs in python
I'm using regression SVMs in python and I am wondering if there is any way to get a "confidence-measure" value for its predictions. Previously, when using SVMs for binary classification, I was able to compute a confidence-type value from the 'margin'. Here is some pseudo-code showing how I got a confidence value: # Beg...
[ "Have a look at this similar response on Stack back in January. The chosen answer was spot on regarding how hard it is to get confidence measures on non-parametric fitting methods. There's probably some Bayesian type thing you could do, but that's probably not possible with the Python SVM library: Prefer one class ...
[ 1 ]
[]
[]
[ "margin", "python", "regression", "svm" ]
stackoverflow_0005148168_margin_python_regression_svm.txt
Q: Sendmail without password authentication (Python 2.4) How can I sendmail from Python 2.4 without any password authentication? A: Look at the smptlib example: http://docs.python.org/library/smtplib.html There is no documentation telling you that authentication would be mandatory. Authentication is optional. A: ...
Sendmail without password authentication (Python 2.4)
How can I sendmail from Python 2.4 without any password authentication?
[ "Look at the smptlib example:\nhttp://docs.python.org/library/smtplib.html\nThere is no documentation telling you that authentication would be mandatory.\nAuthentication is optional.\n", "You need to configure your mail server to allow unauthenticated relaying from the IP running your python code (e.g. 127.0.0.1 ...
[ 5, 1 ]
[]
[]
[ "linux", "python", "sendmail" ]
stackoverflow_0005726781_linux_python_sendmail.txt
Q: Mac and Windows compatible GUI for Python, which is easy to install and works with pygame? I have made a program that finds and measures the radius of yeast colonies in images. It uses pygame for pixel access and graphical display of the images. The next step is to make it "user friendly" so that the non-programm...
Mac and Windows compatible GUI for Python, which is easy to install and works with pygame?
I have made a program that finds and measures the radius of yeast colonies in images. It uses pygame for pixel access and graphical display of the images. The next step is to make it "user friendly" so that the non-programmers in my university bio lab can use it. Pygame lacks scroll bars, text fields, "open file" dia...
[ "Fear not! Other people have had the same problem and have been helped. \nAlso, here are few useful links. These are GUI toolkits for PyGame GooeyPy, Mike's Simple GUI, OcempGUI and a whole lot more. \nPGU I think is one of the popular libraries that most game developers use and it seems to be reasonably well maint...
[ 3 ]
[]
[]
[ "portability", "pygame", "python", "tkinter", "user_interface" ]
stackoverflow_0005726974_portability_pygame_python_tkinter_user_interface.txt
Q: App engine validation with `django` and `css` Looking at those references etc, I have been unable to come up with a good way to couple everything together. The problem relates to send back the form and contents if the form is not valid. So what I am doing is pulling out each generated form item by item and display...
App engine validation with `django` and `css`
Looking at those references etc, I have been unable to come up with a good way to couple everything together. The problem relates to send back the form and contents if the form is not valid. So what I am doing is pulling out each generated form item by item and displaying in the .html file. So my question is. How do I ...
[ "You can add your own attributes to widgets (i.e. controls) that Django uses to render your form elements. This includes a class attribute for CSS styling:\nclass QuoteForm(djangoforms.ModelForm):\n email = EmailField(widget = TextInput(attrs={'class':'textfield'}))\n class Meta:\n model = Quote\n ...
[ 1 ]
[]
[]
[ "css", "django", "google_app_engine", "python" ]
stackoverflow_0005416196_css_django_google_app_engine_python.txt
Q: how to print a dict which has japanese word using python this is my code : import xlrd,sys data = xlrd.open_workbook('a.xls') boss = data.sheets()[3] print boss.row_values(3)[1] it can show the right word : キャプションサンプル。てすてす。改行もしたいよ but because the a.xls has many data , so i append this data to a dict in python...
how to print a dict which has japanese word using python
this is my code : import xlrd,sys data = xlrd.open_workbook('a.xls') boss = data.sheets()[3] print boss.row_values(3)[1] it can show the right word : キャプションサンプル。てすてす。改行もしたいよ but because the a.xls has many data , so i append this data to a dict in python , like this : stage_dict[stage_number]['boss'][boss_number]['n...
[ "You cannot. print(somedict) will always print the repr() of the dict which is valid python code using escape sequences.\nHowever, since printing a dict should be a debug-only thing anyway this is not really a problem. Displaying a value from the dict should work.\n", "You can derive your own class from dict and ...
[ 3, 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005726827_dictionary_python.txt
Q: How to create a master process in Python under Linux? When running, gunicorn (a python daemon) then a ps aux | grep gunicorn, you get a process for each worker and a master process. If you kill the master process, you kill them all. How to do this in Python? Is there a way for each process to communicate with each...
How to create a master process in Python under Linux?
When running, gunicorn (a python daemon) then a ps aux | grep gunicorn, you get a process for each worker and a master process. If you kill the master process, you kill them all. How to do this in Python? Is there a way for each process to communicate with each other (sending data, reponding to it asynchronously, etc)?...
[ "You can use the multiprocessing module to create the worker processes. In order to get the behavior you want, you need to implement a signal handler that will catch common kill signals, terminate the worker processes, and exit gracefully.\nSince gunicorn is open-source, you might also want to take a look at the co...
[ 4 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005727478_linux_python.txt
Q: Install script for C project with Python API I have a project which is mostly written in C, but it also has a Python API which uses Python extension modules written in C. What is the best way to write installation/deployment scripts for a Linux/UNIX environment? Usually, I use the make utility to compile and inst...
Install script for C project with Python API
I have a project which is mostly written in C, but it also has a Python API which uses Python extension modules written in C. What is the best way to write installation/deployment scripts for a Linux/UNIX environment? Usually, I use the make utility to compile and install projects written in C. Most of the time, I ju...
[ "If you cannot use python's distutils for some reason, you can try some heuristics in shell:\nINSTALL_PATH=$(python -c 'import sys; print [ i for i in sys.path if i.endswith(\"-packages\") ][0]')\n\ntested on:\n\nRHEL5: /usr/lib64/python2.4/site-packages\nDebian: /usr/local/lib/python2.6/dist-packages\nSolaris: /us...
[ 1, 0 ]
[]
[]
[ "c", "linux", "makefile", "python", "unix" ]
stackoverflow_0005719506_c_linux_makefile_python_unix.txt
Q: encryption/decryption with user input Idk why this is not outputing to the file, any ideas or help? def encrypt(text, key): alphabet = "abcdefghijklmnopqrstuvwxyz" text = text.lower() cipherText = "" for ch in text: idx = alphabet.find(ch) cipherText = cipherText + key[idx] retu...
encryption/decryption with user input
Idk why this is not outputing to the file, any ideas or help? def encrypt(text, key): alphabet = "abcdefghijklmnopqrstuvwxyz" text = text.lower() cipherText = "" for ch in text: idx = alphabet.find(ch) cipherText = cipherText + key[idx] return cipherText def decrypt(cipherText, key)...
[ "I can think of 2 tracks to be followed:\n\nuse raw_input, which returns a string, instead of input that returns a function (that invalidates your tests userInput == \"decrypt\" and similar)\nfor line in in_file: is enough to browse a file, you don't need to add read_line = in_file.readline()\n\n" ]
[ 0 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0005726357_encryption_python.txt
Q: py-appscript filter with datetime I am trying to use the day field of a datetime property as a filter when selecting events from an iCal calendar. The following doesn't seem to work (to select all events for the current date): cal = app("iCal").calendars["myCalender"].get() cDate = datetime.now() cEvents = cal.eve...
py-appscript filter with datetime
I am trying to use the day field of a datetime property as a filter when selecting events from an iCal calendar. The following doesn't seem to work (to select all events for the current date): cal = app("iCal").calendars["myCalender"].get() cDate = datetime.now() cEvents = cal.events[its.start_date.day==cDate.day].get(...
[ "This line\ncal.events[its.start_date.day==cDate.day].get()\n\nchecks its.start_date.day==cDate.day and returns False or True. As an index, this translates into 0 and 1 and takes one of the first two elements in the cal.events list. Is this what you want?\n" ]
[ 0 ]
[]
[]
[ "datetime", "filter", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0005727708_datetime_filter_py_appscript_python_sourceforge_appscript.txt
Q: Ignore Text between XML tag """ test.xml <xyz> <pqr> <abc><a href="data:text/html;charset=utf-8,base64,JTNjc2NyaXB0JTNlYWxlcnQoIlhTUyIpO2hpc3RvcnkuYmFjaygpOyUzYy9zY3JpcHQlM2UiPjwvYT4=</abc> </pqr> <pqr> <abc><iframe src="data:text/html;charset=utf-8,base64,JTNjc2NyaXB0JTNlYWxlcnQ...
Ignore Text between XML tag
""" test.xml <xyz> <pqr> <abc><a href="data:text/html;charset=utf-8,base64,JTNjc2NyaXB0JTNlYWxlcnQoIlhTUyIpO2hpc3RvcnkuYmFjaygpOyUzYy9zY3JpcHQlM2UiPjwvYT4=</abc> </pqr> <pqr> <abc><iframe src="data:text/html;charset=utf-8,base64,JTNjc2NyaXB0JTNlYWxlcnQoIlhTUyIpO2hpc3RvcnkuYmFjaygpOyUz...
[ "You can change the xml first and use cdata to enclose not well formatted xml\nexample:\n<xyz>\n <pqr>\n <abc><![CDATA[<a href=\"data:text/html;charset=utf-8,base64,JTNjc2NyaXB0JTNlYWxlcnQoIlhTUyIpO2hpc3RvcnkuYmFjaygpOyUzYy9zY3JpcHQlM2UiPjwvYT4=]]></abc>\n </pqr>\n <pqr>\n <abc><![CDATA...
[ 2, 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0005728248_python_xml_xml_parsing.txt
Q: Can Django's .annotate() return objects? I have a record set that looks like this (extraneous data omitted to protect the easily bored): id | user_id | created | units ----+---------+-------------------------------+------- 1 | 1 | 2011-04-18 15:43:02.737063+00 | 20 2 | 1 |...
Can Django's .annotate() return objects?
I have a record set that looks like this (extraneous data omitted to protect the easily bored): id | user_id | created | units ----+---------+-------------------------------+------- 1 | 1 | 2011-04-18 15:43:02.737063+00 | 20 2 | 1 | 2011-04-18 15:43:02.737063+00 | 4 3 | ...
[ "It looks like there was some confusion when I initially asked the question, and as a result I was directed to not use .values() when that wasn't actually the problem. The problem is that Django's .annotate() doesn't allow for the overwriting of column properties with calculated values, and only annotates objects ...
[ 7, 3, 0 ]
[]
[]
[ "annotate", "django", "python" ]
stackoverflow_0005718234_annotate_django_python.txt
Q: Condense list into string : ['z','y','x'...] -> 'zyx...' ? Python (2.7.1) If I have list='abcdedcba' and i want: a=z, b=y, c=x, d=w, e=v so it would translate to: translate='zyxwvwxya' How would I do this? If I construct a dictionary >>> d=dict(zip(('a','b','c','d','e'),('z','y','x','w','v'))) and type >>> examp...
Condense list into string : ['z','y','x'...] -> 'zyx...' ? Python (2.7.1)
If I have list='abcdedcba' and i want: a=z, b=y, c=x, d=w, e=v so it would translate to: translate='zyxwvwxya' How would I do this? If I construct a dictionary >>> d=dict(zip(('a','b','c','d','e'),('z','y','x','w','v'))) and type >>> example= d[x] for x in list >>> print translate ['z', 'y', 'x', 'w', 'v', 'w', 'x', ...
[ "the_list = ['z', 'y', 'x', 'w', 'v', 'w', 'x', 'y', 'z']\nprint \"\".join(the_list)\n\n", "For monoalphabetic substitution, use maketrans and translate from the string module. They operate like the unix tr command. Joining with an empty separator is the correct answer for that last step, but not necessary for th...
[ 12, 5, 2, 2, 1, 0 ]
[]
[]
[ "letters", "list", "python", "string", "translate" ]
stackoverflow_0005725843_letters_list_python_string_translate.txt
Q: Python print in embedded python wont display anything to cmd I have an application that launches a python script with parameters. When the script runs i print some info on the cmd. The funny thing is that i can't see anything from the print function on the cmd. If i redirect sys.stdout to a file i get what i want ...
Python print in embedded python wont display anything to cmd
I have an application that launches a python script with parameters. When the script runs i print some info on the cmd. The funny thing is that i can't see anything from the print function on the cmd. If i redirect sys.stdout to a file i get what i want to print which is strange. I'm using python 2.6.4. Anyone encounte...
[ "Are you using cmd.exe on windows? If so, there was or still is known problems trying to print to it using python. I believe the issue is a UTF-8 encoding problem. I have heard the following batch file will fix this issue (never tested).\nset PYTHONIOENCODING=UTF-8\ncmd /u /k chcp 65001\nset PYTHONIOENCODING=\nexit...
[ 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0005728837_printing_python.txt
Q: Calculating the null space of a matrix I'm attempting to solve a set of equations of the form Ax = 0. A is known 6x6 matrix and I've written the below code using SVD to get the vector x which works to a certain extent. The answer is approximately correct but not good enough to be useful to me, how can I improve th...
Calculating the null space of a matrix
I'm attempting to solve a set of equations of the form Ax = 0. A is known 6x6 matrix and I've written the below code using SVD to get the vector x which works to a certain extent. The answer is approximately correct but not good enough to be useful to me, how can I improve the precision of the calculation? Lowering eps...
[ "A is full rank --- so x is 0\nSince it looks like you need a least-squares solution, i.e. min ||A*x|| s.t. ||x|| = 1, do the SVD such that [U S V] = svd(A) and the last column of V (assuming that the columns are sorted in order of decreasing singular values) is x.\nI.e., \nU =\n\n -0.23024 -0.23241 0....
[ 10, 6 ]
[]
[]
[ "least_squares", "linear_algebra", "math", "python", "svd" ]
stackoverflow_0002992947_least_squares_linear_algebra_math_python_svd.txt
Q: 'int' object is not iterable when I'm not trying to iterate The following piece of code attempts to create a map that shows the minimum number of moves it would take to get from each square on that map to the specified location. The function as a whole is largely irrelevant to the problem, but I thought I should p...
'int' object is not iterable when I'm not trying to iterate
The following piece of code attempts to create a map that shows the minimum number of moves it would take to get from each square on that map to the specified location. The function as a whole is largely irrelevant to the problem, but I thought I should provide my problem in context. I've also imported deque from colle...
[ "The line does try to iterate:\n>>> a, b = 0\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'int' object is not iterable\n\nThe line\nsquares_to_check = deque((0, loc))\n\ninitialises the deque with the two elements 0 and loc, not with the single element (0, loc). Use\nsqu...
[ 7 ]
[]
[]
[ "deque", "python", "tuples", "typeerror" ]
stackoverflow_0005729068_deque_python_tuples_typeerror.txt
Q: Django / Python catch exception not working? Should this code not be working? if request.GET.has_key("category"): try: post_list = post_list.filter(category=request.GET.get("category")) except ValueError: print "Category is not an integer" Category is an IntegerField. I...
Django / Python catch exception not working?
Should this code not be working? if request.GET.has_key("category"): try: post_list = post_list.filter(category=request.GET.get("category")) except ValueError: print "Category is not an integer" Category is an IntegerField. I'm trying to handle the case when a user enters th...
[ "Try something like this:\ncategory = request.GET.get(\"category\")\nif category:\n try:\n post_list = post_list.filter(category=int(category))\n except ValueError:\n print \"That's not an integer\"\n\n", "No need for the if statement, request.GET.get will return None if it's not set.\ntry:\n ...
[ 3, 2 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0005729228_django_exception_python.txt
Q: Django-CMS plugin not working I've been working a Django-CMS plugin that uses the Flickr API, and after much debugging I finally got it working (locally). Once i migrated it to my server, it kept throwing this error on the edit page: The main part is : Exception Type: ValueError at /admin/cms/page/2/edit/500.shtml...
Django-CMS plugin not working
I've been working a Django-CMS plugin that uses the Flickr API, and after much debugging I finally got it working (locally). Once i migrated it to my server, it kept throwing this error on the edit page: The main part is : Exception Type: ValueError at /admin/cms/page/2/edit/500.shtml/ Exception Value: invalid literal ...
[ "This happened because the Flickr API was not compatible with Python 2.4, upgrading to Python 2.7 solved this problem.\n" ]
[ 1 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0004940244_django_django_cms_python.txt
Q: Parsing keepalived.conf, translate to json What would be the (python preferred) best way to parse the keepalived.conf format and return it to json ? I'd like to automate the adding/removing of virtual and real servers. My first guess is pyparsing, following a few answers from stackoverflow, but I can't get it to w...
Parsing keepalived.conf, translate to json
What would be the (python preferred) best way to parse the keepalived.conf format and return it to json ? I'd like to automate the adding/removing of virtual and real servers. My first guess is pyparsing, following a few answers from stackoverflow, but I can't get it to work ! The format of keepalived.conf is like this...
[ "Here is a rough first pass at parsing this data:\nfrom pyparsing import *\n\n# basic punctuation - useful in parsing, but suppress from results \nLBRACE,RBRACE = map(Suppress, \"{}\")\n\n# some simple terminals\nipv4_address = Regex(r\"\\d{1,3}(\\.\\d{1,3}){3}\")\nipv6_address = Regex(r\"[0-9a-fA-F:]+\")\nip_ad...
[ 0 ]
[]
[]
[ "json", "parsing", "python" ]
stackoverflow_0005729269_json_parsing_python.txt
Q: complex sorting on python ,very trivial but interesting bug I wanted to sort with 'sets' or 'a'. I try with the information below . >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] http://wiki.python.org/moin/HowTo/Sorting/ That function works w...
complex sorting on python ,very trivial but interesting bug
I wanted to sort with 'sets' or 'a'. I try with the information below . >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] http://wiki.python.org/moin/HowTo/Sorting/ That function works with 'count' but not with 'sets', 'a'. class Number: def __ini...
[ "If you follow the link you gave, you will realize you must instantiate your objects like this:\nnumber_objects = [Number([1, 3, 7], 2, 3),\n Number([3, 7], 2, 2), \n .......\n ]\n\nthen,\nsorted(number_objects, key=attrgetter('sets', 'count'))\n\nshould work.\nFor...
[ 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0005729404_python_sorting.txt
Q: Idiomatic way to print arbitrary number of items from a list on each line I want to print data from a list, such as: ['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70'] However, rather than printing one element in the list using something like: for item in list: print item I want to print an arbitrary number o...
Idiomatic way to print arbitrary number of items from a list on each line
I want to print data from a list, such as: ['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70'] However, rather than printing one element in the list using something like: for item in list: print item I want to print an arbitrary number of items from the list on each line. I can think of many messy ways to do it an...
[ "This works. It seems pretty simple.\nfor i in range(0, len(some_list), line_length):\n print( some_list[i:i+line_length] )\n\nIf you want the literal formatting shown in the question, you'd have to do something like this.\nfor i in range(0, len(some_list), line_length):\n print( \" \".join( \"{0:.2f}\".for...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005729851_python.txt
Q: How does get_FIELD_display (in django) work? I'm a novice in Django and Python, and recently came across a number of methods in Django docs, such as Model.get_FOO_display(). Help page says that you can substitute FOO for a name of a field. I've been trying to figure out how that is possible in Python and looked in...
How does get_FIELD_display (in django) work?
I'm a novice in Django and Python, and recently came across a number of methods in Django docs, such as Model.get_FOO_display(). Help page says that you can substitute FOO for a name of a field. I've been trying to figure out how that is possible in Python and looked into 'Model' class souce. There I came across this:...
[ "This is all managed via the metaclass - you'll see in the source that the Model class defines a __metaclass__ attribute, which is set to ModelBase. The metaclass is to the class as a class is to an instance.\nSo the metaclass is called when a Django class is defined. The metaclass then executes various code which ...
[ 31, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005730211_django_python.txt
Q: Python: Asynchronous send/receive on normal socket and a http connection I have a task that needs to accept msgs (normal strings) at the frontend, do some processing and convert those msgs to http requests that need to be sent to a backend server. So there are essentially two endpoints - frontend is a normal BSD s...
Python: Asynchronous send/receive on normal socket and a http connection
I have a task that needs to accept msgs (normal strings) at the frontend, do some processing and convert those msgs to http requests that need to be sent to a backend server. So there are essentially two endpoints - frontend is a normal BSD socket. Backend is a urllib.HTTPconnection. Responses go the reverse way. Howe...
[ "Isn't the asyncore module of Python suitable for your problem? Or a framework like Twisted?\n" ]
[ 1 ]
[]
[]
[ "ajax", "asynchronous", "python", "sockets" ]
stackoverflow_0005730407_ajax_asynchronous_python_sockets.txt
Q: Django 1.3 performance As shown in "Why Django Sucks" slides, Django slowed down significantly between 0.96 and 1.2. Are there any tests measuring speed regression for 1.3 release? Anyone here experienced any speed change (in both directions) with upgrade? A: I have noticed no slow down in the django application...
Django 1.3 performance
As shown in "Why Django Sucks" slides, Django slowed down significantly between 0.96 and 1.2. Are there any tests measuring speed regression for 1.3 release? Anyone here experienced any speed change (in both directions) with upgrade?
[ "I have noticed no slow down in the django application itself while migrating a site from .9 to 1.3 on mysql. These slides may offer some useful criticisms, but the numbers don't seem to be useful at all.\nIn addition to django on mysql, I have been using django-nonrel based on 1.3 with mongodb and it is fast, I me...
[ 6 ]
[]
[]
[ "django", "performance", "python" ]
stackoverflow_0005728451_django_performance_python.txt
Q: How do I force a namespace prefix on an attibute in a SOAP request created using suds I am using python suds (version: 0.3.9 GA build: R659-20100219) to interact with a SOAP service with the following structure: Service ( DPWSService ) tns="http://ejb.revitalization.services.ndg/" Prefixes (1) ns0 = "http://ejb.r...
How do I force a namespace prefix on an attibute in a SOAP request created using suds
I am using python suds (version: 0.3.9 GA build: R659-20100219) to interact with a SOAP service with the following structure: Service ( DPWSService ) tns="http://ejb.revitalization.services.ndg/" Prefixes (1) ns0 = "http://ejb.revitalization.services.ndg/" Ports (1): (DPWSPort) Methods (13): addTimer(request request, ...
[ "What you're looking for is in suds documentation and is called a MessagePlugin. The marshalled option allows you to change you're message before being sent. You need to add it into your client as a plugin:\nself.client = Client(url, plugins=[MyPlugin()])\n\nIn marshalled method search for context.envelope childs. ...
[ 5, 0 ]
[]
[]
[ "attributes", "namespaces", "python", "soap", "suds" ]
stackoverflow_0005540023_attributes_namespaces_python_soap_suds.txt
Q: installing only .pyc (python compiled) with setuptools I want to run python setup.py install (the setup script uses setuptools), and I want only the .pyc files to be included in the resulting egg or directory. all .py files must not be present. How can I do this ? A: not with install, but a possibility is to run...
installing only .pyc (python compiled) with setuptools
I want to run python setup.py install (the setup script uses setuptools), and I want only the .pyc files to be included in the resulting egg or directory. all .py files must not be present. How can I do this ?
[ "not with install, but a possibility is to run the following command\npython setup.py bdist_egg --exclude-source-files\nand install the resulting egg in dist with easy_install\neasy_install dist/eggname.egg\nNote that according to the manual install is nothing but a shortcut to easy_install use.\n" ]
[ 26 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0005730686_python_setuptools.txt
Q: post method in Python I want to write a script in Python that would connect and post some data to several web-servers automatically. Please write how to post and submit data for example to google. Just can't understand how to do it from Python documentation. Thank You. A: Check the documentation on the urllib2 m...
post method in Python
I want to write a script in Python that would connect and post some data to several web-servers automatically. Please write how to post and submit data for example to google. Just can't understand how to do it from Python documentation. Thank You.
[ "Check the documentation on the urllib2 module and check out this urllib2 the missing manual. It's all there.\n", "If you are open for packages outside standard library, then mechanize is a good option for such tasks.\n" ]
[ 3, 0 ]
[]
[]
[ "post", "python" ]
stackoverflow_0005729935_post_python.txt
Q: python mysql insert the received message from android How to insert the received message from android to python in mySQL? In other words I'm opening socket between android and python and anything I enter in android it send to my python then I want this thing whatever string or it to be insert to python !! I know a...
python mysql insert the received message from android
How to insert the received message from android to python in mySQL? In other words I'm opening socket between android and python and anything I enter in android it send to my python then I want this thing whatever string or it to be insert to python !! I know about the insert method and it works fine with me but I want...
[ "What you might want to consider is setting up a Python-based Web service. Call the Web service from Android and have the Web service do your database INSERTs for you.\nBe sure to implement sufficient measures in your Web service to ensure that not-just-any query is allowed to be performed simply by passing it int...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005729430_mysql_python.txt
Q: Access the Twitter API + GetDirectMessages + Arduino in Python Following a tutorial I was able to get and parse the Twitter stream for my own account and send this information through the serial connection to interact with my Arduino project. However I need to get messages sent directly to me and not my public fee...
Access the Twitter API + GetDirectMessages + Arduino in Python
Following a tutorial I was able to get and parse the Twitter stream for my own account and send this information through the serial connection to interact with my Arduino project. However I need to get messages sent directly to me and not my public feed. Below is the code to get the public feed then my attempt at tryin...
[ "From your comment, it sounds like api.GetDirectMessages() returned an empty list. Print len(status) directly after the API call to verify that. Are you sure there are new direct messages available to read? Have you tried setting a specific date with api.GetDirectMessages() using the since parameter?\nInstead of ch...
[ 0 ]
[]
[]
[ "api", "arduino", "feed", "python", "twitter" ]
stackoverflow_0005724516_api_arduino_feed_python_twitter.txt
Q: Python xml.dom.minidom generates invalid XML? I have encountered strange problem with xml.dom.minidom python package. I generate a document, populating it with data taken from terminal. Sometimes such data contain terminal control characters. When I stored such character in text data node with minidom.toprettyxml(...
Python xml.dom.minidom generates invalid XML?
I have encountered strange problem with xml.dom.minidom python package. I generate a document, populating it with data taken from terminal. Sometimes such data contain terminal control characters. When I stored such character in text data node with minidom.toprettyxml() everything seems to be fine, however, the generat...
[ "Looking at the code for _write_data it only escapes ampersands, slashes and brackets:\ndef _write_data(writer, data):\n \"Writes datachars to writer.\"\n data = data.replace(\"&\", \"&amp;\").replace(\"<\", \"&lt;\")\n data = data.replace(\"\\\"\", \"&quot;\").replace(\">\", \"&gt;\")\n writer.write(da...
[ 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0005728118_minidom_python_xml.txt
Q: PyGame get sprite group hey guys, was trying to build pacman using pygame, have a small problem. When the pacman is moving if i press a key then it changes direction, unfortunately if there is a wall above then the pacman stops at that place and points upwards until i change the direction. I want help with how to ...
PyGame get sprite group
hey guys, was trying to build pacman using pygame, have a small problem. When the pacman is moving if i press a key then it changes direction, unfortunately if there is a wall above then the pacman stops at that place and points upwards until i change the direction. I want help with how to find out if the block 3 or 4 ...
[ "You could use:\nhttp://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide\npacman.rect.y = pacman.rect.y - 3 \ncolliding = pygame.sprite.spritecollide(pacman, level) \nif colliding:\n can_move_upwards = False\nelse:\n can_move_upwards = True\npacman.rect.y = pacman.rect.y + 3\n\nAnd do the same ...
[ 2, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005664158_pygame_python.txt
Q: making sprites randomly appear I am trying to have sprites randomly appear on the screen with out using OOP principles this code is from a ants demo for AI if randint(1, 10) == 1: leaf = Leaf(world, leaf_image) leaf.location = Vector2(randint(0, w), randint(0, h)) world....
making sprites randomly appear
I am trying to have sprites randomly appear on the screen with out using OOP principles this code is from a ants demo for AI if randint(1, 10) == 1: leaf = Leaf(world, leaf_image) leaf.location = Vector2(randint(0, w), randint(0, h)) world.add_entity(leaf) world.pr...
[ "A sprite is an object. So you need to use some OOP to work with a sprite. Here's an example:\n# Sample Python/Pygame Programs\n# Simpson College Computer Science\n# http://cs.simpson.edu/?q=python_pygame_examples\n\nimport pygame\nimport random\n\n# Define some colors\nblack = ( 0, 0, 0)\nwhite = ( 255...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005292447_pygame_python.txt
Q: PyCUDA: Querying Device Status (Memory specifically) PyCUDA's documentation mentions Driver Interface calls in passing, but I'm a bit think and can't see how to get information such as 'SHARED_SIZE_BYTES' out of my code. Can anyone point me to any examples of querying the device in this way? Is it possible to / ...
PyCUDA: Querying Device Status (Memory specifically)
PyCUDA's documentation mentions Driver Interface calls in passing, but I'm a bit think and can't see how to get information such as 'SHARED_SIZE_BYTES' out of my code. Can anyone point me to any examples of querying the device in this way? Is it possible to / How do I check the device state (eg between malloc/memcpy ...
[ "Just for anyone else coming across this, spending half an hour with the CUDA API in one hand, and the PyCUDA documentation in another does wonders. Its much simpler than my initial experiments indicated.\nRuntime Kernel Info\nIncoming lazy lazy code\n...\nkernel=mod.get_function(\"foo\")\nmeminfo(kernel)\n...\ndef...
[ 21 ]
[]
[]
[ "cuda", "device_driver", "gpgpu", "pycuda", "python" ]
stackoverflow_0005730010_cuda_device_driver_gpgpu_pycuda_python.txt
Q: Python memory management for list() I'm creating a tuple, and then converting it to a list with the code: y=("hello","the","world") y=list(y) Does python simply mark the objects as now mutable and reachable through the label y, or does it create a complete copy of every object, add these to the new list structure...
Python memory management for list()
I'm creating a tuple, and then converting it to a list with the code: y=("hello","the","world") y=list(y) Does python simply mark the objects as now mutable and reachable through the label y, or does it create a complete copy of every object, add these to the new list structure, and then delete the original immutable ...
[ "During the execution of the line\ny = list(y)\n\nthe following happens:\n\nThe right-hand side gets evaluated. This includes creating a new list object. The list object is filled with the items of the tuple object passed to the constructor. These items are not copied. Rather their reference count is increased,...
[ 14, 9, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005731878_python.txt
Q: Git in Python and Spec Files I am currently writing a Python script for use on Linux machines that will loop through a list of packages and update their rpm spec files on a repository to include a certain change. My difficulty is with actually getting the spec files (which are blobs?) from the git repository. Some...
Git in Python and Spec Files
I am currently writing a Python script for use on Linux machines that will loop through a list of packages and update their rpm spec files on a repository to include a certain change. My difficulty is with actually getting the spec files (which are blobs?) from the git repository. Some guidance would be appreciated on ...
[ "Assuming the name of the file is A/b/foo.spec for package A, you would\n f = open (\"repository/A/b/foo.spec\")\n change_file(f)\n run_command(git add A/b/foo.spec)\n run_command(git commit -m \"Changed spec file for package A\")\n\nImplement the change_file and run_command functions. The run_command functions...
[ 0 ]
[]
[]
[ "git", "python", "rpm", "specifications" ]
stackoverflow_0005731840_git_python_rpm_specifications.txt
Q: Pygame screen freezes when I close it The code loads up a pygame screen window, but when I click the X to close it, it becomes unresponsive. I'm running on a 64-bit system, using a 32-bit python and 32-bit pygame. from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) ga...
Pygame screen freezes when I close it
The code loads up a pygame screen window, but when I click the X to close it, it becomes unresponsive. I'm running on a 64-bit system, using a 32-bit python and 32-bit pygame. from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop()
[ "Mach1723's answer is correct, but I would like to suggest another variant of a main loop:\nwhile 1:\n for event in pygame.event.get():\n if event.type == QUIT: ## defined in pygame.locals\n pygame.quit()\n sys.exit()\n\n if event.type == ## Handle other event types here...\n\...
[ 9, 4, 2, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005615860_pygame_python.txt
Q: How can I store data items in individual variables from an extracted table in Python? I have another question about how to collect data from a table. This is an ongoing project and previous answers have been extremely helpful since I'm pretty new to Python. I have now successfully extracted a table from html usin...
How can I store data items in individual variables from an extracted table in Python?
I have another question about how to collect data from a table. This is an ongoing project and previous answers have been extremely helpful since I'm pretty new to Python. I have now successfully extracted a table from html using BeatifulSoup thanks to previous answers to my questions. Now my new problem is storing i...
[ "Do you mean store rather than just printing each row? You can put them into a dictionary; assuming the columns are always in that order and are always specified you can use something like:\npayment_dict = {}\nfor tr in rows:\n year_td, salary_td, bonus_td = tr.findAll('td')\n salary = salary_td.find(text=True)\n...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005731777_beautifulsoup_python.txt
Q: How to make a many to many or a foreign key not required in a model for django? here is my model : class Page(models.Model): template = models.CharField(max_length=200,blank=True) self_url = models.ForeignKey('liens.Lien',null=True,blank=True) Categorie = models.ForeignKey(Categorie_Page,null=True,blan...
How to make a many to many or a foreign key not required in a model for django?
here is my model : class Page(models.Model): template = models.CharField(max_length=200,blank=True) self_url = models.ForeignKey('liens.Lien',null=True,blank=True) Categorie = models.ForeignKey(Categorie_Page,null=True,blank=True) Liens = models.ManyToManyField('liens.Lien',related_name="Liens sur la pa...
[ "Set on the relevant fields null=True and update your database.\nIt looks like you've already set null on self_url, so the problem is that your database has not been updated with this nullable information. Syncdb will not update your tables!\nrun python manage.py reset myapp (this will destroy / recreate your table...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005732369_django_django_models_python.txt
Q: Automate WordPress Install from python I have a python program that sets up a wordpress site on my server. It downloads the zip and unzips it into a directory, sets up the database and user, configures the config file. Now I would like to call the the wp_install function in wp-admin/include/upgrade.php and pass it...
Automate WordPress Install from python
I have a python program that sets up a wordpress site on my server. It downloads the zip and unzips it into a directory, sets up the database and user, configures the config file. Now I would like to call the the wp_install function in wp-admin/include/upgrade.php and pass it the parameters it needs $weblog_title, $use...
[ "It looks like wp_install() gets called inside of /wp-admin/install.php during step 1, and after form data has been validated. If you submit ?step=1& ... (all of the other required form fields) it should result in calling wp_install. So yes, you should be able to use urllib(2) for this.\n", "Urllib is an option...
[ 1, 0 ]
[]
[]
[ "python", "wordpress" ]
stackoverflow_0005732384_python_wordpress.txt
Q: Dividing binary image into 'blocks' of pixel data I am using Python and PIL as part of my work on embedding data in binary images and need to analyse groups of pixels to determine appropriate pixels to manipulate in order to embed data. The image needs to be split into equal 'blocks' of pixel data ready for analys...
Dividing binary image into 'blocks' of pixel data
I am using Python and PIL as part of my work on embedding data in binary images and need to analyse groups of pixels to determine appropriate pixels to manipulate in order to embed data. The image needs to be split into equal 'blocks' of pixel data ready for analysis, but I am struggling to come up with an appropriate ...
[ "You need to use numpy array slicing to get group of pixels. Image is just 2D array, so you can use arr = numpy.array(Image.open(filename)), and after you can slice it.\n#this code block from my fractal dimension finder\nstep = 2**a\nfor j in range(2**l):\n for i in range(2**l):\n block = arr[j * step:(j ...
[ 3, 3 ]
[]
[]
[ "embedding", "numpy", "python", "python_imaging_library" ]
stackoverflow_0005716430_embedding_numpy_python_python_imaging_library.txt
Q: How can I make the Eclipse Python debugger more reliable? I've found that under some circumstances the Eclipse python debugger can be unreliable. For example, when stepping through a memory-hungry Python program I've found that after a certain point the debugger fails to respond. The entire process hangs with 100%...
How can I make the Eclipse Python debugger more reliable?
I've found that under some circumstances the Eclipse python debugger can be unreliable. For example, when stepping through a memory-hungry Python program I've found that after a certain point the debugger fails to respond. The entire process hangs with 100% cpu load. I've heard (unconfirmed) reports from developers th...
[ "There are known issues with Python 2.4 (so, if possible, get a newer version), still, if you're unable to get a newer version, at least use threadframe extension (http://pypi.python.org/pypi/threadframe). If None of that's possible, it's really expected that the debugger doesn't work as well as it could (as the de...
[ 2, 0 ]
[]
[]
[ "debugging", "eclipse", "pydev", "python" ]
stackoverflow_0003043597_debugging_eclipse_pydev_python.txt
Q: Python package external dependencies I'm writing a python script which uses an external library (paramiko). If I'm to release the package how do I package paramiko also? Is there anyway I can give it as we can give dependencies in java as .jar files? Edit: What I had in my mind was giving a single script and an ar...
Python package external dependencies
I'm writing a python script which uses an external library (paramiko). If I'm to release the package how do I package paramiko also? Is there anyway I can give it as we can give dependencies in java as .jar files? Edit: What I had in my mind was giving a single script and an archive file which contains all the dependen...
[ "Make it a proper package and read up about setuptools: Python setuptools link\nDependencies can be specified using 'install_requires' parameter inside the setup.py file of your package.\n", "\nIf I'm to release the package how do I package paramiko also?\n\nYou don't. Instead you declare the dependencies:\n\nIns...
[ 9, 4 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0005729051_packaging_python.txt
Q: Show retweeters of a Twitter status in Tweepy I've been trying to find a way of doing the equivalent of: retweeters_of('twitterstatusid') I can't see an explicit method in tweepy - and couldn't work out any other way of finding this. Any help appreciated. A: Solved: results = api.retweeted_by('statusid') (Th...
Show retweeters of a Twitter status in Tweepy
I've been trying to find a way of doing the equivalent of: retweeters_of('twitterstatusid') I can't see an explicit method in tweepy - and couldn't work out any other way of finding this. Any help appreciated.
[ "Solved: \nresults = api.retweeted_by('statusid') \n\n(This method was missing from documentation.)\n" ]
[ 3 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0005688762_python_tweepy_twitter.txt
Q: Python regex problem I'm trying to match any of the following lines with a regex in python: RAA RAA RAA RAA / OOO OOO RAA RAA / OOO OOO / ROCKY These strings should always be on their own line so RAA RAA moves over there. wouldn't match. I came up with this regex using RegExr: ^([A-Z]*([ ]?)*([A-Z]?)*([ \/]?)*)...
Python regex problem
I'm trying to match any of the following lines with a regex in python: RAA RAA RAA RAA / OOO OOO RAA RAA / OOO OOO / ROCKY These strings should always be on their own line so RAA RAA moves over there. wouldn't match. I came up with this regex using RegExr: ^([A-Z]*([ ]?)*([A-Z]?)*([ \/]?)*)*$ This works fine to mat...
[ "That regex is far too general: not only does it match more than you want, but it has so many *s that the regex matcher will constantly be pointlessly backtracking to try some other combination. I haven't tried to work the combinatorial tree, but it's at least several thousand attempts per non-matching line.\nSpe...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005733486_python_regex.txt
Q: How to iterate over the file in python I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error. Traceback (most recent call last): File "...
How to iterate over the file in python
I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error. Traceback (most recent call last): File "convert.py", line 7, in <module> print >...
[ "The traceback indicates that probably you have an empty line at the end of the file.\nYou can fix it like this:\nf = open('test.txt','r')\ng = open('test1.txt','w') \nwhile True:\n x = f.readline()\n x = x.rstrip()\n if not x: break\n print >> g, int(x, 16)\n\nOn the other hand it would be better to us...
[ 78, 14, 7, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005733419_python.txt
Q: how to display dialog using pygtk with glade I am trying create alert dailog using glade,but its not working .am i doing anything wrong here. test.glade : <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="wi...
how to display dialog using pygtk with glade
I am trying create alert dailog using glade,but its not working .am i doing anything wrong here. test.glade : <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- interface-naming-policy project-wide --> <object class="GtkWindow" id="window1"> <child> <object class="GtkVBox" ...
[ "Two things off the top of my head (assuming your indentation is correct and not like it is above):\n1.) You do not invoke the main loop like:\naddgui = app()\ngtk.main()\n\n2.) You have a typo in\nself.alert = self.builder.get_object('dailog1') ## dialog is spelled wrong\n\n" ]
[ 2 ]
[]
[]
[ "glade", "pygtk", "python", "user_interface" ]
stackoverflow_0005734274_glade_pygtk_python_user_interface.txt
Q: Is there a Tkinter widget equivalent to .NET's ListView control? In .NET, there is the ListView control, which displays a multicolumn list of items with clickable column headings one can use to sort the list in ascending or descending order by column. I need a scrollable Tkinter widget with exactly that behavior, ...
Is there a Tkinter widget equivalent to .NET's ListView control?
In .NET, there is the ListView control, which displays a multicolumn list of items with clickable column headings one can use to sort the list in ascending or descending order by column. I need a scrollable Tkinter widget with exactly that behavior, but there doesn't appear to be anything in the standard Tkinter module...
[ "If you're using a modern version of tkinter you can use the ttk.Treeview widget. \n" ]
[ 5 ]
[]
[]
[ "python", "tk_toolkit", "tkinter" ]
stackoverflow_0005733659_python_tk_toolkit_tkinter.txt
Q: CUDA: Unaligned Memory Access Not Supported: What am I missing? There are a few questions similar to this but in this case, its a bit weird; NVCC 3.1 doesn't like this but 3.2 and 4.0RC do; float xtmp[MAT1]; for (i=0; i<MAT1; i++){ xtmp[i]=x[p[i]]; //value that should be here } Where p is passed by reference...
CUDA: Unaligned Memory Access Not Supported: What am I missing?
There are a few questions similar to this but in this case, its a bit weird; NVCC 3.1 doesn't like this but 3.2 and 4.0RC do; float xtmp[MAT1]; for (i=0; i<MAT1; i++){ xtmp[i]=x[p[i]]; //value that should be here } Where p is passed by reference to the function (int *p) coming from... int p_pivot[MAT1],q_pivot[MA...
[ "That looks like a compiler bug to me. This will work with nvcc 3.1 on 64 bit platforms:\nfloat xtmp[MAT1];\n//Swap rows (x=Px)\nfor (i=0; i<MAT1; i++){\n int idx = p[i];\n xtmp[i]=x[idx]; //value that should be here\n}\n\nMy guess is that something in the implicit int to size_t conversion is breaking. Doesn'...
[ 2 ]
[]
[]
[ "cuda", "gpgpu", "nvcc", "python" ]
stackoverflow_0005729871_cuda_gpgpu_nvcc_python.txt
Q: connecting to a socket arg = data.split( ) args = '' for index,item in enumerate(arg) : if index > 3: if args == '': args = item else : args += ' ' + item if data.find('!check')...
connecting to a socket
arg = data.split( ) args = '' for index,item in enumerate(arg) : if index > 3: if args == '': args = item else : args += ' ' + item if data.find('!check') != -1: nick = data.sp...
[ "What arguments are you giving your code? The ValueError is telling you that you're trying to convert a period (.) to an integer, which makes no sense. What is args?\n" ]
[ 1 ]
[]
[]
[ "irc", "proxy", "python", "sockets" ]
stackoverflow_0005734770_irc_proxy_python_sockets.txt
Q: Should I use metaclasses here? I'm reading some data, which I want to create classes out of - this is done at load-time. The classes are grouped into a Special class, which can only be instantiated using run-time information. The classes depend on this Special class, so they can only be useful once it is created. ...
Should I use metaclasses here?
I'm reading some data, which I want to create classes out of - this is done at load-time. The classes are grouped into a Special class, which can only be instantiated using run-time information. The classes depend on this Special class, so they can only be useful once it is created. Here is some simplified code that sh...
[ "Since I generally prefer classes of closures in Python, I'd use factory classes here and avoid the use of dynamically created classes alltogether. Example:\nclass Foo:\n def __init__(self, param1, param2, special):\n self.param1 = param1\n self.param2 = param2\n self.special = special\n ...
[ 3, 2, 0 ]
[]
[]
[ "metaclass", "metaprogramming", "python" ]
stackoverflow_0005732464_metaclass_metaprogramming_python.txt
Q: Good way to read csvData using psycopg2 I am trying to get a fast i.e. fast and not a lot of code, way to get csv data into postgres data base. I am reading into python using csvDictreader which works fine. Then I need to generate code somehow that takes the dicts and puts it into a table. I want to do this automa...
Good way to read csvData using psycopg2
I am trying to get a fast i.e. fast and not a lot of code, way to get csv data into postgres data base. I am reading into python using csvDictreader which works fine. Then I need to generate code somehow that takes the dicts and puts it into a table. I want to do this automaticaly as my tables often have hundreds of va...
[ "Say you have a list of field names (presumably you can get this from the header of your csv file):\nfieldnames = ['Name', 'Address', 'City', 'State']\n\nAssuming they're all VARCHARs, you can create the table \"TableName\":\nsql_table = 'CREATE TABLE TableName (%s)' % ','.join('%s VARCHAR(50)' % name for name in f...
[ 4, 1 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0003571243_psycopg2_python.txt
Q: Speed of fetching web pages with Eventlet and Python? I am writing a relatively simple crawler in Python but I want to use asynchronous networking lib in order to fetch multiple pages concurrently.I saw the examples on their page but when I apply the same logic that is shown and works for ~200 web pages for ~100...
Speed of fetching web pages with Eventlet and Python?
I am writing a relatively simple crawler in Python but I want to use asynchronous networking lib in order to fetch multiple pages concurrently.I saw the examples on their page but when I apply the same logic that is shown and works for ~200 web pages for ~1000/2000 urls , the performance slows down.(Most of the urls ...
[ "We created a transformation proxy service with Spawning web server. Spawning is using eventlets internally. The purpose of a service was to expose legacy XML API to mobile applications (iPhone, Android, etc.)\nhttp://pypi.python.org/pypi/Spawning/\n1) The server calls ISS backed backend service which outputs XML u...
[ 2 ]
[]
[]
[ "asynchronous", "eventlet", "python", "web_crawler" ]
stackoverflow_0005734050_asynchronous_eventlet_python_web_crawler.txt
Q: In node tree, parent.addChild(self) is adding self to self I'm building a simple node tree in python. But when my constructor tries to add the current node as a child of a given parent, the current node also adds itself as a child of itself. Here's my constructor method (and the creation of children): children ...
In node tree, parent.addChild(self) is adding self to self
I'm building a simple node tree in python. But when my constructor tries to add the current node as a child of a given parent, the current node also adds itself as a child of itself. Here's my constructor method (and the creation of children): children = [] def __init__(self, parent=None, tag="[ROOT]", attrs=None):...
[ "When you initialize children at the class level every instance of your class ends up sharing the same list object.\n>>> class C:\n... children = []\n... \n>>> a = C()\n>>> b = C()\n>>> id(a.children)\n144349644\n>>> id(b.children)\n144349644\n\nTry initializing it in your constructor instead:\ndef __init__(self, ...
[ 4, 0 ]
[]
[]
[ "nodes", "python" ]
stackoverflow_0005734991_nodes_python.txt
Q: What's the benefit of allowing python files to import themselves I can't tell you how many times I've been bitten by accidentally naming my file like something I'm trying to import, resulting in python importing the file. This example should show what I'm talking about (my first example didn't work) if / is in PYT...
What's the benefit of allowing python files to import themselves
I can't tell you how many times I've been bitten by accidentally naming my file like something I'm trying to import, resulting in python importing the file. This example should show what I'm talking about (my first example didn't work) if / is in PYTHONPATH: /foo __init__.py /test foo.py __init__.py def do_thingy(...
[ "No, there isn't a use for importing yourself. But there also isn't a use for having two things that could be imported by the same name, so there's no point in detecting the case you've given and treating it specially.\n", "Python namespaces require each name to be distinct. Any time you import a module it is al...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005734833_python.txt
Q: Extracting values from XML using Python I have the following xml extracted from another xml file. <notifications> <notification name="ccmSmtp" oid="1.3.6.1" status="current"> <objects> <object module="callhome" name="ccmSmtp" /> </objects> <description>This is a description</description> </no...
Extracting values from XML using Python
I have the following xml extracted from another xml file. <notifications> <notification name="ccmSmtp" oid="1.3.6.1" status="current"> <objects> <object module="callhome" name="ccmSmtp" /> </objects> <description>This is a description</description> </notification> <notification name="ccmAlertGro...
[ "If you want to get the attributes for each item in notificationlist, you could do this:\nattrslist = [dict(node.attributes.items()) for node in notificationlist]\nprint attrslist[0]\n# => {u'status': u'current', u'oid': u'1.3.6.1', u'name': u'ccmSmtp'}\nprint attrslist[0]['status']\n# => current\n\nFrom here it wo...
[ 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0005729226_python_xml_xml_parsing.txt
Q: What is the easiest way to make an optional C extension for a python package? I've created a C extension that I'd like to enable in my Python package (using setuptools) only if a command line option is passed in. What is the easiest way to do this? I can't seem to find any straightforward ways of going about this...
What is the easiest way to make an optional C extension for a python package?
I've created a C extension that I'd like to enable in my Python package (using setuptools) only if a command line option is passed in. What is the easiest way to do this? I can't seem to find any straightforward ways of going about this.
[ "There's actually a distribute/setuptools feature called \"Features\" that can be used for this. \nIt's explicitly designed to have setup.py do different things based on --with-xxx and --without-xxx command line options.\n\nThis blog post gives a nice introduction, I can't find any better documentation at this time...
[ 15, 4 ]
[]
[]
[ "cython", "python", "python_c_extension", "setuptools" ]
stackoverflow_0004056657_cython_python_python_c_extension_setuptools.txt
Q: python self-less this works in the desired way: class d: def __init__(self,arg): self.a = arg def p(self): print "a= ",self.a x = d(1) y = d(2) x.p() y.p() yielding a= 1 a= 2 i've tried eliminating the "self"s and using a global statement in __init__ class d: def __init__(self,arg)...
python self-less
this works in the desired way: class d: def __init__(self,arg): self.a = arg def p(self): print "a= ",self.a x = d(1) y = d(2) x.p() y.p() yielding a= 1 a= 2 i've tried eliminating the "self"s and using a global statement in __init__ class d: def __init__(self,arg): global a ...
[ "\"self\" is the way how Python works. So the answer is: No! If you want to cut hair: You don't have to use \"self\". Any other name will do also. ;-) \n", "Python methods are just functions that are bound to the class or instance of a class. The only difference is that a method (aka bound function) expects the i...
[ 6, 4, 0 ]
[]
[]
[ "class", "python", "self" ]
stackoverflow_0005735286_class_python_self.txt
Q: can python write to file while file is open in notepad? I'm using csv.writer to write to file. Is it okay if the file is open in notepad at the same time? What about programs other than notepad? A: Notepad does not create explicit lock for open files. http://social.technet.microsoft.com/Forums/en/windowsserver20...
can python write to file while file is open in notepad?
I'm using csv.writer to write to file. Is it okay if the file is open in notepad at the same time? What about programs other than notepad?
[ "Notepad does not create explicit lock for open files.\nhttp://social.technet.microsoft.com/Forums/en/windowsserver2008r2branchoffice/thread/2d844400-66e3-4c94-9369-902056064f20\nhttp://en.wikipedia.org/wiki/File_locking\n", "As long as the application doesn't have a file lock on the file in question, then sure i...
[ 3, 1, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005735645_file_io_python.txt
Q: Fast conversion of C/C++ vector to Numpy array I'm using SWIG to glue together some C++ code to Python (2.6), and part of that glue includes a piece of code that converts large fields of data (millions of values) from the C++ side to a Numpy array. The best method I can come up with implements an iterator for the ...
Fast conversion of C/C++ vector to Numpy array
I'm using SWIG to glue together some C++ code to Python (2.6), and part of that glue includes a piece of code that converts large fields of data (millions of values) from the C++ side to a Numpy array. The best method I can come up with implements an iterator for the class and then provides a Python method: def __array...
[ "You will want to define __array_interface__() instead. This will let you pass back the pointer and the shape information directly.\n", "Maybe it would be possible to use f2py instead of swig. Despite its name, it is capable of interfacing python with C as well as Fortran. See http://www.scipy.org/Cookbook/f2py_a...
[ 2, 1, 0, 0 ]
[]
[]
[ "arrays", "c++", "numpy", "python", "swig" ]
stackoverflow_0005424324_arrays_c++_numpy_python_swig.txt
Q: Trying to figure out a recursive counting program in Python def countSubStringMatchRecursive(target,key): """Counts how many times key is in string(string,key)""" x=find(target,key) print x return x!=-1 and countSubStringMatchRecursive(target[x+1:],key)+1 So this program takes a given string and ...
Trying to figure out a recursive counting program in Python
def countSubStringMatchRecursive(target,key): """Counts how many times key is in string(string,key)""" x=find(target,key) print x return x!=-1 and countSubStringMatchRecursive(target[x+1:],key)+1 So this program takes a given string and counts how many times a substring shows up inside of it. So given...
[ "As jhwist said, String.find returns the lowest index of the match. Therefore the recursion will only happen if the substring is actually found (otherwise String.find returns -1).\nThis is a very inefficient way to do this. Python supports this function, it is called str.count(sub[, start[, end]]). Documented here:...
[ 2, 1, 0, 0 ]
[]
[]
[ "counting", "python", "recursion" ]
stackoverflow_0005735916_counting_python_recursion.txt
Q: Sort nodes after using getElementsByTagName by the nodes attributes EDIT The dictionary is the offender here, the answer marked on this question works, the dictionary does what it wants though. Sorting the dictionary is the answer in this case, but now I know how to sort nodes via attributes and so do you. END I a...
Sort nodes after using getElementsByTagName by the nodes attributes
EDIT The dictionary is the offender here, the answer marked on this question works, the dictionary does what it wants though. Sorting the dictionary is the answer in this case, but now I know how to sort nodes via attributes and so do you. END I am so happy to be asking Python questions, here is what I have: def parse_...
[ "The nodes are not sorted by the name in the XML, and also this is reflected in the list of nodes. They are going to appear in the same order from which they were iterated. Lists, by definition, are ordered. Dictionaries are not. The problem you're having is that when you're iterating the dictionary keys, your attr...
[ 2, 0 ]
[]
[]
[ "attributes", "minidom", "python", "sorting" ]
stackoverflow_0005735927_attributes_minidom_python_sorting.txt
Q: How to have a self instance in a staticmethod in Python As in the title I want to know how to have a self instance in a staticmethod in python. A: By definition, a static method does not have a self parameter. That's what makes it static. If it did have a self parameter, it would be a regular method and not a st...
How to have a self instance in a staticmethod in Python
As in the title I want to know how to have a self instance in a staticmethod in python.
[ "By definition, a static method does not have a self parameter. That's what makes it static. If it did have a self parameter, it would be a regular method and not a static method.\n" ]
[ 6 ]
[]
[]
[ "python", "singleton", "static_methods" ]
stackoverflow_0005736264_python_singleton_static_methods.txt
Q: how can I rollback a virtualenv environment I created a virtualenvironment using virtualenv and now I want to roll back what I have done and recreate a different virtualenvironment at a different location with different combination of modules. I know that I can just create the second one and use it while leaving t...
how can I rollback a virtualenv environment
I created a virtualenvironment using virtualenv and now I want to roll back what I have done and recreate a different virtualenvironment at a different location with different combination of modules. I know that I can just create the second one and use it while leaving the first one alone but would simply deleting the ...
[ "You can just delete the first and use the new one. Also consider using virtualenvwrapper to make maintaining your virtualenv's easier.\n" ]
[ 5 ]
[]
[]
[ "python", "unix", "virtualenv" ]
stackoverflow_0005736369_python_unix_virtualenv.txt
Q: Error message "MemoryError" in Python Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text: MemoryError. Other times...
Error message "MemoryError" in Python
Here's my problem: I'm trying to parse a big text file (about 15,000 KB) and write it to a MySQL database. I'm using Python 2.6, and the script parses about half the file and adds it to the database before freezing up. Sometimes it displays the text: MemoryError. Other times it simply freezes. I figured I could avoid...
[ "Generators are a good idea, but you seem to miss the biggest problem:\n(str for str in splitter.split(open(fn).read()) if str and str <> 'A' and str <> 'S')\nYou're reading the whole file in at once even if you only need to work with bits at a time. You're code is too complicated for me to fix, but you should be a...
[ 7, 2, 1, 1 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0000978841_memory_management_python.txt
Q: Dynamic Instance variables within Class Scope I've got a class that is a descendant of SQLAlchemy's declarative base. I need to write a bridge object that will translate between the declarative base and another system I am running, but I want the bridge object to not have to know exactly what columns are in my rec...
Dynamic Instance variables within Class Scope
I've got a class that is a descendant of SQLAlchemy's declarative base. I need to write a bridge object that will translate between the declarative base and another system I am running, but I want the bridge object to not have to know exactly what columns are in my record. That being the case, I want a way to list all ...
[ "This can be done by providing a metaclass to declarative_base\nand in that metaclass\nfrom sqlalchemy import Column, Integer\nfrom sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta\n\nclass MyMeta(DeclarativeMeta): \n\n def __init__(klass, classname, bases, dict_): \n\n for k, v in dict...
[ 1 ]
[]
[]
[ "metaclass", "python", "setattr", "sqlalchemy" ]
stackoverflow_0005734301_metaclass_python_setattr_sqlalchemy.txt
Q: Sending progress value to progress bar in python In my game I have two modules, island.py which loads the islands into my game and the second module is gui.py which handles the gui widgets before game starting. My problem is how to send the progress values from the island.py module to the progress bar created in g...
Sending progress value to progress bar in python
In my game I have two modules, island.py which loads the islands into my game and the second module is gui.py which handles the gui widgets before game starting. My problem is how to send the progress values from the island.py module to the progress bar created in gui.py module EDIT: also with an instance of the loadin...
[ "Expanding on rocksport's answer...this is how I did it\nclass GUI:\n def __init__(self):\n GUI.self = self\n\n\n @staticmethod\n def set_progressbar():\n print \"set progress bar\"\n print GUI.self\n\n\ng = GUI()\ng.set_progressbar()\n\n", "I would attack this a bit differently. I w...
[ 4, 3, 1 ]
[]
[]
[ "loading", "progress", "python", "user_interface" ]
stackoverflow_0005642500_loading_progress_python_user_interface.txt
Q: Help with understanding list function When I type the following into the interpreter I get the desired output behavior: >>> x = (7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6) >>> y = list(x) >>> y [7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6] Above, I simply converted a tuple to a list. However, when I run the following code I get ...
Help with understanding list function
When I type the following into the interpreter I get the desired output behavior: >>> x = (7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6) >>> y = list(x) >>> y [7, 2, 1, 1, 6, 2, 1, 2, 1, 2, 2, 6] Above, I simply converted a tuple to a list. However, when I run the following code I get an answer that I don't understand. pwm = in...
[ "When you call list on a string, it generates a list in which each character is an item in the list. So for example:\n>>> list(\"hey, you\")\n['h', 'e', 'y', ',', ' ', 'y', 'o', 'u']\n\nSince the data returned from input in this case is a string, calling list on it generates a list of characters.\nFor the sake of d...
[ 6, 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005736337_python.txt
Q: Django custom method won't show up I have two custom methods for a model manager in Django. One of them works. I recently added another and Django (and python) act like it doesn't exist. Here's the relevant part of the model: class FigureServerManager(models.Manager): #This method takes as input a user and ...
Django custom method won't show up
I have two custom methods for a model manager in Django. One of them works. I recently added another and Django (and python) act like it doesn't exist. Here's the relevant part of the model: class FigureServerManager(models.Manager): #This method takes as input a user and grabs a figure that is not marked comple...
[ "Python Language Reference, §2.1.8: \"Indentation\"\n" ]
[ 6 ]
[]
[]
[ "django", "django_models", "methods", "object", "python" ]
stackoverflow_0005736898_django_django_models_methods_object_python.txt
Q: De-greedifying a regular expression in python I'm trying to write a regular expression that will convert a full path filename to a short filename for a given filetype, minus the file extension. For example, I'm trying to get just the name of the .bar file from a string using re.search('/(.*?)\.bar$', '/def_params/...
De-greedifying a regular expression in python
I'm trying to write a regular expression that will convert a full path filename to a short filename for a given filetype, minus the file extension. For example, I'm trying to get just the name of the .bar file from a string using re.search('/(.*?)\.bar$', '/def_params/param_1M56/param/foo.bar') According to the Python...
[ "What you're missing isn't so much about greediness as about regular expression engines: they work from left to right, so the / matches as early as possible and the .*? is then forced to work from there. In this case, the best regex doesn't involve greediness at all (you need backtracking for that to work; it wil...
[ 8, 3, 0, 0, 0, 0 ]
[ "try this one on for size:\nmatch = re.search('.*/(.*?).bar$', '/def_params/param_1M56/param/foo.bar')\n" ]
[ -1 ]
[ "greedy", "non_greedy", "python", "regex" ]
stackoverflow_0005736294_greedy_non_greedy_python_regex.txt
Q: Python 2.6 automatically turns variables within a function definition global under certain circumstances? Why? I am absolutely dumbfounded by why the following is happening: Here is my code: def add_one(array): new_array = array length = len(array) for i in range(length): new_array[i] = new...
Python 2.6 automatically turns variables within a function definition global under certain circumstances? Why?
I am absolutely dumbfounded by why the following is happening: Here is my code: def add_one(array): new_array = array length = len(array) for i in range(length): new_array[i] = new_array[i]+1 return new_array x = [1,2,3,4,5]; y = add_one(x) print x print y Here are the results: [2, 3,...
[ "When you say new_array = array, you're not making a copy of the array, you're simply making another name for the array. Both names still apply to the same array.\nTo make a copy the simplest way is to use slicing: new_array = array[:]\n", "Nothing is made global for obscure readons. array is still a perfectly no...
[ 6, 4, 1, 0 ]
[]
[]
[ "debugging", "global_variables", "issue_tracking", "local_variables", "python" ]
stackoverflow_0005737082_debugging_global_variables_issue_tracking_local_variables_python.txt
Q: How do I replicate "from module import class" with __import__() or django.utils.importlib? I want to import a class from python module. The module contains multiple classes and which one I need is determined by a string at runtime. Edit: I'm using python 2.6.5, django 1.3. A: With judicious use of getattr()....
How do I replicate "from module import class" with __import__() or django.utils.importlib?
I want to import a class from python module. The module contains multiple classes and which one I need is determined by a string at runtime. Edit: I'm using python 2.6.5, django 1.3.
[ "With judicious use of getattr().\n", "MyClass = getattr(mymodule, myclass_name)\n\n", "Or import(module,globals(),locals(),['classname',],-1)\n" ]
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005734186_django_python.txt
Q: Working with complex numbers in real time with GNU Radio I need to work with data received from the USRP (using the gr-sounder to be specific), and I'm not exactly sure how I would do that. Are there any python packages I can use to work with the data, and more specifically, how would I use them. To be more specif...
Working with complex numbers in real time with GNU Radio
I need to work with data received from the USRP (using the gr-sounder to be specific), and I'm not exactly sure how I would do that. Are there any python packages I can use to work with the data, and more specifically, how would I use them. To be more specific, I need to calculate the error between vectors in real time...
[ "Python and Numpy have a variety of methods for reading data depending on the format. And of course numpy is built to deal with numerical operations on array data, real and complex.\nPlotting data could be accomplished using matplotlib:\nhttp://matplotlib.sourceforge.net/\nalthough there are other packages like May...
[ 1 ]
[]
[]
[ "gnuradio", "matplotlib", "numpy", "python", "telecommunication" ]
stackoverflow_0005736379_gnuradio_matplotlib_numpy_python_telecommunication.txt
Q: converting strings to numeric What's a simple way to convert stings into numerics: from: ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04'] to: [3.65e+03, 1.14e+04, 1.35e+04, 1.46e+04] Thanks. A: map(float, your_list) or [float(x) for x in your_list] Update For an explanation of why an unqualified recommendati...
converting strings to numeric
What's a simple way to convert stings into numerics: from: ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04'] to: [3.65e+03, 1.14e+04, 1.35e+04, 1.46e+04] Thanks.
[ "map(float, your_list)\n\nor\n[float(x) for x in your_list]\n\nUpdate For an explanation of why an unqualified recommendation to \"use decimal\" is not a good idea, see my answer to another question.\n", "First off, I hope you are aware of the limitations in representing the floating point accurately in our curre...
[ 4, 4 ]
[ "numbers = [eval(s) for s in ['3.65e+03', '1.14e+04', '1.35e+04', '1.46e+04']]\n\neval's a bit of a hack, but it's pretty well guaranteed to work. (specific float is also a good approach.)\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0005737188_python.txt
Q: SVN Integration with django I have a small bug tracker written in django. I'd like to integrate it with an svn repository so that when someone commits to svn it will automatically add a note to an issue in the bug tracker. Does anyone have any input on how to best approach this? Should I setup svn hooks? use a...
SVN Integration with django
I have a small bug tracker written in django. I'd like to integrate it with an svn repository so that when someone commits to svn it will automatically add a note to an issue in the bug tracker. Does anyone have any input on how to best approach this? Should I setup svn hooks? use a cron job and pull from the log?
[ "You can have a post-commit hook in the svn repo that uses, ideally, a restful interface to your Django app and adds the note. That way your app remains very simple.\n" ]
[ 6 ]
[]
[]
[ "django", "python", "svn" ]
stackoverflow_0005737483_django_python_svn.txt
Q: Object Oriented Python So in the interest of practicing Python and more specifically understanding object oriented programing I have written this simple script to better understand the concepts. However when I try to initiate a "monkeys" object what ends up happening is Python adds the name of my first monkey obje...
Object Oriented Python
So in the interest of practicing Python and more specifically understanding object oriented programing I have written this simple script to better understand the concepts. However when I try to initiate a "monkeys" object what ends up happening is Python adds the name of my first monkey object indefinitely... Am I appr...
[ "Assuming you initialise a Monkeys with a list of names, instead of\nself.allmonkeys[name] = monkey(name)\n\nI think you want\nself.monkeydict[name] = monkey(name)\n\n\nFYI the Python naming convention is that classes be uppercased. Also I don't think Monkeys is a descriptive name; Zoo might be better. Note also th...
[ 3, 1, 0 ]
[]
[]
[ "function", "oop", "python" ]
stackoverflow_0005737578_function_oop_python.txt
Q: How do I convert part of a python tuple (byte array) into an integer I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values: response = (0, 0, 117, 143, 6) The first 4 values are a 32-bit int tel...
How do I convert part of a python tuple (byte array) into an integer
I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values: response = (0, 0, 117, 143, 6) The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage...
[ "Would,\nnum = (response[0] << 24) + (response[1] << 16) + (response[2] << 8) + response[3]\n\nmeet your needs?\naid\n", "See Convert Bytes to Floating Point Numbers in Python \nYou probably want to use the struct module, e.g.\nimport struct\n\nresponse = (0, 0, 117, 143, 6)\nstruct.unpack(\">I\", ''.join([chr(x)...
[ 13, 11, 4, 4, 2, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0000386753_python_tuples.txt
Q: Python LXML iterparse with nested elements I would like to retrieve the content of a specific element within an XML file. However, within the XML element, there are other XML elements, which destroy the proper extraction of the content within the parent tag. An example: xml = '''<?xml version='1.0' ?><test><claim-...
Python LXML iterparse with nested elements
I would like to retrieve the content of a specific element within an XML file. However, within the XML element, there are other XML elements, which destroy the proper extraction of the content within the parent tag. An example: xml = '''<?xml version='1.0' ?><test><claim-text><b>2</b>. A protective uniform for use by a...
[ "You could use an xpath to find and concatenate all the text nodes directly under each <claim-text> node, like this: \nfrom StringIO import StringIO\nfrom lxml import etree\nxml = '''<?xml version='1.0' ?><test><claim-text><b>2</b>. A protective uniform for use by a person in combat or law enforcement, said uniform...
[ 3 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0005732291_lxml_python_xml.txt
Q: How do the PIL ImageFilter enhancement filters work? Where can I find information on what algorithms the PIL ImageFilter functions use? Like how does edge_enhance work? I'm looking to implement a difference of Gaussians filter but if PIL has a filter that works similarly I'll use that. A: The ImageFilter methods...
How do the PIL ImageFilter enhancement filters work?
Where can I find information on what algorithms the PIL ImageFilter functions use? Like how does edge_enhance work? I'm looking to implement a difference of Gaussians filter but if PIL has a filter that works similarly I'll use that.
[ "The ImageFilter methods all use kernels convolved with an image to produce the filter effects. Here is good primer on kernel convolution. If you load the ImageFilter module you can figure out the kernels used for each kind of operation by looking at \n>>> help(ImageFilter)\n\nFor example, for EDGE_ENHANCE_MORE hel...
[ 2 ]
[]
[]
[ "imagefilter", "python", "python_imaging_library" ]
stackoverflow_0003346980_imagefilter_python_python_imaging_library.txt
Q: Writing a script for fetching the specific part of a web page in a loop for offline use I have a specific use. I am preparing for GRE. Everytime a new word comes, I look it up at www.mnemonicdictionary.com, for its meanings and mnemonics. I want to write a script in python preferably ( or if someone could provide ...
Writing a script for fetching the specific part of a web page in a loop for offline use
I have a specific use. I am preparing for GRE. Everytime a new word comes, I look it up at www.mnemonicdictionary.com, for its meanings and mnemonics. I want to write a script in python preferably ( or if someone could provide me a pointer to an already existing thing as I dont know python much but I am learning now) w...
[ "If you have Bash (version 4+) and wget, an example\n#!/bin/bash\ntemplate=\"http://www.mnemonicdictionary.com/include/ajaxSearch.php?word=%s&event=search\"\nwhile read -r word\ndo\n url=$(printf \"$template\" \"$word\")\n data=$(wget -O- -q \"$url\")\n data=${data#*&nbsp;}\n echo \"$word: ${data%%<*}\"...
[ 3, 1 ]
[]
[]
[ "offline_browsing", "python", "scripting" ]
stackoverflow_0005738339_offline_browsing_python_scripting.txt
Q: How to Parse Java-script contains[dynamic] on web-page[html] using Python? I am building a spider and I am using Beautiful soup to parse the contain of particular URL. Now, some sites are using Java-script to show dynamic contain which will be shown to user once some action [clicking or time] happens. Beautiful ...
How to Parse Java-script contains[dynamic] on web-page[html] using Python?
I am building a spider and I am using Beautiful soup to parse the contain of particular URL. Now, some sites are using Java-script to show dynamic contain which will be shown to user once some action [clicking or time] happens. Beautiful soup just parse the static contain which is before the java-script tag has run. ...
[ "Your best bet for accurately parsing Javascript-enhanced content from web pages is to load the page via a browser engine. Luckily there are ways to automate this in Python.\nThe method I've had the most success with is to use the pywebkitgtk project which lets you programmatically create and control instances of t...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "web_crawler" ]
stackoverflow_0005738024_beautifulsoup_python_web_crawler.txt
Q: How do I handle the following situation in Python? I want to say a[current] = value rather than saying a.append(value) because I want to show that the current value is value. The former listing shows this better. I come from C, so I am a bit confused with python lists. In C I preallocate space, so a[current] w...
How do I handle the following situation in Python?
I want to say a[current] = value rather than saying a.append(value) because I want to show that the current value is value. The former listing shows this better. I come from C, so I am a bit confused with python lists. In C I preallocate space, so a[current] would exist and contain junk before I assign it value. Ca...
[ "You can do something like\n[0] * 10\n\nwhich will result in \n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nBut your approach will probably not be very \"pythonic\". If switching to Python, you should also think about thinking in python. ;-)\n", "You can allocate a list of length n by using\nmy_list = [None] * n\n\nObviousl...
[ 5, 1, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0005736531_c_python.txt
Q: Mini Iterable Model Mapper for google app engine python I don't think what I want exists. Can anyone create for me a barebones mini mapper class? Detailed pseudo-code or actual python is fine. Update: Simple, working version at bottom of post. Update 2 - June 20: safer execution: continue/break/return within iter...
Mini Iterable Model Mapper for google app engine python
I don't think what I want exists. Can anyone create for me a barebones mini mapper class? Detailed pseudo-code or actual python is fine. Update: Simple, working version at bottom of post. Update 2 - June 20: safer execution: continue/break/return within iterall() works now. added defer_db flag for sending db puts and ...
[ "Why don't you want to use Mapreduce? It's designed for exactly this use-case, already does everything you want, and can be invoked programmatically. 'Lightweight' is a very vague term, but I'm not aware of any reason that the mapreduce library doesn't suit your task exactly - and there's very little reason to dupl...
[ 1 ]
[]
[]
[ "google_app_engine", "mapreduce", "python" ]
stackoverflow_0005737796_google_app_engine_mapreduce_python.txt
Q: How to get rid of forward slash in Python raw_input() Beginner programmer here. So bear with me. I have a simple python program. print "How tall are you?", height = raw_input() print "So you're %r tall" %(height) If I enter the height as 6'6'' python would output So you're '6\6"' How do I get rid of the forward ...
How to get rid of forward slash in Python raw_input()
Beginner programmer here. So bear with me. I have a simple python program. print "How tall are you?", height = raw_input() print "So you're %r tall" %(height) If I enter the height as 6'6'' python would output So you're '6\6"' How do I get rid of the forward slash "\" from the output? Thanks in advance!
[ "%r converts to the repr of height, you should use %s instead\nIf you are using Python >=2.6, you can write it this way instead\nprint \"So you're {height} tall.\".format(height=height)\n\n" ]
[ 7 ]
[]
[]
[ "forward", "python", "raw_input", "slash" ]
stackoverflow_0005738965_forward_python_raw_input_slash.txt
Q: Twitter API libraries for desktop apps? I'm looking for a way to fetch recent posts from twitter. Really I just want to be able to grab and store new posts about a certain topic from twitter in a text file. Are there any current programs or libraries which do this (prefrably C++, although python is ok too)? What w...
Twitter API libraries for desktop apps?
I'm looking for a way to fetch recent posts from twitter. Really I just want to be able to grab and store new posts about a certain topic from twitter in a text file. Are there any current programs or libraries which do this (prefrably C++, although python is ok too)? What would people suggest?
[ "you can check the API docs here, some of the projects that are listed there:\nC++\nQTweetLib - C++ Qt based Twitter library\nQTwitLib by Bradley Lackey & Maks Zolin. C++ library for Linux, Windows, and Mac. Currently in beta. Unmaintained since 2009.\nTwitcurl by Mahesh. C++ library which uses curl library for HTT...
[ 5 ]
[]
[]
[ "api", "c++", "python", "twitter" ]
stackoverflow_0005739006_api_c++_python_twitter.txt
Q: Do I have a threading issue here? I have been experimenting with GNU Radio and came across the tunnel.py program. This program allows you to tunnel IP traffic over a wireless radio link using Linux TUN/TAP devices. For the most part it is working however one part of the code is confusing me. There is a class which...
Do I have a threading issue here?
I have been experimenting with GNU Radio and came across the tunnel.py program. This program allows you to tunnel IP traffic over a wireless radio link using Linux TUN/TAP devices. For the most part it is working however one part of the code is confusing me. There is a class which implements a 'basic MAC layer'. This c...
[ "\nThe function main_loop does a carrier sense before transmitting a new packet. The thing I don't understand is why it is sensing a receive channel before transmitting on a separate non-overlapping transmit channel.\n\nThe CSMA/CA is intended to be used with half-duplex systems, where all nodes use the same freque...
[ 0 ]
[]
[]
[ "gnuradio", "multithreading", "python" ]
stackoverflow_0005650776_gnuradio_multithreading_python.txt
Q: How can i make this code run smoothly on google app engine? i'm new to web apps so i'm not so used to worrying about CPU limits, but i looks i am going to have a problem with this code. I read in google's quotas page that i can use 6.5 CPU hours per day an 15 CPU , minutes per minute. Google Said: CPU time is rep...
How can i make this code run smoothly on google app engine?
i'm new to web apps so i'm not so used to worrying about CPU limits, but i looks i am going to have a problem with this code. I read in google's quotas page that i can use 6.5 CPU hours per day an 15 CPU , minutes per minute. Google Said: CPU time is reported in "seconds," which is equivalent to the number of CPU cycl...
[ "I don't like to optimize until I need to. First, just try it. It might just work. If you go over quota, shrug, come back tomorrow.\nTo split jobs into smaller parts, look at the Task Queue API. Maybe you can divide the workload into two queues, one that scrapes pages and one that processes them. You can put l...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005711393_google_app_engine_python.txt