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: Why do I get a "IndexError: list index out of range"? (Beautiful Soup) I am trying to scrape a table here very similar in structure to my previous question. I just changed the attributes names but I am getting index out of range error. This is the TR: <TR VALIGN="bottom"> <TD BGCOLOR=#cc6600 ALIGN="center" ><FONT ...
Why do I get a "IndexError: list index out of range"? (Beautiful Soup)
I am trying to scrape a table here very similar in structure to my previous question. I just changed the attributes names but I am getting index out of range error. This is the TR: <TR VALIGN="bottom"> <TD BGCOLOR=#cc6600 ALIGN="center" ><FONT FACE="Verdana, Arial, Helvetica, sans-serif">1</FONT></TD> <TD BGCOLOR=#CC66...
[ "I modified how you are getting the last \"center\" td in the following code:\nimport urllib\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(urllib.urlopen(\"http://www.law.com/special/professionals/amlaw/amlaw200/amlaw200_ppp.html\"))\nrows = soup.findAll(name='tr',attrs={'valign':'bottom'}, limit=1...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping", "web_scraping" ]
stackoverflow_0007641777_beautifulsoup_python_screen_scraping_web_scraping.txt
Q: How do you create a "go back to this point" code in Python? I'm new to coding with python and did not know what header to search up my problem in python. My question is: How do you create a go back to this point command? You know, like in menus where you open a tab and don't want to be there, so you press Back. Al...
How do you create a "go back to this point" code in Python?
I'm new to coding with python and did not know what header to search up my problem in python. My question is: How do you create a go back to this point command? You know, like in menus where you open a tab and don't want to be there, so you press Back. Also, whenever I search it up I always find questions or explanatio...
[ "\"Flow control\" might be a good thing to search on. As you learn the Python vernacular you'll see that you can do everything you need to without the goto type command you're reaching for. Depending on what you're trying to do, you might want to use a looping construct like for or while. Or you might write a reusa...
[ 4, 1 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0007641916_python_user_interface.txt
Q: Python observable implementation that supports multi-channel subscribers In a twisted application I have a series of resource controller/manager classes that interact via the Observable pattern. Generally most observers will subscribe to a specific channel (ex. "foo.bar.entity2") but there are a few cases where I...
Python observable implementation that supports multi-channel subscribers
In a twisted application I have a series of resource controller/manager classes that interact via the Observable pattern. Generally most observers will subscribe to a specific channel (ex. "foo.bar.entity2") but there are a few cases where I'd like to know about all event in a specific channel (ex. "foo.*" ) so I wrot...
[ "This looks like you are on the right track to me. I was using PyPubSub with a wxPython app for a bit, and then ended up implementing my own \"more simple\" version that, at its root, looks very similar to what you've done here except with a few more bells and whistles that you'd probably end up implementing as you...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007638760_python.txt
Q: how to copy a file between 2 computers on the network in python I am trying to move a log file from a computer, where an operation is performed, to another computer, that will get the log file and process it, returning a document with the result of the analysis. I am using Python for the job, but I am open to othe...
how to copy a file between 2 computers on the network in python
I am trying to move a log file from a computer, where an operation is performed, to another computer, that will get the log file and process it, returning a document with the result of the analysis. I am using Python for the job, but I am open to other options (I have to run this copy via console on OSX, due the fact t...
[ "I use this all the time at home so I don't have to keep file sharing daemons running constantly:\npython -m SimpleHTTPServer\n\nOn the client machine, use a browser or wget.\nIn fact I use it so often I made this script that prints the IP Address also, named serv. Feel free to hack it into your needs. Just cd to ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007641481_python.txt
Q: Python equivalent of ActionScript's apply()/call() methods? I'm writing a pretty simple function for use in my Django project to display a number of pages only if the application is in debug mode. In AS3, you can essentially apply a methods parameters to another methods using that method's call or apply method. Le...
Python equivalent of ActionScript's apply()/call() methods?
I'm writing a pretty simple function for use in my Django project to display a number of pages only if the application is in debug mode. In AS3, you can essentially apply a methods parameters to another methods using that method's call or apply method. Let me demonstrate: public function secureCall(...arguments):void {...
[ "When defining a function, you can use this notation:\ndef takes_any_args(*args, **kwargs):\n pass\n\nargs will be a tuple of positional arguments,\nkwargs a dict of keyword arguments\nYou can then call another function with these arguments like this:\nsome_function(*args, **kwargs)\n\nYou can omit either of the...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007642226_python.txt
Q: Issues with Python socket module So I'm working on a Python IRC framework, and I'm using Python's socket module. Do I feel like using Twisted? No, not really. Anyway, I have an infinite loop reading and processing data from socket.recv(xxxx), where xxxx is really irrelevant in this situation. I split the receiv...
Issues with Python socket module
So I'm working on a Python IRC framework, and I'm using Python's socket module. Do I feel like using Twisted? No, not really. Anyway, I have an infinite loop reading and processing data from socket.recv(xxxx), where xxxx is really irrelevant in this situation. I split the received data into messages using str.split(...
[ "You should really be using select or poll, e.g. via asyncore or select, or twisted (which you prefer not to).\nReading from a socket you never know how much you'll receive in each read. You could receive several messages in one go, or have one message split into many reads. You should always collect the data in a ...
[ 4, 0 ]
[]
[]
[ "irc", "python", "sockets" ]
stackoverflow_0007642309_irc_python_sockets.txt
Q: Regex match in google app engine webapp WSGIApplication Hi A rather simple question: application = webapp.WSGIApplication([ ('/result', Result), ('/result/', Result), The only difference is the trailing '/'. Can I merge the two url mapping into one? A: For SEO reasons, it is usually better to choose one URL to...
Regex match in google app engine webapp WSGIApplication
Hi A rather simple question: application = webapp.WSGIApplication([ ('/result', Result), ('/result/', Result), The only difference is the trailing '/'. Can I merge the two url mapping into one?
[ "For SEO reasons, it is usually better to choose one URL to handle, and redirect the other to the chosen one. Otherwise search engines will see duplicate content. For example something like this:\nclass RedirectHandler(webapp.RequestHandler):\n def get(self):\n self.redirect(\"/result/\", True)\n\napplica...
[ 2, 1 ]
[ "by default the google app engine will recognize /result/ same as /result so you can just go with\napplication = webapp.WSGIApplication([\n('/result', Result),\n\nyou can as well make regular expressions for links such as\napplication = webapp.WSGIApplication([\n('/block/([0-9]+)/permissions', Result),\n\n" ]
[ -1 ]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0007628187_google_app_engine_python_web_applications.txt
Q: Elegant way to remove contiguous repeated elements in a list I'm looking for a clean, Pythonic, way to eliminate from the following list: li = [0, 1, 2, 3, 3, 4, 3, 2, 2, 2, 1, 0, 0] all contiguous repeated elements (runs longer than one number) so as to obtain: re = [0, 1, 2, 4, 3, 1] but although I have workin...
Elegant way to remove contiguous repeated elements in a list
I'm looking for a clean, Pythonic, way to eliminate from the following list: li = [0, 1, 2, 3, 3, 4, 3, 2, 2, 2, 1, 0, 0] all contiguous repeated elements (runs longer than one number) so as to obtain: re = [0, 1, 2, 4, 3, 1] but although I have working code, it feels un-Pythonic and I am quite sure there must be a w...
[ "Here is a version based on Karl's answer which doesn't requires copies of the list (tmp, the slices, and the zipped list). izip is significantly faster than (Python 2) zip for large lists. chain is slightly slower than slicing but doesn't require a tmp object or copies of the list. islice plus making a tmp is a bi...
[ 8, 4, 1, 1 ]
[]
[]
[ "idioms", "list", "python", "python_2.x" ]
stackoverflow_0007641955_idioms_list_python_python_2.x.txt
Q: Matching every word in a txt file I'm working on a Project Euler problem (for fun). It comes with a 46kb txt file containing 1 line with a list of over 5000 names in the format like this: "MARIA","SUSAN","ANGELA","JACK"... My plan is to write a method to extract every name and append them into a Python list. Is r...
Matching every word in a txt file
I'm working on a Project Euler problem (for fun). It comes with a 46kb txt file containing 1 line with a list of over 5000 names in the format like this: "MARIA","SUSAN","ANGELA","JACK"... My plan is to write a method to extract every name and append them into a Python list. Is regular expression the best weapon to ta...
[ "That looks like a format that the csv module would be helpful with. Then you wouldn't have to write any regex.\n", "If the format of the file is as you say it is, i.e.\n\nIt's a single line\nThe format is like this: \"MARIA\",\"SUSAN\",\"ANGELA\",\"JACK\"\n\nThen this should work:\n\n>>> import csv\n>>> lines = ...
[ 3, 3, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007642337_python_regex.txt
Q: Twitter Feed Reader I just read this gizmodo article about converting a label printer into a hashtag checker/printer. http://www.lifehacker.com.au/2011/10/hack-a-label-printer-into-a-twitter-hashtag-ticker/ While the hardware is cool, I'd like to understand the Twitter API. How would I do the same for tweets from ...
Twitter Feed Reader
I just read this gizmodo article about converting a label printer into a hashtag checker/printer. http://www.lifehacker.com.au/2011/10/hack-a-label-printer-into-a-twitter-hashtag-ticker/ While the hardware is cool, I'd like to understand the Twitter API. How would I do the same for tweets from a user, and using Python?...
[ "May I suggest you start by reading one of the many python twitter libraries. I have used the following one before http://code.google.com/p/python-twitter/\nAfter that you just need a thread and a timer. \n", "The Twitter developer documentation is quite comprehensive and good.\n" ]
[ 0, 0 ]
[]
[]
[ "api", "hashtag", "python", "twitter" ]
stackoverflow_0007642576_api_hashtag_python_twitter.txt
Q: In wxpython is there a wx.CallDuring I found wx.CallAfter and wx.CallLater in the documentation but neither solves my problem. What I'm trying to do is update a status bar while doing a task, but both wx.CallAfter and wx.CallLater only updates after task. Example: #!/usr/bin/env python # -*- coding: utf-8 -*- # ge...
In wxpython is there a wx.CallDuring
I found wx.CallAfter and wx.CallLater in the documentation but neither solves my problem. What I'm trying to do is update a status bar while doing a task, but both wx.CallAfter and wx.CallLater only updates after task. Example: #!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Fri Sep 30 20:...
[ "From the sound of it, \"CallDuring\" is nothing more than simply calling whatever function you want. It will get called exactly when you call it. Is there a reason why calling it directly doesn't solve your problem?\nHowever, you're telling your program to sleep. No amount of \"call during\" will help you since yo...
[ 3 ]
[]
[]
[ "call", "events", "python", "user_interface", "wxpython" ]
stackoverflow_0007617414_call_events_python_user_interface_wxpython.txt
Q: How can I get more detail on why a fixture is not loading? I have a TestCase that doesn't seem to load the fixtures. I'm seeing this error as the test database is being built: No fixtures found. .............................................Problem installing fixture '/Users/Bryan/work/CNPROG/forum/fixtures/forum...
How can I get more detail on why a fixture is not loading?
I have a TestCase that doesn't seem to load the fixtures. I'm seeing this error as the test database is being built: No fixtures found. .............................................Problem installing fixture '/Users/Bryan/work/CNPROG/forum/fixtures/forum_fixtures.json': Traceback (most recent call last): File "/L...
[ "Run tests with greater detail with this command:\npython manage.py test --verbosity=2\nI fixed this by rearranging the order of the fixtures. \nIf you have Related objects, you need to make sure the objects that have the most associations ( e.g. auth_user ) is listed first in the fixture because the related object...
[ 1, 0, 0 ]
[]
[]
[ "django_testing", "python" ]
stackoverflow_0002908795_django_testing_python.txt
Q: PyQt4 Application Launch Alright, so I have two applications that won't launch now, a important one and a test one, the test one used to run, but now it is saying: AttributeError: 'StartQt4' object has no attribute 'filename' So, I have no idea why that is happening, and that only happens when I try to use either ...
PyQt4 Application Launch
Alright, so I have two applications that won't launch now, a important one and a test one, the test one used to run, but now it is saying: AttributeError: 'StartQt4' object has no attribute 'filename' So, I have no idea why that is happening, and that only happens when I try to use either the save feature or open featu...
[ "What did you change between it working and not working?\nFor the test code without knowing what the Ui_LQNotepad class does it's hard to say, but QMainWindow objects don't have a filename attribute so your code as given will never have worked. I suspect you may mean self.ui.filename but I can't say for certain tha...
[ 0, 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0007632537_pyqt4_python.txt
Q: Long (and failing) bulk data loads to Google App Engine datastore I'm developing an application on Google App Engine using the current django non-rel and the now default, high replication datastore. I'm currently trying to bulk load a 180MB csv file locally on a dev instance with the following command: appcfg.py ...
Long (and failing) bulk data loads to Google App Engine datastore
I'm developing an application on Google App Engine using the current django non-rel and the now default, high replication datastore. I'm currently trying to bulk load a 180MB csv file locally on a dev instance with the following command: appcfg.py upload_data --config_file=bulkloader.yaml --filename=../my_data.csv --k...
[ "180MB is a lot of data to load into the dev_appserver - it's not designed for large (or even medium) datasets; it's built entirely for small-scale local testing. Your best bet would be to reduce the size of your test dataset; if you can't do that, try the --use_sqlite command line flag to use the new sqlite-based ...
[ 2 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0007642729_bulkloader_google_app_engine_python.txt
Q: Python inheritance woes This is a homework question, but as you can see I've written most of the code already. :) What I'm trying to have happen is that the Agent object inherits the methods from the Investor object, as the Agent object's methods are suppose to be basically the same. The only different is the con...
Python inheritance woes
This is a homework question, but as you can see I've written most of the code already. :) What I'm trying to have happen is that the Agent object inherits the methods from the Investor object, as the Agent object's methods are suppose to be basically the same. The only different is the constructors, Investor takes 6 p...
[ "There is a lot going on here, so I'll try to be brief.\nclass Investor(object):\n reports = []\n data = []\n\n def __init__(self, LastName, FirstName, Date, Gender, Title, Rid=1):\n # the following two lines define variables which only exist inside\n # __init__, so they can basically be gott...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007642683_python.txt
Q: What are the differences between swap in C++ and Python? About swap, in C++, we can swap two by std::swap(x, y);. x and y are passed into swap as reference. But in Python, can we also write a swap function which can do the swap the same way as in C++? The Python version of swap I implemented is kinda stupid: def s...
What are the differences between swap in C++ and Python?
About swap, in C++, we can swap two by std::swap(x, y);. x and y are passed into swap as reference. But in Python, can we also write a swap function which can do the swap the same way as in C++? The Python version of swap I implemented is kinda stupid: def swap_in_python(x, y): return y, x #so when swapping a and ...
[ "Actually, in Python, it's much more elegant:\n(a,b) = (b,a)\n\nYou don't have to call a function at all. And, yes, as per the comments, the parentheses are unnecessary here. I still prefer them since I believe they make the intent clearer.\n\nFollowing edit:\n\nIs there any other way not employing assignment (not ...
[ 5, 2, 1, 1 ]
[]
[]
[ "python", "swap" ]
stackoverflow_0007642909_python_swap.txt
Q: Adding extra state to itertools.product I have taken a look at itertools.permutations and combinations, but I don't think they will work for my issue. Basically, I am looking to create a list of all possible permutations of a given string with a defined length (greater than the amount of elements). Basically, I wo...
Adding extra state to itertools.product
I have taken a look at itertools.permutations and combinations, but I don't think they will work for my issue. Basically, I am looking to create a list of all possible permutations of a given string with a defined length (greater than the amount of elements). Basically, I would like to have three possible states, 0, 1,...
[ "Works for me:\n>>> import itertools\n>>> s = list(itertools.product(('0','1','*'), repeat=8))\n>>> len(s)\n6561\n\nSee it working online: ideone.\n" ]
[ 0 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0007643345_python_python_itertools.txt
Q: isDigit() for rational numbers? I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another wa...
isDigit() for rational numbers?
I am trying to evaluate if the string in one of the textbox of my interface is a number (i.e. not text or anything else). In Python, there is a method called isdigit() that will return True if the string only contains digits (no negative signs or decimal points). Is there another way I could evaluate if my string is a ...
[ "1.25 is a notation commonly used for reals, less so for rational numbers. Python's float will raise a ValueError when conversion fails. Thus:\ndef isReal(txt):\n try:\n float(txt)\n return True\n except ValueError:\n return False\n\n", "try/catch is very cheap in Python, and attempting...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000888925_python_string.txt
Q: Django Site encryption I am writing a site for which I require all data to be transmitted under encryption. Last night I was considering encrypting form data before posting it but I've just created a Django form for login and realised that using the action field will send the data back to the server unencrypted. ...
Django Site encryption
I am writing a site for which I require all data to be transmitted under encryption. Last night I was considering encrypting form data before posting it but I've just created a Django form for login and realised that using the action field will send the data back to the server unencrypted. <form method="post" action="...
[ "Encryption in JavaScript is useless as explained here. So SSL is your only option. \n", "I've found some information here if you plan to deploy your site with https:\nhttp://www.redrobotstudios.com/blog/2009/02/18/securing-django-with-ssl/\n" ]
[ 6, 1 ]
[]
[]
[ "django", "python", "ssl" ]
stackoverflow_0007643941_django_python_ssl.txt
Q: Modify the width of a tab in a format string Is it possible to redefine the space width of a tab when printing a \t character in python? A: Try pydoc string.expandtabs, I think it will do what you want. A: Python's print feature does not convert tabs to spaces - it outputs a literal tab. The way it appears dep...
Modify the width of a tab in a format string
Is it possible to redefine the space width of a tab when printing a \t character in python?
[ "Try pydoc string.expandtabs, I think it will do what you want.\n", "Python's print feature does not convert tabs to spaces - it outputs a literal tab. The way it appears depends on what program you use to view it.\n" ]
[ 21, 8 ]
[]
[]
[ "python" ]
stackoverflow_0007643579_python.txt
Q: facebook app invite notification won't go away even though delete comes back ok I have a facebook app and have it working far enough that users can invite friends, but I can't seem to delete the notifications. I'm in python, on Django, using urllib to issue the delete request thusly: conn = httplib.HTTPSConnection...
facebook app invite notification won't go away even though delete comes back ok
I have a facebook app and have it working far enough that users can invite friends, but I can't seem to delete the notifications. I'm in python, on Django, using urllib to issue the delete request thusly: conn = httplib.HTTPSConnection('graph.facebook.com') user = request.facebook.user t = urllib.quote(user.oauth_token...
[ "You should notice that the request_id returned by FB sometimes has many IDs. For example, if 2 or more friends invite you to use an application, Facebook may join those request_id to one string. The request_id params may have the format \"A_FacebookId,B_FacebookId\".\nYou must split the parameters to retrieves the...
[ 0 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "python", "urllib" ]
stackoverflow_0007642801_django_facebook_facebook_graph_api_python_urllib.txt
Q: X.509 libraries I'm looking for a library/module/package with which I could create and sign X.509 certificates, with the ability to conditionally add custom v3 extensions – which can be fairly complicated; for example, this bletchful OpenSSL.cnf snippet used by Kerberos PKINIT, just to represent foo@EXAMPLE.ORG: ...
X.509 libraries
I'm looking for a library/module/package with which I could create and sign X.509 certificates, with the ability to conditionally add custom v3 extensions – which can be fairly complicated; for example, this bletchful OpenSSL.cnf snippet used by Kerberos PKINIT, just to represent foo@EXAMPLE.ORG: [v3_extensions] s...
[ "As it turns out, I added exactly this information to the documentation for Ruby 1.9.3, which was just published today by James Britt - have a look at the documentation for OpenSSL::X509::Certificate, it should answer all your questions. \nModifying the examples there to generate the particular extensions listed in...
[ 5, 2, 1 ]
[]
[]
[ "c#", "perl", "python", "ruby", "x509" ]
stackoverflow_0007639483_c#_perl_python_ruby_x509.txt
Q: Python - Check Words not in Files in Folder I'm formulating a script to check if a certain word is in a path or not. The problem I'm facing is that I can't seem to get a specific result without individual files results. Example: path = "/opt/webserver/logs/" file1.txt file2.txt file3.txt .... ... .. file10000.txt...
Python - Check Words not in Files in Folder
I'm formulating a script to check if a certain word is in a path or not. The problem I'm facing is that I can't seem to get a specific result without individual files results. Example: path = "/opt/webserver/logs/" file1.txt file2.txt file3.txt .... ... .. file10000.txt Code below: #checkWordinFiles.py import os wor...
[ "The conceptual problem is that os.listdir produces a list of names of files in the directory; therefore, you are searching for the words within the file name, not the file contents. To fix this, you will need to use the file name to open and read the file.\nThe show-offy way:\nimport os\n\ndef contents(filename):\...
[ 1, 0 ]
[ "Here's how you could do it:\nfor word in words:\n word_found = False\n for infile in files:\n if word in infile:\n word_found = True\n break\n if not word_found:\n print \"%s not in any file\" % word\n\n", "#checkWordinFiles.py\nimport os\n\nwords = [ \"Apple\", \"Ora...
[ -1, -1 ]
[ "file", "find", "python" ]
stackoverflow_0007644184_file_find_python.txt
Q: Installing NumPy on Snow Leopard (10.6) with XCode 4 installed I can't seem to install NumPy to System Python now that I've upgraded to Xcode 4. When I try to do: easy_install -U numpy I get: File "/private/tmp/easy_install-xoqh9U/numpy-1.6.1/numpy/core/setup.py", line 696, in get_mathlib_info RuntimeError: Broke...
Installing NumPy on Snow Leopard (10.6) with XCode 4 installed
I can't seem to install NumPy to System Python now that I've upgraded to Xcode 4. When I try to do: easy_install -U numpy I get: File "/private/tmp/easy_install-xoqh9U/numpy-1.6.1/numpy/core/setup.py", line 696, in get_mathlib_info RuntimeError: Broken toolchain: cannot link a simple C program I'd like to use System ...
[ "you have download tar.gz file from the site unzip it and then move that folder to any of the pythonpath\nwhich you can get by typing \nsys.path\n" ]
[ 0 ]
[]
[]
[ "macos", "numpy", "osx_snow_leopard", "python", "xcode4" ]
stackoverflow_0007344059_macos_numpy_osx_snow_leopard_python_xcode4.txt
Q: Changing the font color of a accompanying text item in a CheckListCtrl? How do I change the font color of a selected item in a CheckListCtrl ? For a selected item I would like the change the color of text in the accompanying text of the selected item ? class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtr...
Changing the font color of a accompanying text item in a CheckListCtrl?
How do I change the font color of a selected item in a CheckListCtrl ? For a selected item I would like the change the color of text in the accompanying text of the selected item ? class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin, ListCtrlAutoWidthMixin): def __init__(self, parent): wx.ListCtrl._...
[ "Maybe you need this:\nself.list.SetItemTextColour(index, colour)\n\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007643945_python_wxpython.txt
Q: Getting ActivePython to work with WSH I've installed ActivePython 2.7.2 and I'm trying to execute a .pys script via the console with wscript/cscript, [i.e. ActivePython (PythonScript with .pys extension) in Microsoft's WSH(Windows Scripting Host)] and when trying with wscript I get two errors. "The program can...
Getting ActivePython to work with WSH
I've installed ActivePython 2.7.2 and I'm trying to execute a .pys script via the console with wscript/cscript, [i.e. ActivePython (PythonScript with .pys extension) in Microsoft's WSH(Windows Scripting Host)] and when trying with wscript I get two errors. "The program cannot start because MSVCR90.dll is missing fr...
[ "To fix this:\n\nInstall Python for Windows Extensions (PyWin32)\nRegister python, C:\\YourPythonVersion\\Lib\\site-packages\\win32comext\\axscript\\client\\pyscript.py\n\n" ]
[ 8 ]
[]
[]
[ "activepython", "python", "pywin32", "wsh" ]
stackoverflow_0007637210_activepython_python_pywin32_wsh.txt
Q: access list from query result on django(python) DB table select * from AAA; id | name | grade -------------------- 1 | john | A 2 | cavin | B django grade_list = AAA.objects.all() for item in grade_list: print item.name result -> john cavin ============================================ I want to chan...
access list from query result on django(python)
DB table select * from AAA; id | name | grade -------------------- 1 | john | A 2 | cavin | B django grade_list = AAA.objects.all() for item in grade_list: print item.name result -> john cavin ============================================ I want to change this code(same function) grade_list = AAA.objects....
[ "Yes you can do this with the getattr built-in function.\ngrade_list = AAA.objects.all()\nprint_field = 'name'\n\nfor item in grade_list:\n print getattr(item, print_field)\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007645149_django_python.txt
Q: Django form field label translations I have a baseform with over 20 fields. Then I have about 15 other forms inheriting from that form, passing in a parameter called fields which the baseform uses to delete all other fields. Best explain via example: class BaseForm(forms.Form): reportid = forms.HiddenInput() ...
Django form field label translations
I have a baseform with over 20 fields. Then I have about 15 other forms inheriting from that form, passing in a parameter called fields which the baseform uses to delete all other fields. Best explain via example: class BaseForm(forms.Form): reportid = forms.HiddenInput() fromdate = forms.DateField(label=_("Fro...
[ "Django provides _lazy variants of the translation functions (for example ugettext_lazy) so you can ark strings for translations at the access time (as opposed to when the translation function is called).\nIt's documented in details at https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#lazy-translation\...
[ 15 ]
[]
[]
[ "django", "django_forms", "internationalization", "python" ]
stackoverflow_0007595965_django_django_forms_internationalization_python.txt
Q: How to do atomic file replacement? What's the recommended way to replace a file atomically in Python? i.e. if the Python script is interrupted, there is a power outage etc. files do not have a high probability of ending up in an inconsistent state (half written to the disk). A solution for Linux/UNIX platforms is ...
How to do atomic file replacement?
What's the recommended way to replace a file atomically in Python? i.e. if the Python script is interrupted, there is a power outage etc. files do not have a high probability of ending up in an inconsistent state (half written to the disk). A solution for Linux/UNIX platforms is preferred. (I know getting 100% atomic o...
[ "Create a new file and os.rename() it over the existing file. This is atomic on most platforms under most conditions.\n" ]
[ 15 ]
[]
[]
[ "atomic", "filesystems", "fwrite", "python", "rename" ]
stackoverflow_0007645338_atomic_filesystems_fwrite_python_rename.txt
Q: How to call a function stored in another file from a Python program? If I have a text file that contains a python function definition, how can I make the function call from another Python program. Ps: The function will be defined in the Python program that does the call. Ways in which can be done: Consider the p...
How to call a function stored in another file from a Python program?
If I have a text file that contains a python function definition, how can I make the function call from another Python program. Ps: The function will be defined in the Python program that does the call. Ways in which can be done: Consider the python function as a module and call it. Constraint here is that I have to ...
[ "You are looking for the exec keyword.\n>>> mycode = 'print \"hello world\"'\n>>> exec mycode\nHello world\n\nSo if you read your text file as text (assuming that it only contains the function) like:\ntest.txt:\ndef a():\n print \"a()\"\n\ntest.py:\nmycode = open('test.txt').read()\nexec mycode # this will execu...
[ 5, 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007644657_python.txt
Q: loading picture for django templates via css I have such folder structure in my django site theme: index file load the style.css and the style.css should load my bg.jpg,I do this in style.css: body { background:#fff url('../images/images/bg.jpg') repeat-x; } but it doesn't work,I,ve tryed this,too: body { ...
loading picture for django templates via css
I have such folder structure in my django site theme: index file load the style.css and the style.css should load my bg.jpg,I do this in style.css: body { background:#fff url('../images/images/bg.jpg') repeat-x; } but it doesn't work,I,ve tryed this,too: body { background:#fff url('sitestatic/images/im...
[ "Try: background:#fff url(../images/images/bg.jpg) repeat-x;\nThe URL should be without the single quotes. BTW why do you have two \"images\" directories nested?\n", "You may want to read the documentation about how to manage static files with django.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007645119_django_python.txt
Q: python - importing modules on shared server i have a script named gmailCleaner.py, on my pc it runs great and ajusts my gmail (using imap) just the way i want. so i wanted to make this script availabl to everybody on my website (shared hosting, python enabled) the script runs but fails to connect to gmail (using s...
python - importing modules on shared server
i have a script named gmailCleaner.py, on my pc it runs great and ajusts my gmail (using imap) just the way i want. so i wanted to make this script availabl to everybody on my website (shared hosting, python enabled) the script runs but fails to connect to gmail (using same settings as in my pc, only diffrence is that ...
[ "If your shared server supports pip install and virtualenv, try this\nvirtualenv env --no-site-packages\npip install python<version>\npip install otherpythonpackages \nThis should solve your problem.\n" ]
[ 0 ]
[]
[]
[ "imaplib", "python", "shared" ]
stackoverflow_0007645381_imaplib_python_shared.txt
Q: Split the string 'abcde' into a list with separate elements I have a string like 'g fmnc wms bgblr rpylqjyrc gr zw fylb'. I use the .split() function in python and get ['g', 'fmnc', 'wms', 'bgblr', 'rpylqjyrc', 'gr', 'zw', 'fylb'] Now I want to split each of the elements into seperated lists like: [['g'], [['f'],[...
Split the string 'abcde' into a list with separate elements
I have a string like 'g fmnc wms bgblr rpylqjyrc gr zw fylb'. I use the .split() function in python and get ['g', 'fmnc', 'wms', 'bgblr', 'rpylqjyrc', 'gr', 'zw', 'fylb'] Now I want to split each of the elements into seperated lists like: [['g'], [['f'],['m'],['n'],['c']],...] and so on. My problem is to split the elem...
[ "Try this:\n[list(item) for item in s.split()]\n\nIt will give you this [['g'], ['f', 'm', 'n', 'c'], ...] which isn't quite what you asked for, but probably what you meant.\n", ">>> sample = 'g fmnc wms bgblr rpylqjyrc gr zw fylb'\n>>> [ list(x) for x in sample.split() ]\n[['g'], ['f', 'm', 'n', 'c'], ['w', 'm',...
[ 4, 2, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0007646001_python_python_2.7.txt
Q: pySerial receives as ASCII how to convert into integer? I am using pySerial to talk to an MSP430 module. This module is transmitting over serial and I am using pySerial to read (as in com.read(20) ). But the type of what pyserial receives is ascii. So when I send out 0x37 from the MSP430 it receives it as '7' and ...
pySerial receives as ASCII how to convert into integer?
I am using pySerial to talk to an MSP430 module. This module is transmitting over serial and I am using pySerial to read (as in com.read(20) ). But the type of what pyserial receives is ascii. So when I send out 0x37 from the MSP430 it receives it as '7' and all this is then given to me as a string something like "7☺7"...
[ "Unpack the data with struct:\n>>> import struct\n>>> data = '\\x37\\x01\\x37'\n>>> struct.unpack('!BBB', data)\n(55, 1, 55)\n\n" ]
[ 2 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0007646420_pyserial_python.txt
Q: cPickle, NetworkX: Why is inheritance faster than delegation? I am using NetworkX to process large graphs. I want to serialize/deserialize those graphs, and I can do that efficiently using cPickle. However, I noticed a performance penalty when I use delegation instead of inheritance, for example: class A: def _...
cPickle, NetworkX: Why is inheritance faster than delegation?
I am using NetworkX to process large graphs. I want to serialize/deserialize those graphs, and I can do that efficiently using cPickle. However, I noticed a performance penalty when I use delegation instead of inheritance, for example: class A: def __init__(self, **kwargs): self.graph = Digraph() class A(DiGr...
[ "Delegation means you have twice the number of objects.\nWithout inheritance, the serialized format looks like this:\nA {graph: [pointer +1]}\nDigraph {name:'mygraph', nodes:..., edges:...}\n\nWith inheritance, it's more like:\nA {name:'mygraph', nodes:..., edges:...}\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007646453_python.txt
Q: qtreeview data inconsistency I have a QTreeView GUI based on editabletreemode.py in the PyQt examples. Inside the model, I re-implemented setData() for my need: for some out-of-bound value, I'm returning False, otherwise, it returns True def setData(self, index, value, role=QtCore.Qt.EditRole): if role != QtCo...
qtreeview data inconsistency
I have a QTreeView GUI based on editabletreemode.py in the PyQt examples. Inside the model, I re-implemented setData() for my need: for some out-of-bound value, I'm returning False, otherwise, it returns True def setData(self, index, value, role=QtCore.Qt.EditRole): if role != QtCore.Qt.EditRole: return Fal...
[ "The only issue I can see is the signature of .setData(), which is .setData(index, value, role). Neither your code snippet nor the description of your problem are verbose enough to say anything else.\nEdit: Indeed, after looking at the Qt sources, I stand corrected. Unlike I've stated before this edit, the return...
[ 1 ]
[]
[]
[ "model_view_controller", "python", "qt" ]
stackoverflow_0007645555_model_view_controller_python_qt.txt
Q: How do I add serial number by replacing character in string in Python? oldName = "old_###" now I want to convert all the "#" in to the serial number, for example, in this case oldName should be "old_001" is there any possible Pythonic Way to do this? A: Couldn't you just do: oldName.replace('###', '001') Of cou...
How do I add serial number by replacing character in string in Python?
oldName = "old_###" now I want to convert all the "#" in to the serial number, for example, in this case oldName should be "old_001" is there any possible Pythonic Way to do this?
[ "Couldn't you just do:\noldName.replace('###', '001')\n\nOf course my assumption here is that you always have 3 '#' symbols.\nSimple is the best way to go I say, if this works you won't need to use the re module.\n", "Try it with string formatting:\nnumber = 123\nserial_number = \"old_%03d\" % number\n\n", "old...
[ 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007646102_python.txt
Q: Is this an appropriate use of python's built-in hash function? I need to compare large chunks of data for equality, and I need to compare many pairs per second, fast. Each object is guaranteed to be the same length, it is possible and likely that there may only be slight differences located at unknown positions. T...
Is this an appropriate use of python's built-in hash function?
I need to compare large chunks of data for equality, and I need to compare many pairs per second, fast. Each object is guaranteed to be the same length, it is possible and likely that there may only be slight differences located at unknown positions. Timings below show that using == operator is very fast if there is a ...
[ "Python's hash function is designed for speed, and maps into a 64-bit space. Due to the birthday paradox, this means you'll likely get a collision at about 5 billion entries (probably way earlier, since the hash function is not cryptographical). Also, the precise definition of hash is up to the Python implementatio...
[ 38 ]
[]
[]
[ "hash", "hash_collision", "python" ]
stackoverflow_0007646520_hash_hash_collision_python.txt
Q: imaplib - works on pc but not on server? import imaplib M=imaplib.IMAP4_SSL('imap.gmail.com', 993) when run on my pc it works and alls fine, but on server it returns: 'module' object has no attribute 'IMAP4_SSL' well this module clearly needs that attribute. any clue? A: IMAP4_SSL is only present if Python's ss...
imaplib - works on pc but not on server?
import imaplib M=imaplib.IMAP4_SSL('imap.gmail.com', 993) when run on my pc it works and alls fine, but on server it returns: 'module' object has no attribute 'IMAP4_SSL' well this module clearly needs that attribute. any clue?
[ "IMAP4_SSL is only present if Python's ssl module is available (you can test with import ssl). Try upgrading your server's python version, and/or installing the ssl module.\n" ]
[ 2 ]
[]
[]
[ "imaplib", "python" ]
stackoverflow_0007646661_imaplib_python.txt
Q: Optimising partial dictionary key match I have a dictionary which uses a 4-tuple as it's key. I need to find all the keys in the dictionary which partially match some other tuple. I have some code which does this but it's slow and needs optimizing. Here's what I'm after: Keys: (1, 2, 3, 4) (1, 3, 5, 2) (2, 4, 8, 7...
Optimising partial dictionary key match
I have a dictionary which uses a 4-tuple as it's key. I need to find all the keys in the dictionary which partially match some other tuple. I have some code which does this but it's slow and needs optimizing. Here's what I'm after: Keys: (1, 2, 3, 4) (1, 3, 5, 2) (2, 4, 8, 7) (1, 4, 3, 4) Match: (1, None, 3, None) Resu...
[ "You can't optimize this further if you store your data in a plain dictionary, since it does not provide anything faster then a sequential access to all elements of your dictionary in some unpredictable order. This means that your solution is not faster then O(n).\nNow, databases. Database is not a universal soluti...
[ 5, 4, 4, 2 ]
[]
[]
[ "algorithm", "optimization", "python" ]
stackoverflow_0007636963_algorithm_optimization_python.txt
Q: Python TCP Client to Client message forwarding I am looking for a short example in python of a TCP server passing an incoming client message to another new client. All I could find was examples on echo server/clients. Cheers, dhpizza A: Here's a basic example using only standard libraries: import SocketServer i...
Python TCP Client to Client message forwarding
I am looking for a short example in python of a TCP server passing an incoming client message to another new client. All I could find was examples on echo server/clients. Cheers, dhpizza
[ "Here's a basic example using only standard libraries:\nimport SocketServer\nimport threading\n\nclass Handler(SocketServer.StreamRequestHandler):\n\n def handle(self):\n print self.client_address,'connected'\n self.server.add_client(self.request)\n while 1:\n data = self.request....
[ 3 ]
[]
[]
[ "client", "forwarding", "message", "python", "tcp" ]
stackoverflow_0007645647_client_forwarding_message_python_tcp.txt
Q: 404 error handling with mako template Trying to display template rendered by mako on 404 errors, but it still displays standart error page with cherrypy footer and additional message: |In addition, the custom error page failed: TypeError: render_body() takes exactly 1 argument (3 given)" The code: def error_page_4...
404 error handling with mako template
Trying to display template rendered by mako on 404 errors, but it still displays standart error page with cherrypy footer and additional message: |In addition, the custom error page failed: TypeError: render_body() takes exactly 1 argument (3 given)" The code: def error_page_404(status, message, traceback, version): ...
[ "You are most likely raising an error with in your 404 handler and I guess you not setting the request.error_response of the cherrypy config like this, and about the error of response_body check this, you are probably using wrong the body of the template.\nEdit from the comments:\ndef error_page_404(status, message...
[ 2, 1 ]
[]
[]
[ "cherrypy", "mako", "python" ]
stackoverflow_0007632183_cherrypy_mako_python.txt
Q: Python, Twisted and adding a cookie to getPage using cookielib Below is my code for adding a cookie to get a page using getPage. Also is the error message I get. How to I add a cookie? Is cookie is None then the code works. cj = cookielib.CookieJar() client.getPage(iUrl,headers,method='GET',cookies=cj).addC...
Python, Twisted and adding a cookie to getPage using cookielib
Below is my code for adding a cookie to get a page using getPage. Also is the error message I get. How to I add a cookie? Is cookie is None then the code works. cj = cookielib.CookieJar() client.getPage(iUrl,headers,method='GET',cookies=cj).addCallback(self.processPage,iUrl).addErrback(self.printError,iUrl) ...
[ "Looks like you're passing a cookiejar in the cookie argument. I can't find a reference for that working.\nI've tried passing a simple dict and it works. Here's the full code:\nfrom twisted.web import client\nimport pprint\n\ndef processPage (page, url):\n print len(page), 'bytes received'\n print 'cookies: '...
[ 2 ]
[]
[]
[ "cookies", "python", "twisted" ]
stackoverflow_0007647258_cookies_python_twisted.txt
Q: How to select font size bgcolor using selenium this is my html code and i need to select font size, bgcolor which is there in nonscript. <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> <!-- RECOMMENDED if your web app will not fu...
How to select font size bgcolor using selenium
this is my html code and i need to select font size, bgcolor which is there in nonscript. <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> <!-- RECOMMENDED if your web app will not function without JavaScript enabled --> <noscript>...
[ "you just want to grab the text? you can look at something like beautiful soup (which i'm not familiar with), or use a simple regex\nimport re\nm = re.compile(r'background-color: (\\w+);',re.I)\nresult = m.search(text)\nif result:\n bgc = result.group(1)\n\n" ]
[ 0 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0007643723_python_selenium_rc.txt
Q: How do I extract an exact word from text by using python? I want to calculate how many lines contain a word matched with keywords I chosen. So I coded like this. 28 for each_keyword in keywords: 29 if each_keyword in text: 31 related_tweet_count += 1 32 p...
How do I extract an exact word from text by using python?
I want to calculate how many lines contain a word matched with keywords I chosen. So I coded like this. 28 for each_keyword in keywords: 29 if each_keyword in text: 31 related_tweet_count += 1 32 print "related_tweet_count", related_tweet_count 33 ...
[ "You need to actually substitute each_keyword into the regular expression. At the moment it's literally trying to match \"each_keyword\".\n28 for each_keyword in keywords:\n30 if re.search('\\\\b' + each_keyword + '\\\\b', text, re.I):\n31 related_tweet_count += 1\n32 ...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007634626_python.txt
Q: Python ConfigParser wrapper I have a config file and i want to load the options dynamicaly by entering the section and the options name. For instance this is the config file contents. [templates] path = /full/path/to/template and the config.py file class Config(object): def __init__(self): self.config...
Python ConfigParser wrapper
I have a config file and i want to load the options dynamicaly by entering the section and the options name. For instance this is the config file contents. [templates] path = /full/path/to/template and the config.py file class Config(object): def __init__(self): self.config = ConfigParser.ConfigParser() ...
[ "config.py\n;# if not applicable leave it blank\n\n[templates]\npath = /full/path/to/template\n\nconfigparse.py\nclass Config(object):\n def __init__(self):\n self.config = ConfigParser.ConfigParser()\n self.config.read('config.py')\n\n def get_path(self):\n return self.config.get('templa...
[ 4 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0007645252_configparser_python.txt
Q: VIM, recognize .pyp as a python file I'm doing some plugin programming for cinema 4d in python and decided to man up and start using a real code editor, VIM. followed the instructions on this page: http://sontek.net/turning-vim-into-a-modern-python-ide my question is what changes do i have to make to the .vimrc fi...
VIM, recognize .pyp as a python file
I'm doing some plugin programming for cinema 4d in python and decided to man up and start using a real code editor, VIM. followed the instructions on this page: http://sontek.net/turning-vim-into-a-modern-python-ide my question is what changes do i have to make to the .vimrc file to get vim to recognize cinema 4d pytho...
[ "Use autocmd to set the filetype when opening an existing or starting a new file. I think this should do it:\nautocmd BufRead,BufNewFile *.pyp set filetype=python\n\nSee :help autocmd for the full details of how this works.\n" ]
[ 6 ]
[]
[]
[ "cinema_4d", "python", "vim" ]
stackoverflow_0007648320_cinema_4d_python_vim.txt
Q: django make query DB TABLE select * from AAA; id | Name | Class | Grade | -------------------------------------- 1 | john | 1 | A | 2 | Jane | 2 | B | 3 | Joon | 2 | A | 4 | Josh | 3 | C | | Code Dj...
django make query
DB TABLE select * from AAA; id | Name | Class | Grade | -------------------------------------- 1 | john | 1 | A | 2 | Jane | 2 | B | 3 | Joon | 2 | A | 4 | Josh | 3 | C | | Code Django search_result = AA...
[ "Maybe you can do it like this:\ntarget_filter = 'Class'\nfilter_args = {target_filter: 3}\nsearch_result = AAA.objects.filter(**filter_args).count()\n\n", "It is somehow the same answer I gave here. You can also use the getattr but now with the module object itself. This is either __module__ if it is the same mo...
[ 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007645503_django_python.txt
Q: Popen Communicate with PIPE does not catch all output of process I'm trying to run a python script and capture the output of it. It seems like after the first output line it redirects to the console instead of to my string. Manage.py is a command-line utility for managing Django projects, like starting the product...
Popen Communicate with PIPE does not catch all output of process
I'm trying to run a python script and capture the output of it. It seems like after the first output line it redirects to the console instead of to my string. Manage.py is a command-line utility for managing Django projects, like starting the production server or running unit tests. This is my code: import os, string, ...
[ "Because they're written to stderr, not stdout. Try\ndef runProcess(command, parameters):\n process = Popen([command]+parameters, stdout=PIPE,stderr=PIPE)\n return process.communicate()\n\nout,err =runProcess('python',['manage.py','test','coffeebean'])\n\nprint (\"*****Own output*****\")\nprint(out)\nprint (\...
[ 3 ]
[]
[]
[ "pipe", "popen", "python", "python_2.7" ]
stackoverflow_0007647106_pipe_popen_python_python_2.7.txt
Q: Python error: TypeError: POST data should be bytes In my below code I am getting an error "raise TypeError("POST data should be bytes" TypeError: POST data should be bytes or an iterable of bytes. It cannot be str." What am I doing wrong ? I am using python 3.2.2 Below is the code: msg = "Test post" password_mana...
Python error: TypeError: POST data should be bytes
In my below code I am getting an error "raise TypeError("POST data should be bytes" TypeError: POST data should be bytes or an iterable of bytes. It cannot be str." What am I doing wrong ? I am using python 3.2.2 Below is the code: msg = "Test post" password_manager = urllib.request.HTTPPasswordMgr() password_manager....
[ "It means what it says - in Python 3, strings are unicode by default, but you can't post unicode: you have to use a bytestring.\nThis should work:\nmsg = b\"Test post\"\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007649002_python.txt
Q: Python pipe in binary file from command line -u option Is there a decoupled method of passing in a binary file without suffering the penalty of python having unbuffered stdout for the entire duration of running a program (if i intend to use only cmdline and not open(...,'rb')? It seems like -u is the only way to ...
Python pipe in binary file from command line -u option
Is there a decoupled method of passing in a binary file without suffering the penalty of python having unbuffered stdout for the entire duration of running a program (if i intend to use only cmdline and not open(...,'rb')? It seems like -u is the only way to read in a file as binary data (from cmdline) http://docs.pyt...
[ "You could perhaps avoid Python's file mode by instead grabbing the fileno out of the sys.stdin file-like object, and using os.read() to grab data from it?\nimport os\nimport sys\n\nstdin_no = sys.stdin.fileno()\nsome_bytes = os.read(stdin_no, 1024)\n\n", "This code will change standard input (only) to unbuffered...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007606822_python.txt
Q: Automated alignment of "tabular" Python code I have some Python code that looks something like this: rates = {3: [((17500, 99999), Decimal('23425.00'), Decimal('7234.24'))], 4: [(( 0, 3510), Decimal( '4563.00'), Decimal('5234.00')), (( 3510, 17500), Decimal('34578.00'), Decimal('3464.50')...
Automated alignment of "tabular" Python code
I have some Python code that looks something like this: rates = {3: [((17500, 99999), Decimal('23425.00'), Decimal('7234.24'))], 4: [(( 0, 3510), Decimal( '4563.00'), Decimal('5234.00')), (( 3510, 17500), Decimal('34578.00'), Decimal('3464.50')), ((17500, 99999), Decimal('18268.00...
[ "(NOTE: I do not consider the following particularly sane.)\nFor the most part if you just typed out (most editors will help you align your dict and list items) your original code you should get something like this:\nrates = {3: [((17500, 199999), Decimal('23425.00'), Decimal('7234.245'))],\n 4: [((0, 3510)...
[ 5, 2, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007643142_python.txt
Q: When is a python object's hash computed and why is the hash of -1 different? Following on from this question, I'm interested to know when is a python object's hash computed? At an instance's __init__ time, The first time __hash__() is called, Every time __hash__() is called, or Any other opportunity I might be ...
When is a python object's hash computed and why is the hash of -1 different?
Following on from this question, I'm interested to know when is a python object's hash computed? At an instance's __init__ time, The first time __hash__() is called, Every time __hash__() is called, or Any other opportunity I might be missing? May this vary depending on the type of the object? Why does hash(-1) == ...
[ "The hash is generally computed each time it's used, as you can quite easily check yourself (see below).\nOf course, any particular object is free to cache its hash. For example, CPython strings do this, but tuples don't (see e.g. this rejected bug report for reasons).\nThe hash value -1 signals an error in CPython...
[ 25, 7, 1 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0007648129_hash_python.txt
Q: django two Model filter I have to two Model: class ModelA(models.Model): field1=models.CharField(max_length=50) field2=models.CharField(max_length=50) class ModelB(model.Model): field3=models.ForeignKey(ModelA) field4=Models.CharField(max_length=50) I want to get ModelA not in ModelB for modelA qu...
django two Model filter
I have to two Model: class ModelA(models.Model): field1=models.CharField(max_length=50) field2=models.CharField(max_length=50) class ModelB(model.Model): field3=models.ForeignKey(ModelA) field4=Models.CharField(max_length=50) I want to get ModelA not in ModelB for modelA queryset result? How do it? Thi...
[ "ModelA.objects.filter(modelb__isnull=True)\n\nShould work.\n" ]
[ 2 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0007649507_django_orm_python.txt
Q: Iterate python list and capitalize specific letters I have a list in python, which I'd like to iterate and capitalize every letter that isn't 'A', so turn this list: ['albert', 'angela', 'leo', 'bridget'] Into: ['aLBERT', 'aNGELa', 'LEO', 'BRIDGET'] A: [''.join(c.upper() if c != 'a' else c for c in word) for wo...
Iterate python list and capitalize specific letters
I have a list in python, which I'd like to iterate and capitalize every letter that isn't 'A', so turn this list: ['albert', 'angela', 'leo', 'bridget'] Into: ['aLBERT', 'aNGELa', 'LEO', 'BRIDGET']
[ "[''.join(c.upper() if c != 'a' else c for c in word) for word in the_list]\n\n", "All of the existing answers seem to want to operate on the characters individually. It is simpler and easier just to handle the words as a whole:\n>>> the_list = ['albert', 'angela', 'leo', 'bridget']\n>>> [ word.upper().replace('A...
[ 4, 3, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007648878_list_python.txt
Q: Does importing a module (but not using it) decrease performance in Python? I'm running a website using Django, and I import ipdb at the beginning of almost all of my scripts to make debugging easier. However, most of the time I never use the functions from the module (only when I'm debugging). Just wondering, will...
Does importing a module (but not using it) decrease performance in Python?
I'm running a website using Django, and I import ipdb at the beginning of almost all of my scripts to make debugging easier. However, most of the time I never use the functions from the module (only when I'm debugging). Just wondering, will this decrease my performance? It's just that when I want to create a breakpoint...
[ "As @wRAR mentioned, Loading a module may imply executing any amounts of code which can take any amount of time. On the other hand, the module will only be loaded once and any subsequent attempt to import will find the module present in os.sys.modules and reference to that.\nIn a Django environment in debuging mode...
[ 3, 2, 0 ]
[]
[]
[ "pdb", "python", "python_import" ]
stackoverflow_0007649136_pdb_python_python_import.txt
Q: Python MySQLdb freeze on connect attempt I'm trying to use MySQLdb in Python to connect to the database I have established on a Pagoda Box application. First, I open the Pagoda tunnel to the database with: $ pagoda tunnel -a <app-name> and it returns that the tunnel has been successfully opened, with the connect...
Python MySQLdb freeze on connect attempt
I'm trying to use MySQLdb in Python to connect to the database I have established on a Pagoda Box application. First, I open the Pagoda tunnel to the database with: $ pagoda tunnel -a <app-name> and it returns that the tunnel has been successfully opened, with the connection available on 127.0.0.1:3307. I run the fo...
[]
[]
[ "As a general rule whenever you are trying to figure out where a program is stalled you can either launch it with strace (strace myprog.py) or you can run an strace on the pid (strace -p pidnum)\nfor example, my ipython has a pid of 12608 so I run\n strace -po 12608\n\nthen I run\n con = MySQLdb.connect('xxx....
[ -1 ]
[ "freeze", "mysql_python", "python" ]
stackoverflow_0007649680_freeze_mysql_python_python.txt
Q: python regex search I have another question with regex, i want to catch info1,info2 and info3 : >>> a '|123|blabla bloblo|90' >>> b '|123|blabla[[blibli|bloblo]]|90' >>> re.search('\|(?P<info1>\d+)\|(?P<info2>[^\|]*)\|(?P<info3>\d+)',a).groupdict() {'info1': '123', 'info3': '90', 'info2': 'blabla bloblo'} >>> ...
python regex search
I have another question with regex, i want to catch info1,info2 and info3 : >>> a '|123|blabla bloblo|90' >>> b '|123|blabla[[blibli|bloblo]]|90' >>> re.search('\|(?P<info1>\d+)\|(?P<info2>[^\|]*)\|(?P<info3>\d+)',a).groupdict() {'info1': '123', 'info3': '90', 'info2': 'blabla bloblo'} >>> re.search('\|(?P<info1>\d...
[ "Just to give you alternative and assuming that you data doesn't contains quote \" or you can replace it with any other char, here is away to use csv module\nimport csv\nimport StringIO\ndata = '|123|blabla|[[blibli|bloblo]]|90'\n# assuming data doesn't have quotes, we can convert [[ and ]] to quotes and use csv to...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007649065_python_regex.txt
Q: How I can set gap in Vertical BoxSizer? How can I set gap in Vertical BoxSizer? What's in the Vertival BoxSizer the similar or alternative method of SetVGap (which sets the vertical gap (in pixels) between the cells in the sizer) in GridSizer? A: There are several ways to add blank space in a sizer. sizer = wx.B...
How I can set gap in Vertical BoxSizer?
How can I set gap in Vertical BoxSizer? What's in the Vertival BoxSizer the similar or alternative method of SetVGap (which sets the vertical gap (in pixels) between the cells in the sizer) in GridSizer?
[ "There are several ways to add blank space in a sizer.\nsizer = wx.BoxSizer(wx.VERTICAL)\nsizer.Add(widget, proportion=0, style=wx.ALL, border=5)\n\nThe code above will add the widget with a 5 pixel border on all sides of it. If you want to put some space between two widgets, you can do one of the following:\nsizer...
[ 16, 5, 5, 2 ]
[]
[]
[ "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0007647760_python_user_interface_wxpython_wxwidgets.txt
Q: Convert an int to a CSS colour Possible Duplicate: RGB Int to RGB - Python Using Python I need to convert an int to a six digit hex that I can use as a background colour in CSS. Any ideas how to do that? The int is a primary key of a model in Django. A: Convert an int to a 6-digit hex: In [10]: '{0:06X}'.forma...
Convert an int to a CSS colour
Possible Duplicate: RGB Int to RGB - Python Using Python I need to convert an int to a six digit hex that I can use as a background colour in CSS. Any ideas how to do that? The int is a primary key of a model in Django.
[ "Convert an int to a 6-digit hex:\nIn [10]: '{0:06X}'.format(16746513)\nOut[10]: 'FF8811'\n\nCheck that the hex is equivalent to the int:\nIn [9]: int('FF8811',16)\nOut[9]: 16746513\n\n", "IF you really just have an integer then \"#\" + hex(value) will return the appropriate code to use. However, if you have a tu...
[ 10, 5 ]
[]
[]
[ "css", "python" ]
stackoverflow_0007651007_css_python.txt
Q: DoesNotExist error in django view/template with one-to-one field I have these models. class Storypak(models.Model): headline = models.CharField('Headline', max_length=200) pub_date = models.DateField(blank=True) class Story(models.Model): storypak = models.OneToOneField('Storypak', blank=True, null=Tr...
DoesNotExist error in django view/template with one-to-one field
I have these models. class Storypak(models.Model): headline = models.CharField('Headline', max_length=200) pub_date = models.DateField(blank=True) class Story(models.Model): storypak = models.OneToOneField('Storypak', blank=True, null=True) copy = models.TextField(blank=True) And this view. def pak_de...
[ "You haven't given enough detail to troubleshoot much past the error here, but the simple error message can only be triggered by one statement in your view, that is...\npak = Storypak.objects.get(pk=pak_id)\n\nThe pak_id is either invalid, or your model is malformed and a Storypak with that id doesn't exist. That i...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0007643174_django_django_models_django_templates_django_views_python.txt
Q: Django problems with saving a m2m relationship I have been able to save m2m relationships with forms in the past, but I am currently have problems with the following and I can't understand why: # models.py class File(models.Model): client = models.ManyToManyField(Client) product = models.ForeignKey(Produc...
Django problems with saving a m2m relationship
I have been able to save m2m relationships with forms in the past, but I am currently have problems with the following and I can't understand why: # models.py class File(models.Model): client = models.ManyToManyField(Client) product = models.ForeignKey(Product, related_name='item_product') created = models...
[ "You're trying to assign one client to a ManyToMany field. This would work if it was a ForeignKey to a Client, but for ManyToMany, you will have to do something like:\ntemp.client.add(client)\n\nNote: temp will have to be saved first, before you can assign clients. This is because there's a table Django uses mappin...
[ 3, 2 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0007651628_django_django_forms_django_views_python.txt
Q: "reduce" function in python not work on "namedtuple"? I have a log file that is formatted in the following way: datetimestring \t username \t transactionName \r\n I am attempting to run some stats over this dataset. I have the following code: import time import collections file = open('Log.txt', 'r') Transactio...
"reduce" function in python not work on "namedtuple"?
I have a log file that is formatted in the following way: datetimestring \t username \t transactionName \r\n I am attempting to run some stats over this dataset. I have the following code: import time import collections file = open('Log.txt', 'r') TransactionData = collections.namedtuple('TransactionData', ['transac...
[ "Simply use:\nminDate = min(t.transactionDate for t in transactions)\n\nBelow is an explanation of why your code isn't working.\nLet's say transactions = [t1, t2, t3] where t1...t3 are three named tuples.\nBy the definition of reduce, your code:\nreduce(lambda x,y: min(x.transactionDate, y.transactionDate), transac...
[ 6 ]
[]
[]
[ "lambda", "python", "reduce" ]
stackoverflow_0007651762_lambda_python_reduce.txt
Q: GUI to control multiple remote hosts (using the same GUI for simulation and real hardware) I've a GUI based on python and gtk, my program manages varios applications in the same machine using subprocesses, i.e a button launchs an emulated host, another button connects it to a switch ... now I want to but each com...
GUI to control multiple remote hosts (using the same GUI for simulation and real hardware)
I've a GUI based on python and gtk, my program manages varios applications in the same machine using subprocesses, i.e a button launchs an emulated host, another button connects it to a switch ... now I want to but each component in a separated machine (some hosts will work as soft switches, others may work as routers...
[ "Since you already have a mechanism that works to spawn the processes on the local machine, it sounds like the only thing you're lacking is a way to spawn the processes on the remote machines. I would go with simple ssh connections as it would require the fewest changes to both your infrastructure and your code.\n...
[ 1 ]
[]
[]
[ "python", "simulation", "ssh", "virtualization" ]
stackoverflow_0007645841_python_simulation_ssh_virtualization.txt
Q: Python(3), Loop over tuple and use string format to display My homework assignment is to Loop over ((1, 1), (2, 2), (12, 13), (4, 4)) and use string formatting to display this tuple as: 1 = 1 x 1 4 = 2 x 2 156 = 12 x 13 16 = 4 x 4 while also preserving the spacing. What I have so far: d = ((1,1), (2,2), (12,13...
Python(3), Loop over tuple and use string format to display
My homework assignment is to Loop over ((1, 1), (2, 2), (12, 13), (4, 4)) and use string formatting to display this tuple as: 1 = 1 x 1 4 = 2 x 2 156 = 12 x 13 16 = 4 x 4 while also preserving the spacing. What I have so far: d = ((1,1), (2,2), (12,13), (4,4)) for a, b in d: print("{0} = {1}".format(a* b, d)) ...
[ "d = ((1,1), (2,2), (12,13), (4,4))\nfor a, b in d:\n print(\"{0} = {1} x {2}\".format(a* b, a, b))\n\n", "On the right side of the equation you want to print the content of variable a, then the character x and then the content of variable b.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "string_formatting", "tuples" ]
stackoverflow_0007652073_python_string_formatting_tuples.txt
Q: Is it possible to use Python based Unit Test frameworks and runners, to test C Code Python based Unit test Frameworks like "nose" have a lot of rich features, i wonder if we can leverage them to test C Code. A: Of course you can.... but you'll have to write a binding to call your C code in python (with ctypes fo...
Is it possible to use Python based Unit Test frameworks and runners, to test C Code
Python based Unit test Frameworks like "nose" have a lot of rich features, i wonder if we can leverage them to test C Code.
[ "Of course you can.... but you'll have to write a binding to call your C code in python (with ctypes for example), and write the tests in python (this is really possible and an easy way to do smart tests)\nExample : \n\nWrite a dummy C library.\n\nfoolib.c\nint my_sum(int , int);\n\nint my_sum(int a , int b);\n{\n ...
[ 15 ]
[]
[]
[ "c", "python", "unit_testing" ]
stackoverflow_0007652193_c_python_unit_testing.txt
Q: How can I open URLs in an existing browser window with the webbrowser module? I’m using the webbrowser Python module to open images in Internet Explorer. Specifically, I’m using the webbrowser.open('C:...', new=0) command. However, even though I say new=0 my URL is always opened in a new browser window. What can I...
How can I open URLs in an existing browser window with the webbrowser module?
I’m using the webbrowser Python module to open images in Internet Explorer. Specifically, I’m using the webbrowser.open('C:...', new=0) command. However, even though I say new=0 my URL is always opened in a new browser window. What can I do so my link is opened in an already-open browser window? Thank you for your help...
[ "Try open_new_tab.\nwebbrowser.open_new_tab(url)\nOpen url in a new page (“tab”) of the default browser, if possible, otherwise equivalent to open_new().\n\nFrom the docs: http://docs.python.org/library/webbrowser.html\n" ]
[ 1 ]
[]
[]
[ "browser", "python", "webbrowser_control" ]
stackoverflow_0007651141_browser_python_webbrowser_control.txt
Q: Data structure for large ranges of consecutive integers? Suppose you have a large range of consecutive integers in memory, each of which belongs to exactly one category. Two operations must be O(log n): moving a range from one category to another, and finding the category counts for a given range. I'm pretty sure ...
Data structure for large ranges of consecutive integers?
Suppose you have a large range of consecutive integers in memory, each of which belongs to exactly one category. Two operations must be O(log n): moving a range from one category to another, and finding the category counts for a given range. I'm pretty sure the second operation is solved trivially given a correct imple...
[ "As far as I understood the question you have a range [A, B] and queries of the form -\n\nAssign a particular range to a category\n\n\nE.g.\nR1 R2 C1\nR3 R4 C2\n\n\nQuery a range for the total number of items in particular categories.\nE.g. find count of categories in R1 R4\n\nA simple implementation using dictiona...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "computer_science", "python", "tree" ]
stackoverflow_0007644737_algorithm_computer_science_python_tree.txt
Q: Copy data from MS Access to MS Excel using Python I've been spending the better part of the weekend trying to figure out the best way to transfer data from an MS Access table into an Excel sheet using Python. I've found a few modules that may help (execsql, python-excel), but with my limited knowledge and the modu...
Copy data from MS Access to MS Excel using Python
I've been spending the better part of the weekend trying to figure out the best way to transfer data from an MS Access table into an Excel sheet using Python. I've found a few modules that may help (execsql, python-excel), but with my limited knowledge and the modules I have to use to create certain data (I'm a GIS pro...
[ "I eventually found a way to do this. I thought I'd post my code for anyone who may run into the same situation. I use some GIS files, but if you don't, you can set a variable to a directory path instead of using env.workspace and use a cursor search instead of the arcpy.SearchCursor function, then this is doable.\...
[ 3, 1, 1, 1, 1 ]
[]
[]
[ "excel", "ms_access", "python" ]
stackoverflow_0007630142_excel_ms_access_python.txt
Q: Python - change directory to a folder based on what day of the week it is I'm trying to automate an ftp upload with files that are in folders based on the day of the week. Since today is Tuesday I would like to have the script go to the //server/folder/Tuesday folder, and upload the files in that folder. I have t...
Python - change directory to a folder based on what day of the week it is
I'm trying to automate an ftp upload with files that are in folders based on the day of the week. Since today is Tuesday I would like to have the script go to the //server/folder/Tuesday folder, and upload the files in that folder. I have this: os.chdir("//MTR-SRV/Creative/CHARGER/Monitor/Out") cwd = os.getcwd() prin...
[ "You can get the day of the week like this:\n>>> import time\n>>> time.strftime('%A')\n'Tuesday'\n\nIn your case, this ought to do the trick:\nimport time\ndayofweek = time.strftime('%A')\nos.chdir(\"//MTR-SRV/Creative/CHARGER/Monitor/Out/\" + dayofweek)\n\n", "import datetime\n\ndayname = datetime.datetime.now()...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007652444_python.txt
Q: MongoDB "$or" update I have some code that deletes multiple objects from Mongo using an $or opperator, or at least it should. This code illustrates basically what my app is doing lookup = [] listofids = ['4e86fee56607f2a8a2000002','4e86fee56607f2a8a2000003','4e86feeb6607f2a8a2000006'] for id in listofids: look...
MongoDB "$or" update
I have some code that deletes multiple objects from Mongo using an $or opperator, or at least it should. This code illustrates basically what my app is doing lookup = [] listofids = ['4e86fee56607f2a8a2000002','4e86fee56607f2a8a2000003','4e86feeb6607f2a8a2000006'] for id in listofids: lookup.append({'_id':core.Obje...
[ "You need to set the multi parameter to True in order to update all documents that match your query. Otherwise, it only updates the first one (which you probably just don’t notice). See Collection.update.\n(Also note: if you’re querying on multiple values of a single field, you can use the $in operator.)\n" ]
[ 3 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0007652370_mongodb_python.txt
Q: Use a form field as the entity key google app engine python I have a form where a user logs in with a google account and then makes or updates their profile in google app engine. I want to use the form field that contains their email address (which is automatically filled in with their user info from google) as t...
Use a form field as the entity key google app engine python
I have a form where a user logs in with a google account and then makes or updates their profile in google app engine. I want to use the form field that contains their email address (which is automatically filled in with their user info from google) as the new entry's key. This way I can easily update the entries sin...
[ "Every entity in GAE datastore has a key, the key can be an id or string.\nWhen creating an entity you can specify which value the key will have using the key_name atribute. for example: \nAthlete.get_or_insert(key_name=name, ....)\n\nYou can remove the key_name that you put in your model and use the one that come...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007652479_google_app_engine_python.txt
Q: Python: escaping issue with ujson I am using ujson to convert dictionary to json. when I run the following line: ujson.dumps({'key':'val\1'}) I get the following result: [{"key": "val\\1"}] while I expect/want it to be: [{"key": "val\1"}] any idea? A: There is no problem, that's what repr looks like for this ...
Python: escaping issue with ujson
I am using ujson to convert dictionary to json. when I run the following line: ujson.dumps({'key':'val\1'}) I get the following result: [{"key": "val\\1"}] while I expect/want it to be: [{"key": "val\1"}] any idea?
[ "There is no problem, that's what repr looks like for this value. It is \\1.\n" ]
[ 7 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007652759_json_python.txt
Q: Python: How to replace dashes in filenames? The question is related to the answer about renaming files recursively. The code, changed to replace dashes, does not work with cases such as: ./Beginners Tools/Hello's -Trojans-/bif43243 ./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432) ./Git/peep...
Python: How to replace dashes in filenames?
The question is related to the answer about renaming files recursively. The code, changed to replace dashes, does not work with cases such as: ./Beginners Tools/Hello's -Trojans-/bif43243 ./Linux/Nux Col - 1 Works (TEX & Pdf) - T'eouhsoe & More (33323 - 34432) ./Git/peepcode-git-mov/c6_branch_merge.mov ./haskell/OS 200...
[ "The os.path.walk is handy for traversing file system trees, a simple example:\nimport os, shutil\n\ndef rename_file(arg, dirname, filename):\n filepath = os.path.join(dirname, filename)\n # check if file meets your rename condition here\n if os.path.isfile(filepath):\n new_name = \"something\"\n ...
[ 2, 1, 0 ]
[]
[]
[ "parsing", "python", "recursion", "rename" ]
stackoverflow_0001696984_parsing_python_recursion_rename.txt
Q: How to stop a code running due to an input error without causing the GUI from crashing I had a program developed in Python (2.7 & 3.2) that reads three files and generates some code based on those files. In the code, I had several input file checks to capture any input errors by the user. If the program catches ...
How to stop a code running due to an input error without causing the GUI from crashing
I had a program developed in Python (2.7 & 3.2) that reads three files and generates some code based on those files. In the code, I had several input file checks to capture any input errors by the user. If the program catches an input error, I used os.sys.exit() command to stop processing and issue an error message. ...
[ "I assume you can not or prefer not to change your CLI programs and instead wish to catch the exception raised by sys.exit instead in the GUI. Here is how:\nimport os\ntry:\n os.sys.exit()\nexcept SystemExit as err:\n print('Caught ya')\n\n", "Have you tried handling exceptions in python.\n\n\ntry:\n #some ...
[ 3, 0 ]
[]
[]
[ "exit", "pyqt4", "python" ]
stackoverflow_0007652816_exit_pyqt4_python.txt
Q: DOM manipulations in Python (if some element contains only one other element...) I need to remove all <p>s where they are of no need. Such as convert <div><p>xxxx</p></div> to <div>xxxx</div>. How can I do it with DOM? "If <div> has only one <p> inside, than assign that <p>'s text to <div> and remove this <p>". ...
DOM manipulations in Python (if some element contains only one other element...)
I need to remove all <p>s where they are of no need. Such as convert <div><p>xxxx</p></div> to <div>xxxx</div>. How can I do it with DOM? "If <div> has only one <p> inside, than assign that <p>'s text to <div> and remove this <p>". I'd rether do it with regex, but some people say that it is bad. I can't imagine how i...
[ "This works for me:\nfrom xml.dom import minidom\n\ntext = \"<div><p>xxxx</p></div>\"\ndoc = minidom.parseString(text)\n\n# For each div in the root document\nfor tag in doc.childNodes:\n # If it's a <p> and there's only one\n if len(tag.childNodes) == 1 and tag.childNodes[0].tagName == 'p':\n # p_node...
[ 7, 6 ]
[ "Building upon @jterrace answer:\n(PLEASE EDIT THIS QUESTION SO THAT IT IS COMPLETE, OR COMMENT)\nI think the way to go is to create a minidom.Document so that you can modify its xml nodes.\n#coding: utf-8\n\nfrom xml.dom import minidom\n\ntext = \"<div><p>xxxx</p></div>\"\n\ndom = minidom.parseString(text)\n\nfor ...
[ -1, -4 ]
[ "dom", "python" ]
stackoverflow_0007652701_dom_python.txt
Q: Docstring tag for 'yield' keyword There are some tags for docstrings in python, like @param and @return, for example: def my_method(a_param): ''' @param a_param: Description of this param @return: The return value of the method ''' return int(a_param) * (other or 1) What can I use for document...
Docstring tag for 'yield' keyword
There are some tags for docstrings in python, like @param and @return, for example: def my_method(a_param): ''' @param a_param: Description of this param @return: The return value of the method ''' return int(a_param) * (other or 1) What can I use for documenting generators? specially the yield key...
[ "I would consider @return to be appropriate in this case because the function actually returns an iterator object with a next or send method. The validity of the statement x = my_generator(from=3) implies that my_generator really does return something. It merely does so without using the return statement to do it...
[ 9 ]
[]
[]
[ "docstring", "documentation", "python" ]
stackoverflow_0007652540_docstring_documentation_python.txt
Q: python web server and periodic tasks I am using CherryPy to receive requests through REST API. Apart from handling requests the application should also do some resource management every few seconds. What is the easiest way to do this? 1) run a separate thread 2) cherrypy.process.plugins.PerpetualTimer (not sure ho...
python web server and periodic tasks
I am using CherryPy to receive requests through REST API. Apart from handling requests the application should also do some resource management every few seconds. What is the easiest way to do this? 1) run a separate thread 2) cherrypy.process.plugins.PerpetualTimer (not sure how to use it, and it looks like it is heavy...
[ "PerpetualTimer is just a repeating version of threading._Timer.\nWhat you really want to use is cherrypy.process.plugins.Monitor, which is little more than a way to run a separate thread for you. You should use it because it plugs into cherrypy.engine, which governs start and stop behavior for CherryPy servers. If...
[ 3 ]
[]
[]
[ "cherrypy", "multithreading", "python", "webserver" ]
stackoverflow_0007648416_cherrypy_multithreading_python_webserver.txt
Q: File is not decoded properly I have a file encoded in a strange pattern. For example, Char (1 byte) | Integer (4 bytes) | Double (8 bytes) | etc... So far, I wrote the code below, but I have not been able to figure out why still shows garbage in the screen. Any help will be greatly appreciated. BRK_File = 'command...
File is not decoded properly
I have a file encoded in a strange pattern. For example, Char (1 byte) | Integer (4 bytes) | Double (8 bytes) | etc... So far, I wrote the code below, but I have not been able to figure out why still shows garbage in the screen. Any help will be greatly appreciated. BRK_File = 'commands.BRK' input = open(BRK_File, "rb"...
[ "read() returns a string, which you need to decode to get the binary data. You could use the struct module to do the decoding.\nSomething along the following lines should do the trick:\nimport struct\n...\nfmt = 'cid' # char, int, double\ndata = input.read(struct.calcsize(fmt))\nrev, filesize, highpoint = struct.un...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007653254_python.txt
Q: How to add input to command line prompt from wxPython? So I have this code on python, that retrieves output from console when executing shell commands. def OnClick(self, event): cmd = self.command.GetValue() if cmd: input, output, errors = os.popen3(cmd) errors = errors.read() if errors...
How to add input to command line prompt from wxPython?
So I have this code on python, that retrieves output from console when executing shell commands. def OnClick(self, event): cmd = self.command.GetValue() if cmd: input, output, errors = os.popen3(cmd) errors = errors.read() if errors: dlg = wx.MessageDialog(self, errors, 'An e...
[ "Typically when you have a long running process, you need to use a thread. See wiki.wxpython.org/LongRunningTasks for several example solutions. When you get to the password prompt, you can send some kind of notification to the GUI to display a dialog using wx.CallAfter or wx.PostEvent. There are ways to communicat...
[ 0 ]
[]
[]
[ "command_line_interface", "python", "wxpython" ]
stackoverflow_0007653288_command_line_interface_python_wxpython.txt
Q: TypeError: unsupported operand type(s) for -: 'str' and 'str' a'$' money=1000000; portfolio=0; value=0; value=(yahoostock.get_price('RIL.BO')); portfolio=(16*(value)); print id(portfolio); print id(value); money= (money-portfolio); ''' I am getting the error: Traceback (most recent call last): File "/home/dee/d...
TypeError: unsupported operand type(s) for -: 'str' and 'str'
a'$' money=1000000; portfolio=0; value=0; value=(yahoostock.get_price('RIL.BO')); portfolio=(16*(value)); print id(portfolio); print id(value); money= (money-portfolio); ''' I am getting the error: Traceback (most recent call last): File "/home/dee/dee.py", line 12, in <module> money= (value-portfolio); TypeErro...
[ "value=(yahoostock.get_price('RIL.BO'));\n\nApparently returns a string not a number. Convert it to a number: \nvalue=int(yahoostock.get_price('RIL.BO'));\n\nAlso the signal-to-noise ratio isn't very high. You've lots of (,), and ; you don't need. You assign variable only to replace them on the next line. You ca...
[ 6, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007653403_python.txt
Q: Django: is importing a view from a module slower than including it in the main views.py file? This may be more of a question about how Python itself imports methods, which while I understand on a surface level, I don't really have a deep understanding of. An extremely simplified example might make things clearer. ...
Django: is importing a view from a module slower than including it in the main views.py file?
This may be more of a question about how Python itself imports methods, which while I understand on a surface level, I don't really have a deep understanding of. An extremely simplified example might make things clearer. Of the two examples below, would there be any noticeable difference in speed of execution? Example ...
[ "You won't see any difference in speed. Once a module is imported, it is kept in memory so it doesn't have to be loaded again. You can check what has been loaded like so:\nimport sys\nprint sys.modules\n# {'cStringIO': <module 'cStringIO' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/...
[ 5, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007652234_django_python.txt
Q: Download from Megaupload with login - Python It's my first question here. Today, I've done a little application using wxPython: a simple Megaupload Downloader, but yet, it doesn't support premium accounts. Now I would like to know how to download from MU with a login (free or premium user). I'm very new to Python,...
Download from Megaupload with login - Python
It's my first question here. Today, I've done a little application using wxPython: a simple Megaupload Downloader, but yet, it doesn't support premium accounts. Now I would like to know how to download from MU with a login (free or premium user). I'm very new to Python, so please don't be specific and "professional". I...
[ "Questions like this are usually frowned upon, they are very broad, and there are already an abundance of answers if you just search on google.\nYou can use urllib, or mechanize, or any library you can make an http post request with.\nmegaupload looks to have the form values\nlogin:1\nredir:1\nusername:\npassword:\...
[ 1, 1, 1, 0 ]
[]
[]
[ "authentication", "download", "megaupload", "python" ]
stackoverflow_0007653793_authentication_download_megaupload_python.txt
Q: Encountered invalid value when I use pearsonr Maybe I made a mistake. If so, I am sorry to ask this. I want to calculate Pearson's correlation coefficent by using scipy's pearsonr function. from scipy.stats.stats import pearsonr X = [4, 4, 4, 4, 4, 4] Y = [4, 5, 5, 4, 4, 4] pearsonr(X, Y) I get an error below ...
Encountered invalid value when I use pearsonr
Maybe I made a mistake. If so, I am sorry to ask this. I want to calculate Pearson's correlation coefficent by using scipy's pearsonr function. from scipy.stats.stats import pearsonr X = [4, 4, 4, 4, 4, 4] Y = [4, 5, 5, 4, 4, 4] pearsonr(X, Y) I get an error below RuntimeWarning: invalid value encountered in doubl...
[ "\nPearson's correlation coefficient between two variables is defined as the covariance of the two variables divided by the product of their standard deviations.\n\nSo it's the covariance over \n\nthe standard deviation of [4, 5, 5, 4, 4, 4] times \nthe standard deviation of [4, 4, 4, 4, 4, 4].\n\nThe standard devi...
[ 24 ]
[]
[]
[ "correlation", "python", "scipy" ]
stackoverflow_0007653993_correlation_python_scipy.txt
Q: Setting the source for Phonon::VideoPlayer Here is the link to my .ui file. And here is the code to start the GUI: import sys from PyQt4 import QtCore, QtGui from gui import Ui_Form class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self....
Setting the source for Phonon::VideoPlayer
Here is the link to my .ui file. And here is the code to start the GUI: import sys from PyQt4 import QtCore, QtGui from gui import Ui_Form class StartQT4(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_Form() self.ui.setupUi(self) i...
[ "Without getting into TOO much detail about how the Phonon package works, here is a quick snippet:\nfrom PyQt4.phonon import Phonon\n\n...\n\nsource = Phonon.MediaSource(\"http://vsyamuzika.narod.ru/tvist/Rock_around_the_clock.mp3\")\nself.ui.videoPlayer.mediaObject().setCurrentSource(source)\nself.ui.videoPlayer.p...
[ 1 ]
[]
[]
[ "pyqt", "python", "user_interface" ]
stackoverflow_0007643256_pyqt_python_user_interface.txt
Q: Python RegEx nested search and replace I need to to a RegEx search and replace of all commas found inside of quote blocks. i.e. "thing1,blah","thing2,blah","thing3,blah",thing4 needs to become "thing1\,blah","thing2\,blah","thing3\,blah",thing4 my code: inFile = open(inFileName,'r') inFileRl = inFile.re...
Python RegEx nested search and replace
I need to to a RegEx search and replace of all commas found inside of quote blocks. i.e. "thing1,blah","thing2,blah","thing3,blah",thing4 needs to become "thing1\,blah","thing2\,blah","thing3\,blah",thing4 my code: inFile = open(inFileName,'r') inFileRl = inFile.readlines() inFile.close() p = re.compile(r'[...
[ "The csv module is perfect for parsing data like this as csv.reader in the default dialect ignores quoted commas. csv.writer reinserts the quotes due to the presence of commas. I used StringIO to give a file like interface to a string. \nimport csv\nimport StringIO\n\ns = '''\"thing1,blah\",\"thing2,blah\",\"thin...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0007651220_python_regex_replace.txt
Q: Weird Post-Run Animation Error I have a Python 2.7/PyGTK 2.24 project. I'm building on Linux Ubuntu 11. I am using the following code to animate an image's movement across the screen. def move_fish(): global fishmove, flipped if fishmove < 440 and flipped == False: fishmove = fishm...
Weird Post-Run Animation Error
I have a Python 2.7/PyGTK 2.24 project. I'm building on Linux Ubuntu 11. I am using the following code to animate an image's movement across the screen. def move_fish(): global fishmove, flipped if fishmove < 440 and flipped == False: fishmove = fishmove + 10 fixed_hab.move(...
[ "Most likely your tiemout_add fires while the application is destroyed. \nYour options are:\n\nWire a destroy handler and remove the timer before exit.\nTopmost inside move_fish, check if the widget is destroyed and return False to end the timer.\n\nAccessing a widget that no longer exists can fail silently but whe...
[ 0 ]
[]
[]
[ "animation", "gobject", "pygtk", "python" ]
stackoverflow_0007463634_animation_gobject_pygtk_python.txt
Q: import sqlite3 with Python2.7 on Heroku I'm trying Heroku with Python, I ran the "hello word" example with Flask successfully. I now want to deploy a very basic application, using sqlite3 and Flask, and I know the application was working. But I have trouble getting it to work, and I suspect the problem is with sql...
import sqlite3 with Python2.7 on Heroku
I'm trying Heroku with Python, I ran the "hello word" example with Flask successfully. I now want to deploy a very basic application, using sqlite3 and Flask, and I know the application was working. But I have trouble getting it to work, and I suspect the problem is with sqlite. When I started the Python shell that Her...
[ "This isn't possible on Heroku, as sqlite requires a permanent writable file system. Since Heroku does not provide a permanent writable file system, sqlite3 won't work.\nSomething to consider: Heroku is a distributed environment. This means an application may run on many machines within many processes. In your case...
[ 1 ]
[]
[]
[ "heroku", "python", "sqlite" ]
stackoverflow_0007653010_heroku_python_sqlite.txt
Q: Python: Email addresses Python 3# -- coding: utf-8 --email = input ( 'Email: ' )print email # oÓ.öŐ §'"+!%/=()@uÚ.üŰ §'"+!%/=().comI would like:print email # oo.oo@uu.uu.comLatin 1 (ISO-8859-1) characters, at sign (@) and dot (.).Lowletters.The (white) space and special characters are delete.Sorry, I speak a littl...
Python: Email addresses
Python 3# -- coding: utf-8 --email = input ( 'Email: ' )print email # oÓ.öŐ §'"+!%/=()@uÚ.üŰ §'"+!%/=().comI would like:print email # oo.oo@uu.uu.comLatin 1 (ISO-8859-1) characters, at sign (@) and dot (.).Lowletters.The (white) space and special characters are delete.Sorry, I speak a little English.Thank you!
[ "What you are looking for can be accomplished with the string.translate() function.\nSee: Python Docs - String.\nSee also: This tutorial.\n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0007654183_email_python.txt
Q: Good way to organize all sub classes into a dictionary in python? I have a base class and several subclasses. Each sub class has an attribute called "regex" containing a string: # module level dictionary action_types = {} class Action(): regex = '.*' @classmethod def register_action(cls): act...
Good way to organize all sub classes into a dictionary in python?
I have a base class and several subclasses. Each sub class has an attribute called "regex" containing a string: # module level dictionary action_types = {} class Action(): regex = '.*' @classmethod def register_action(cls): action_types[cls.regex] = cls class Sing(Action): regex = r'^SING [0...
[ "That's not how you want to do it.\nclass ActionRegistry(type):\n registry = {}\n def __init__(cls, name, bases, dic):\n if 'regex' in dic:\n cls.registry[dic['regex']] = cls\n super(ActionRegistry, cls).__init__(name, bases, dic)\n\nclass Action(object):\n __metaclass__ = ActionRegistry\n\nclass Sing...
[ 7, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007654272_python_regex.txt
Q: Python code error with sum() function -- syntax works on one platform not another I'm having an error using Python (inherited code). A Sum() function call that works on one platform is not working on another -- I think it is due to some syntax that is incompatible across platforms. The error I am getting is: bsrlx...
Python code error with sum() function -- syntax works on one platform not another
I'm having an error using Python (inherited code). A Sum() function call that works on one platform is not working on another -- I think it is due to some syntax that is incompatible across platforms. The error I am getting is: bsrlx1(112)% /usr/bin/python run-print.py init data File "run-print.py", line 105 val ...
[ "You're using a conditional expression, which was added in Python 2.5.\nYou're not running /usr/bin/python2.5, you're using /usr/bin/python (which is 2.4). To run it using the interpreter specified in the file, make it executable and then run it directly:\nchmod +x run-print.py\n./run-print.py\n\nIt's unlikely that...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007653661_python.txt
Q: Sync local file with HTTP server location (in Python) I have an HTTP server which host some large file and have python clients (GUI apps) which download it. I want the clients to download the file only when needed, but have an up-to-date file on each run. I thought each client will download the file on each run us...
Sync local file with HTTP server location (in Python)
I have an HTTP server which host some large file and have python clients (GUI apps) which download it. I want the clients to download the file only when needed, but have an up-to-date file on each run. I thought each client will download the file on each run using the If-Modified-Since HTTP header with the file time of...
[ "You can add a header called ETag, (hash of your file, md5sum or sha256 etc ), to compare if two files are different instead of last-modified date\n", "I'm assuming some things right now, BUT..\nOne solution would be to have a separate HTTP file on the server (check.php) which creates a hash/checksum of each file...
[ 1, 0, 0 ]
[]
[]
[ "http", "httpclient", "if_modified_since", "python", "urllib2" ]
stackoverflow_0007623600_http_httpclient_if_modified_since_python_urllib2.txt
Q: Mapping tuple (R, R) into ((R,R),R)? Input [[0 0 0 0 0] [0 4 0 0 0] [0 1 0 0 0] [0 1 2 0 0] [0 1 2 3 0]] Intended output [[(0, day00) (0, day01) (0, day02) (0, day03) (0, day04)] [(0, day10) (4, day11) (0, day12) (0, day13) (0, day14)] [(0, day20) (1, day21) (0, day22) (0, day23) (0, day24)] [(0, day30) (1...
Mapping tuple (R, R) into ((R,R),R)?
Input [[0 0 0 0 0] [0 4 0 0 0] [0 1 0 0 0] [0 1 2 0 0] [0 1 2 3 0]] Intended output [[(0, day00) (0, day01) (0, day02) (0, day03) (0, day04)] [(0, day10) (4, day11) (0, day12) (0, day13) (0, day14)] [(0, day20) (1, day21) (0, day22) (0, day23) (0, day24)] [(0, day30) (1, day31) (2, day32) (0, day33) (0, day34)]...
[ "Scan the source matrix and generate a result matrix, one-to-one:\nrandom_matrix = generate_random_matrix(...) # the way you want\nresult = []\nfor row in random_matrix:\n result_row = []\n for value in row:\n result_row.append((value, randomDate(...)))\n result.append(result_row)\nprint result # or whatever\...
[ 1, 0, 0 ]
[]
[]
[ "iterable_unpacking", "matrix", "python" ]
stackoverflow_0007654487_iterable_unpacking_matrix_python.txt
Q: Python yield generator function So I've got this ginormous humungous class, of which the only relevant code is: def get_col_is_numeric(self, col_name): "Returns an iterator with each cell length in the named column" min(self.get_col_iter_is_numeric(col_name)) ... and I loaded some values into ...
Python yield generator function
So I've got this ginormous humungous class, of which the only relevant code is: def get_col_is_numeric(self, col_name): "Returns an iterator with each cell length in the named column" min(self.get_col_iter_is_numeric(col_name)) ... and I loaded some values into the dict from a csv file. Problem is ...
[ "get_col_is_numeric is missing a return statement so it returns None.\nAlso next time, try just posting the actual functions/methods involved rather then the whole class.\n" ]
[ 7 ]
[]
[]
[ "generator", "python", "yield", "yield_keyword", "yield_return" ]
stackoverflow_0007654660_generator_python_yield_yield_keyword_yield_return.txt
Q: Get data back from Jython scripts using JSR-223 I am using Jython 2.5.1 with JSR-223 (i.e. javax.script package) and I expect the last line of the Python script to be returned. For example, after evaluating this script: class Multiplier: def multiply(self, x, y): return x * y Multiplier().multiply(5, 7) I...
Get data back from Jython scripts using JSR-223
I am using Jython 2.5.1 with JSR-223 (i.e. javax.script package) and I expect the last line of the Python script to be returned. For example, after evaluating this script: class Multiplier: def multiply(self, x, y): return x * y Multiplier().multiply(5, 7) I should get back 35, but I get null instead. In other...
[ "This is a Python language issue more than a Jython or JSR 223 issue. Python differentiates between expressions (which have values) and statements (which don't). The script you're passing is a statement. If you passed an expression, it'd have a value.\nThe reason you're seeing something different with Ruby and J...
[ 5, 3, 2 ]
[]
[]
[ "java", "jsr223", "jython", "python" ]
stackoverflow_0001887320_java_jsr223_jython_python.txt
Q: How to get arguments list of a built-in Python class constructor? I'm trying to use the inspect module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood. I'm using Python 2.7 and tried with Python 3.2. This is working: >>> import inspect >>> class C: ... def __init__(self...
How to get arguments list of a built-in Python class constructor?
I'm trying to use the inspect module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood. I'm using Python 2.7 and tried with Python 3.2. This is working: >>> import inspect >>> class C: ... def __init__(self,a,b=4): ... self.sum = a + b ... >>> inspect.getargspec(C.__i...
[ "There is no way to get them, as they are a property of the C code behind the function, and not of the function itself.\n", "Note that this code works just fine on PyPy (where there is no really distinction between those two function types).\n(pypy)fijal@helmut:~$ python\nclass C(Python 2.7.1 (f1e873c5533d, Sep 1...
[ 9, 8 ]
[]
[]
[ "asdl", "inspection", "python", "reflection" ]
stackoverflow_0007628081_asdl_inspection_python_reflection.txt
Q: Pyramid 1.2 on Google App Engine causes import error I'm trying to run Pyramid on GAE by following the steps outlined here. Everything works fine on dev server, but when deployed to Google's servers, the following error occurs: <type 'exceptions.ImportError'>: cannot import name BaseRequest Traceback (most recent ...
Pyramid 1.2 on Google App Engine causes import error
I'm trying to run Pyramid on GAE by following the steps outlined here. Everything works fine on dev server, but when deployed to Google's servers, the following error occurs: <type 'exceptions.ImportError'>: cannot import name BaseRequest Traceback (most recent call last): File "/base/data/home/apps/.../0-0-1.3536344...
[ "It's not really a solution, per-se, but we're about to release the new Python runtime, Python 2.7, which includes updated versions of libraries, including webob 1.1. Perhaps you could target your app against that, instead of against the 2.5 runtime?\n", "Apart from the runtime update, I found another workaround....
[ 1, 1 ]
[]
[]
[ "google_app_engine", "pylons", "pyramid", "python" ]
stackoverflow_0007616580_google_app_engine_pylons_pyramid_python.txt
Q: Best Python Module for HTML parsing I have a website updater(people can update content(text) not the look of the website) which has HTML, javascript as the front end languages & python as the back-end/server side. I am finding that updating HTML is very difficult from the front end because when I grab the updated ...
Best Python Module for HTML parsing
I have a website updater(people can update content(text) not the look of the website) which has HTML, javascript as the front end languages & python as the back-end/server side. I am finding that updating HTML is very difficult from the front end because when I grab the updated HTML by ele.innerHTML or $(ele).html() gi...
[ "For parsing HTML I would suggest you take a look at Beautiful Soup. It's pretty powerful and can deal with some messed up markup as well.\nhttp://www.crummy.com/software/BeautifulSoup/\nCheck this out and see if it helps you out! Hope it does.\n", "I've been using lxml ( http://lxml.de/lxmlhtml.html ). It relat...
[ 8, 6 ]
[]
[]
[ "html", "html_parsing", "python" ]
stackoverflow_0007655042_html_html_parsing_python.txt
Q: TypeError when retrieving random digits I am trying to generate a random three digit extension: >>> ''.join(str(x) for x in random.sample(range(1,10),3)) It works in the prompt. However, when I run the program, it raises a TypeError: str object is not callable. This is the line that I have: filename = hashli...
TypeError when retrieving random digits
I am trying to generate a random three digit extension: >>> ''.join(str(x) for x in random.sample(range(1,10),3)) It works in the prompt. However, when I run the program, it raises a TypeError: str object is not callable. This is the line that I have: filename = hashlib.md5(imagefile.getvalue()).hexdigest() + ...
[ "You have replaced the global name str, which normally refers to the string type, with something else (most likely, a variable containing a string of little importance). Python does not generally treat these sorts of things as keywords (in Python 3.x, True and False have become keywords, where they were just global...
[ 6, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007655207_python.txt
Q: Regex match in urls.py for django app view The url im trying to match is: http://domain/games/getdata/genres/ This request is made via ajax to get some JSON data from a external api. I cant get it to make a match; keeps going to a middleware handler i have set up. Im sure this is fix is pretty obvious, but ive be...
Regex match in urls.py for django app view
The url im trying to match is: http://domain/games/getdata/genres/ This request is made via ajax to get some JSON data from a external api. I cant get it to make a match; keeps going to a middleware handler i have set up. Im sure this is fix is pretty obvious, but ive been staring at this way too long. urls.py: from ...
[ "I'm not sure I understood you correctly... are you saying your view doesn't get called? \nIf you've set up some middleware classes, it's only normal that the flow that handles a request passes through the middleware before (and after), it gets to your view.\nHere's some documentation:\nhttps://docs.djangoproject.c...
[ 1, 1, 0 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0007654828_django_python_regex.txt