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 is this regular expression not working ({m, n})? Trying to understand regular expressions and I am on the repetitions part: {m, n}. I have this code: >>> p = re.compile('a{1}b{1, 3}') >>> p.match('ab') >>> p.match('abbb') As you can see both the strings are not matching the pattern. Why is this happening? A...
Why is this regular expression not working ({m, n})?
Trying to understand regular expressions and I am on the repetitions part: {m, n}. I have this code: >>> p = re.compile('a{1}b{1, 3}') >>> p.match('ab') >>> p.match('abbb') As you can see both the strings are not matching the pattern. Why is this happening?
[ "You shouldn't put a space after the comma, and the {1} is redundant.\n", "Try \np = re.compile('a{1}b{1,3}')\n\n...and mind the space.\n", "Remove the extra whitespace in b.\nChange:\np = re.compile('a{1}b{1, 3}')\n\nto:\np = re.compile('a{1}b{1,3}')\n ^ # no whitespace\n\nand all shou...
[ 9, 6, 4, 4, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004978765_python_regex.txt
Q: Chaining multiple mapreduce tasks in Hadoop streaming I am in scenario where I have two mapreduce jobs. I am more comfortable with python and planning to use it for writing mapreduce scripts and use hadoop streaming for the same. is there a convenient to chain both the jobs following form when hadoop streaming is ...
Chaining multiple mapreduce tasks in Hadoop streaming
I am in scenario where I have two mapreduce jobs. I am more comfortable with python and planning to use it for writing mapreduce scripts and use hadoop streaming for the same. is there a convenient to chain both the jobs following form when hadoop streaming is used? Map1 -> Reduce1 -> Map2 -> Reduce2 I've heard a lot o...
[ "Here is a great blog post on how to use Cascading and Streaming. \nhttp://www.xcombinator.com/2009/11/18/how-to-use-cascading-with-hadoop-streaming/\nThe value here is you can mix java (Cascading query flows) with your custom streaming operations in the same app. I find this much less brittle than other methods.\n...
[ 4, 3, 1, 1 ]
[]
[]
[ "hadoop", "hadoop_plugins", "mapreduce", "python" ]
stackoverflow_0004626356_hadoop_hadoop_plugins_mapreduce_python.txt
Q: getting 500 internal server error with django on dreamhost so i'm not sure what exactly is going on here, i'm a bit of a newbie. so i'm going to walk you through what i've done so far. i set up a django project using the automated dreamhost django setup script. then, following a tutorial, i created an app in th...
getting 500 internal server error with django on dreamhost
so i'm not sure what exactly is going on here, i'm a bit of a newbie. so i'm going to walk you through what i've done so far. i set up a django project using the automated dreamhost django setup script. then, following a tutorial, i created an app in the parent directory of my project, and then created a few models ...
[ "It sounds like your python path might be wrong. You placed your Django app(s) in the parent directory; that means your parent directory needs to be in your python path. If you're using mod_wsgi:\nWSGIPythonPath /path/to/parent/dir:/path/to/parent/dir/YourProjectDir:/other/paths:\n\nThat's assuming /path/to/parent/...
[ 0, 0 ]
[]
[]
[ "django", "dreamhost", "hosting", "python" ]
stackoverflow_0004978551_django_dreamhost_hosting_python.txt
Q: Generic test automation framework for Python I'm working as a system administrator/infrastructure engineer, and sometimes I am wasting my time on checking if everything working properly after infrastructure changes. I want to write some tests, such as: Download some CSS/JavaScript code from a website Login to web...
Generic test automation framework for Python
I'm working as a system administrator/infrastructure engineer, and sometimes I am wasting my time on checking if everything working properly after infrastructure changes. I want to write some tests, such as: Download some CSS/JavaScript code from a website Login to website Upload some file and try to download it Login...
[ "Robot Framework has many nice libraries that would definitely help you - so you don't have to reinvent the wheel. For example, Robot Framework integrates with the Selenium web testing tool.\nI think that from the tools that you mentioned Robot Framework is the most active project - py.test seems to be active also....
[ 7, 1 ]
[]
[]
[ "automated_tests", "frameworks", "python", "testing" ]
stackoverflow_0004980750_automated_tests_frameworks_python_testing.txt
Q: Cocotron with pyobjc? I'm in the planning stages of developing a cross platform (Mac & Windows) app. Performance is not an issue, and Python would be a good fit for the problem domain. I'm a Cocoa developer with pyojc experience. Cocotron looks appealing, but has anyone used Cocotron with pyojbc? If not suppose t...
Cocotron with pyobjc?
I'm in the planning stages of developing a cross platform (Mac & Windows) app. Performance is not an issue, and Python would be a good fit for the problem domain. I'm a Cocoa developer with pyojc experience. Cocotron looks appealing, but has anyone used Cocotron with pyojbc? If not suppose the alternatives are either ...
[ "If the performance is not an issue, then why not to use just python without obj-c? wxPython will provide native look and feel on both Windows, Mac OS and Linux. And it's easy to make distributions for different OSes with py2exe and py2app (and linux users have python anyway :-).\nBTW: there is a great example of w...
[ 1 ]
[]
[]
[ "cocoa", "cocotron", "pyobjc", "python", "windows" ]
stackoverflow_0004978575_cocoa_cocotron_pyobjc_python_windows.txt
Q: How to pass data from Java applet to client side python script? I have a python script which does various number-crunching jobs and now need to put a graphical front-end on it (a molecular editor in which a user draws a compound to pass to the script) to allow others in the lab to use it more easily. The availabl...
How to pass data from Java applet to client side python script?
I have a python script which does various number-crunching jobs and now need to put a graphical front-end on it (a molecular editor in which a user draws a compound to pass to the script) to allow others in the lab to use it more easily. The available editors are Java applets, standalone Java or written in JavaScript....
[ "If you go for JavaScript I'm assuming it would run in a browser and therefore to communicate with anything else it would make HTTP requests (e.g. POST or GET URLs), so the client/server arrangement is unavoidable.\nTherefore you would need to turn your Python code into a web application, using something like Cherr...
[ 1, 0 ]
[]
[]
[ "java", "javascript", "python" ]
stackoverflow_0004980657_java_javascript_python.txt
Q: Analog of virtualrails.org for python Just met such great project - http://virtualrails.org Wondering are there somethigs similar for python/django development ? A: Turnkey has a large selection of images, including Django: http://www.turnkeylinux.org/django VirtualBox is the easiest way to use these images: htt...
Analog of virtualrails.org for python
Just met such great project - http://virtualrails.org Wondering are there somethigs similar for python/django development ?
[ "Turnkey has a large selection of images, including Django: http://www.turnkeylinux.org/django VirtualBox is the easiest way to use these images: http://www.turnkeylinux.org/docs/installation-appliances-virtualbox\n" ]
[ 1 ]
[]
[]
[ "django", "python", "ruby_on_rails" ]
stackoverflow_0004981086_django_python_ruby_on_rails.txt
Q: How can I add custom headers to emails sent through Appengine? Possible Duplicate: Is it possible to add headers to emails being sent by app-engine? I'm using Python. This documentation page: http://code.google.com/appengine/docs/python/mail/emailmessagefields.html doesn't have the answer. Does anyone know how t...
How can I add custom headers to emails sent through Appengine?
Possible Duplicate: Is it possible to add headers to emails being sent by app-engine? I'm using Python. This documentation page: http://code.google.com/appengine/docs/python/mail/emailmessagefields.html doesn't have the answer. Does anyone know how to do this? Thanks.
[ "from looking in appengine/api/mail.py\nmime_message = myMessage.to_mime_message()\nmime_message['message_id'] = 'myid'\n\n" ]
[ 0 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0004981057_email_google_app_engine_python.txt
Q: sorting list of indices How do I sort a list of indices by what they're pointing to in python? I have indices = list(range(len(mylist))) I want to sort the indices so that if a precedes b in indices then mylist[a] > mylist[b]. A: indicies.sort(lambda x,y:mylist[x]-mylist[y]) A: Also, let me add the following...
sorting list of indices
How do I sort a list of indices by what they're pointing to in python? I have indices = list(range(len(mylist))) I want to sort the indices so that if a precedes b in indices then mylist[a] > mylist[b].
[ "indicies.sort(lambda x,y:mylist[x]-mylist[y])\n\n", "Also, let me add the following snippet as an answer, using the information provided in your original question...\n\nI want to sort the indices so that if\n a precedes b in indices then mylist[a] > mylist[b].\n\n...and the additional info you have in your comm...
[ 3, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004963384_python_sorting.txt
Q: What's the best way to handle output redirection? I want my program by default to stdout, but give the option of writing it to a file. Should I create my own print function and call that testing that there is an output file or is there a better way? That seems inefficient to me, but every way I can think of calls ...
What's the best way to handle output redirection?
I want my program by default to stdout, but give the option of writing it to a file. Should I create my own print function and call that testing that there is an output file or is there a better way? That seems inefficient to me, but every way I can think of calls an additional if test for every print call. I know this...
[ "Just write to standard out using print. If the user wants to redirect the output to a file they can do that:\npython foo.py > output.txt\n\n", "Write to a file object, and when the program starts either have that object point to sys.stdout or to a file specified by the user. \nMark Byers' answer is more unix-li...
[ 4, 2, 1, 0, 0 ]
[ "My reaction would be to output to a temp file, then either dump that to stdio, or move it to where they requested. \n" ]
[ -1 ]
[ "python", "redirect" ]
stackoverflow_0004981444_python_redirect.txt
Q: Django: use render_to_response and set cookie Currently, I'm using render_to_response(template_name, locals(), context-etc..) Trying to set a cookie right now and I'm wondering if I can do it with render_to_response. All the examples I see are using HttpResponse object. They set the cookie in the response object, ...
Django: use render_to_response and set cookie
Currently, I'm using render_to_response(template_name, locals(), context-etc..) Trying to set a cookie right now and I'm wondering if I can do it with render_to_response. All the examples I see are using HttpResponse object. They set the cookie in the response object, like this response = HttpResponseObject(html) respo...
[ "Yes, not a problem. The principle is exactly the same.\nresponse = render_to_response(template_name, locals(), context-etc..)\nresponse.set_cookie(\"favorite_color\",request.GET[\"favorite_color\"])\nreturn response\n\n" ]
[ 25 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004981601_django_django_templates_python.txt
Q: how can I combine a switch-case and regex in Python I want to process a string by matching it with a sequence of regular expression. As I'm trying to avoid nested if-then, I'm thinking of switch-case. How can I write the following structure in Python? Thank you switch str: case match(regex1): # do someth...
how can I combine a switch-case and regex in Python
I want to process a string by matching it with a sequence of regular expression. As I'm trying to avoid nested if-then, I'm thinking of switch-case. How can I write the following structure in Python? Thank you switch str: case match(regex1): # do something case match(regex2): # do sth else I know P...
[ "First consider why there is no case statement in Python. So reset you brain and forget them. \nYou can use an object class, function decorators or use function dictionaries to achieve the same or better results. \nHere is a quick trivial example:\n#!/usr/bin/env python\nimport re\n\ndef hat(found):\n if found: ...
[ 9, 3, 1, 1, 1 ]
[]
[]
[ "python", "switch_statement" ]
stackoverflow_0004980146_python_switch_statement.txt
Q: Is it possible to add headers to emails being sent by app-engine? I'm currently putting the finishing touches to an application for a client, this application sends daily emails to subscribers, is it possible to add custom headers to the email so that certain variables can be tracked, like day number (X-Day-Number...
Is it possible to add headers to emails being sent by app-engine?
I'm currently putting the finishing touches to an application for a client, this application sends daily emails to subscribers, is it possible to add custom headers to the email so that certain variables can be tracked, like day number (X-Day-Number) etc...
[ "There isn't a documented way to do it. Perhaps you should suggest it on the issue tracker.\nhttp://code.google.com/p/googleappengine/issues/list\nOf course, if you're really determined, you can create your own email sending gateway on a more traditional server, and call its web service from App Engine.\n", "fro...
[ 3, 2 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002902721_email_google_app_engine_python.txt
Q: Piping very long string through pipe with python subprocess I would like to use python's subprocess library to deal with a string, process this string in a different program, then collect it and save it. Unfortunately, this string is very long (as in millions of characters long). So I have the following code segme...
Piping very long string through pipe with python subprocess
I would like to use python's subprocess library to deal with a string, process this string in a different program, then collect it and save it. Unfortunately, this string is very long (as in millions of characters long). So I have the following code segment set up: cmd = ['some command'] p1 = Popen(cmd, stdin=PIPE, std...
[ "broken pipe can also mean the child process died of other causes. Invalid input or out-of-memory could be culprits. Have you tried changing command to something like cat?\n", "If you are sending millions of characters through input, then something is clearly wrong with the architecture of the program. Normally u...
[ 4, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0004981742_python_subprocess.txt
Q: Where is the __builtin__ module in CPython I want to get the path and source code of the __builtin__ module, where can I get it? A: Latest (trunk) C sources of __builtin__ module: http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup A: The __builtin__ module is built-in, there is no Python ...
Where is the __builtin__ module in CPython
I want to get the path and source code of the __builtin__ module, where can I get it?
[ "Latest (trunk) C sources of __builtin__ module: http://svn.python.org/view/python/trunk/Python/bltinmodule.c?view=markup\n", "The __builtin__ module is built-in, there is no Python source for it. It's coded in C and included as part of the Python interpreter executable.\n", "You can't. it is built-in to the i...
[ 5, 2, 2 ]
[]
[]
[ "cpython", "python" ]
stackoverflow_0004981963_cpython_python.txt
Q: Python GQL query not working ID = int(data_key) results = db.GqlQuery("SELECT * FROM PatientMeds WHERE patientinfo_ID='ID'") where i have done wrong... Thanks.. A: Use a parameter (examples 1, 2): ID = int(data_key) results = db.GqlQuery("SELECT * FROM PatientMeds WHERE patientinfo_ID=:1", ID) # or resu...
Python GQL query not working
ID = int(data_key) results = db.GqlQuery("SELECT * FROM PatientMeds WHERE patientinfo_ID='ID'") where i have done wrong... Thanks..
[ "Use a parameter (examples 1, 2):\nID = int(data_key)\nresults = db.GqlQuery(\"SELECT * FROM PatientMeds WHERE patientinfo_ID=:1\", ID)\n# or\nresults = db.GqlQuery(\"SELECT * FROM PatientMeds WHERE patientinfo_ID=:id\", id=ID)\n\n", "You could also use the more \"Pythonic\" model API:\nfrom path.to.your.models i...
[ 8, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004954972_google_app_engine_python.txt
Q: When automatically importing modules from a subfolder, their imports fail I've read through a couple of similar questions, notably this one about imp.load_module which seems to be close to what I want, but I can't understand why I'm still getting ImportErrors. Here is my folder hierarchy: program\ __init__.py ...
When automatically importing modules from a subfolder, their imports fail
I've read through a couple of similar questions, notably this one about imp.load_module which seems to be close to what I want, but I can't understand why I'm still getting ImportErrors. Here is my folder hierarchy: program\ __init__.py main.py thirdparty\ __init__.py css\ __init__.py css.py ...
[ "Maybe you can solve this by changing the import to:\nfrom .utils import http\n\nOr by adding the folder you import to the Python Path:\nsys.path.append(os.path.join(root, source))\n\nWhen you import modules in thirdparty, the place Python looks for modules is still the main directory. The initial import works, bec...
[ 0 ]
[]
[]
[ "python", "python_import", "python_packaging", "relative_path" ]
stackoverflow_0004981902_python_python_import_python_packaging_relative_path.txt
Q: Extensible biased number generator - Python I am trying to get a random number generator that will be biased in that it takes a number, and prints a number that is likely to be close. Here's what I have now: def biasedRandom(rangen, rangex, target, biaslevel=1): if rangen > rangex: raise ValueError("Mi...
Extensible biased number generator - Python
I am trying to get a random number generator that will be biased in that it takes a number, and prints a number that is likely to be close. Here's what I have now: def biasedRandom(rangen, rangex, target, biaslevel=1): if rangen > rangex: raise ValueError("Min value is less than max value.") return ...
[ "raise exits the function - you do not need to follow raise with return\ntarget in range(lo, hi) is inefficient; why not lo <= target < hi?\nEdit:\nimport random\ndef biasedRandom(lo, hi, target, steps=1):\n if lo >= hi:\n raise ValueError(\"lo should be less than hi\")\n elif target < lo or target >= ...
[ 4, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0004982145_python_random.txt
Q: Parsing HTML in python3, re, html.parser, or something else? I'm trying to get a list of craigslist states and their associates urls. Don't worry, I have no intentions of spaming, if you're wondering what this is for see the * below. What I'm trying to extract begins the line after 'us states' and is the next 50 ...
Parsing HTML in python3, re, html.parser, or something else?
I'm trying to get a list of craigslist states and their associates urls. Don't worry, I have no intentions of spaming, if you're wondering what this is for see the * below. What I'm trying to extract begins the line after 'us states' and is the next 50 < li >'s. I read through html.parser's docs and it seemed too low ...
[ "There is xml.etree an XML Parser available in the Python Standard library itself. You should not using regex for parsing XMLs. Go the particular node where you find the information and extract the links from that.\n", "Use lxml.html. It's the best python html parser. It supports xpath!\n" ]
[ 4, 1 ]
[]
[]
[ "html", "parsing", "python", "regex" ]
stackoverflow_0004982270_html_parsing_python_regex.txt
Q: I found that I'm trying to write an web app behaves exactly like the django admin. What should I do? This may seem quite a weird question but I'm quite confused right now and don't know what to do. I'm working on an intranet web app using django. Soon I found that almost all features I need are done in django-admi...
I found that I'm trying to write an web app behaves exactly like the django admin. What should I do?
This may seem quite a weird question but I'm quite confused right now and don't know what to do. I'm working on an intranet web app using django. Soon I found that almost all features I need are done in django-admin, like adding and editing entries, view and filter items in a list view and so on. The missing parts can ...
[ "That depends on your motivation. If this is an exercise in sharpening yourself then I suggest reinventing it. Mainly because you learn so much in the process. If the main goal is just to have the functionality then use the django-admin and bolt on whatever you need that it lacks.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004982459_django_python.txt
Q: Python, extend/add field to tuple what it is the best way to accomplish the following, either subclassing tuple or some other trick? region = ( "buffer", "region" ) region.cmd = ( "kill", "mark" ) A: You can simply subclass tuple without modification and it will work. By subclassing a built-in class it gains t...
Python, extend/add field to tuple
what it is the best way to accomplish the following, either subclassing tuple or some other trick? region = ( "buffer", "region" ) region.cmd = ( "kill", "mark" )
[ "You can simply subclass tuple without modification and it will work. By subclassing a built-in class it gains the ability to have arbitrary properties assigned to it, like normal user-defined classes.\nclass Region(tuple):\n pass\n\nregion = Region(( \"buffer\", \"region\" ))\nregion.cmd = ( \"kill\", \"mark\" ...
[ 6, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004981881_python.txt
Q: What is wrong with the following Python code? Could any one help me to debug the following python code? code is shown here: #!/usr/bin/python # Filename: using_tuple.py zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional print('Number of animals in the zoo is', len(zoo)) new_zoo = ('m...
What is wrong with the following Python code?
Could any one help me to debug the following python code? code is shown here: #!/usr/bin/python # Filename: using_tuple.py zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional print('Number of animals in the zoo is', len(zoo)) new_zoo = ('monkey', 'camel') print('Number of cages in the new...
[ "Where do you combine old and new zoo?\nPossibilities:\n>>> new_zoo = ('monkey', 'camel', zoo)\n>>> new_zoo\n('monkey', 'camel', ('python', 'elephant', 'penguin'))\n>>> new_zoo = ('monkey', 'camel') + zoo\n>>> new_zoo\n('monkey', 'camel', 'python', 'elephant', 'penguin')\n\n", "Indexing in programming languages u...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004977662_python.txt
Q: How can I use a returned value to open up another instance of a class in Python? I am on exercise 43 doing some self-directed work in Learn Python The Hard Way. And I have designed the framework of a game spread out over two python files. The point of the exercise is that each "room" in the game has a different cl...
How can I use a returned value to open up another instance of a class in Python?
I am on exercise 43 doing some self-directed work in Learn Python The Hard Way. And I have designed the framework of a game spread out over two python files. The point of the exercise is that each "room" in the game has a different class. I have tried a number of things, but I cannot figure out how to use the returned ...
[ "Instead of returning a string try returning an object, ie\n if choice == \"car\":\n return CarRoom()\n\n", "\nIt might be a good idea to make a Room class, and derive your other rooms from it.\nThe Room base class can then have a class variable which automatically keeps track of all instantiated rooms....
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004982138_python.txt
Q: What unit is MongoDB's location indexing in? Meters? Miles? db.posts.ensureIndex({"loc":"2d"}) If I do that and query by it... What are the units? db.posts.find({"loc": {"$within": {"$center" : [ user_center, user_radius ] }}}) What if I want to find something 5 miles away, what would my radius be? A: your uni...
What unit is MongoDB's location indexing in? Meters? Miles?
db.posts.ensureIndex({"loc":"2d"}) If I do that and query by it... What are the units? db.posts.find({"loc": {"$within": {"$center" : [ user_center, user_radius ] }}}) What if I want to find something 5 miles away, what would my radius be?
[ "your unit is whatever you store there. If you store in degrees on a globe that will be your unit for a $within.\nIf you use degrees then the $within for 5 miles will be ~ 0.07 since a degree is 60 nautical miles.\n" ]
[ 1 ]
[]
[]
[ "database", "geolocation", "mongodb", "python" ]
stackoverflow_0004982550_database_geolocation_mongodb_python.txt
Q: I'm learning python and am interested in using it for web-scripting. What frameworkes are out there and do I need one? I've been learning python for use in ArcGIS and some other non-web applications. However, now that I've taken on building a personal website I am interested in using it for web development (as it ...
I'm learning python and am interested in using it for web-scripting. What frameworkes are out there and do I need one?
I've been learning python for use in ArcGIS and some other non-web applications. However, now that I've taken on building a personal website I am interested in using it for web development (as it is the only scripting language I currently know). I've noticed that there are a lot of these things called "frameworks", suc...
[ "The Python web frameworks have nothing to do with GUIs, and can all be used via the terminal. \nThe benefits of a framework, as you say, are all to do with making your life easier by supplying the components you need to build a website: the main ones are database interaction through an ORM, a templating system, an...
[ 2, 2, 1, 0 ]
[]
[]
[ "python", "web", "web_frameworks", "web_scripting" ]
stackoverflow_0004980756_python_web_web_frameworks_web_scripting.txt
Q: Using text in one file to search for match in second file I'm using python 2.6 on linux. I have two text files first.txt has a single string of text on each line. So it looks like lorem ipus asfd The second file doesn't quite have the same format. it would look more like this 1231 lorem 1311 assss 31 1 ...
Using text in one file to search for match in second file
I'm using python 2.6 on linux. I have two text files first.txt has a single string of text on each line. So it looks like lorem ipus asfd The second file doesn't quite have the same format. it would look more like this 1231 lorem 1311 assss 31 1 etc I want to take each line of text from first.txt and deter...
[ "My approach is this: Read the second file, convert it into lowercase and then create a list of the words it contains. Then convert this list into a set, for better performance with large files.\nThen go through each line in the first file, and if it (also converted to lowercase, and with extra whitespace removed) ...
[ 4, 1 ]
[]
[]
[ "python", "regex", "search", "string" ]
stackoverflow_0004982610_python_regex_search_string.txt
Q: How to define a C struct which contain a struct inside a Ctype python Hi I am learning python and using ctype to embedd 'C' in python. My query is- How to use C stru which again calling a stru inside into cytpe/python. typedef struct { struct *i, *j; BOOLEAN z; } foo; A: It's not entirely clear from ...
How to define a C struct which contain a struct inside a Ctype python
Hi I am learning python and using ctype to embedd 'C' in python. My query is- How to use C stru which again calling a stru inside into cytpe/python. typedef struct { struct *i, *j; BOOLEAN z; } foo;
[ "It's not entirely clear from your question, but it looks like you're trying to define a struct that contains a pointer to the same type. It's not immediately obvious how you would accomplish this in python, but you basically define your Structure, and then define the _fields_ attribute afterwards.\nThe ctype docs ...
[ 1 ]
[]
[]
[ "c", "ctype", "python" ]
stackoverflow_0004982735_c_ctype_python.txt
Q: Multiple versions (revisions) of objects with django treebeard MP_Node Tree I'm using Materialized Path tree (provided by django-treebeard) to create a tree structure ( https://bitbucket.org/hoverhell/xmppforum/src/27207da4a061/snapboard/models.py#cl-363 ). I'm trying to implement (recover) object (Post) editing t...
Multiple versions (revisions) of objects with django treebeard MP_Node Tree
I'm using Materialized Path tree (provided by django-treebeard) to create a tree structure ( https://bitbucket.org/hoverhell/xmppforum/src/27207da4a061/snapboard/models.py#cl-363 ). I'm trying to implement (recover) object (Post) editing that allows to view all previous revisions of the edited object. Question is, wher...
[ "After all, I've implemented it with model subclassing (which means almost-duplicate table structures), with base abstract model (which contains the primary data), MP_Tree subclass model (with latest versions in tree structure) with 'previous' as link to model with old revisions, which has 'previous' pointing to se...
[ 1 ]
[]
[]
[ "django", "django_treebeard", "python" ]
stackoverflow_0004870802_django_django_treebeard_python.txt
Q: how to convert 8-bit hebrew to utf-8 in python I have hebrew data such that \xe0 is the hebrew aleph, and wish to convert it into utf-8 A: In general in Python, if you have a byte string you need to use decode first to convert it to the internal representation, afterwards you can encode it to UTF-8. Of course, ...
how to convert 8-bit hebrew to utf-8 in python
I have hebrew data such that \xe0 is the hebrew aleph, and wish to convert it into utf-8
[ "In general in Python, if you have a byte string you need to use decode first to convert it to the internal representation, afterwards you can encode it to UTF-8. Of course, you need to know the coding of \\xe0 for this to work (I assume your character is encoded using ISO-8859-8):\n'\\xe0'.decode('iso-8859-8').en...
[ 7, 0 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0004982968_python_utf_8.txt
Q: Python - dividing a list-of-lists to groups Consider the following simplified case: lol = [['John','Polak',5,3,7,9], ['John','Polak',7,9,2,3], ['Mark','Eden' ,0,3,3,1], ['Mark','Eden' ,5,1,2,9]] What would be a pythonic and memory+speed efficient way to transform this list-of-lists to a list-...
Python - dividing a list-of-lists to groups
Consider the following simplified case: lol = [['John','Polak',5,3,7,9], ['John','Polak',7,9,2,3], ['Mark','Eden' ,0,3,3,1], ['Mark','Eden' ,5,1,2,9]] What would be a pythonic and memory+speed efficient way to transform this list-of-lists to a list-of-lists-of-lists based on the first two paramete...
[ "List:\nfrom itertools import groupby\nlolol = [list(grp) for (match, grp) in groupby(lol, lambda lst: lst[:2])]\n# [[['John', 'Polak', 5, 3, 7, 9], ['John', 'Polak', 7, 9, 2, 3]],\n# [['Mark', 'Eden', 0, 3, 3, 1], ['Mark', 'Eden', 5, 1, 2, 9]]]\n\nDictionary:\ndolol = dict((tuple(match), [x[2:] for x in grp]) for...
[ 6, 5, 0 ]
[]
[]
[ "list", "memory_efficient", "performance", "python" ]
stackoverflow_0004980414_list_memory_efficient_performance_python.txt
Q: restricting characters in a string in django I will like to find out how do i restrict the job.description, a string to a certain number of characters? (I want to limit it to 3 rows in my .html). template(.html) {{ job.description }} forms.py class Meta: model = Job models.py description = db.StringPro...
restricting characters in a string in django
I will like to find out how do i restrict the job.description, a string to a certain number of characters? (I want to limit it to 3 rows in my .html). template(.html) {{ job.description }} forms.py class Meta: model = Job models.py description = db.StringProperty(multiline=True, verbose_name='Description:')...
[ "There is no built-in filter to limit a string to a certain number of characters, but you can limit to a certain number of words:\n{{ job.description|truncatewords:20 }}\n\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#truncatewords\nIf you really want to restrict to a number of characte...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004982794_django_python.txt
Q: Python - skip outofbounds exceptions for the sake of clarity? Suppose you have to accomplish this quite generic task: Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of...
Python - skip outofbounds exceptions for the sake of clarity?
Suppose you have to accomplish this quite generic task: Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front. Now, as Python lists silently skip out of bounds excep...
[ "Yes, it is perfectly a good practice, if your requirement is exactly that. :) \n return 3 * string[:3]\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004983545_python.txt
Q: django manytomany and the modelform I am really new to django, and I have some questions about how django's M2M works and also how it works with the modelForm or the forms.Form am currently working on an application that contains the following models: class Agent(models.Model): user = models.ForeignKey(User) ...
django manytomany and the modelform
I am really new to django, and I have some questions about how django's M2M works and also how it works with the modelForm or the forms.Form am currently working on an application that contains the following models: class Agent(models.Model): user = models.ForeignKey(User) assigned_by = models.ForeignKey('self'...
[ "Question #1: you can specify an intermediate model for the M2M relationship using the through argument:\nclass Agent(models.Model):\n ...\n regions = models.ManyToManyField(Region, through='ARM2M')\n\n(See http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany)\nRegarding question #2,...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_orm", "python" ]
stackoverflow_0004983090_django_django_forms_django_orm_python.txt
Q: Python: How to create nested XML from a flat datastructure I would like to create nested XML (as a string) from a list of dicts with python: toc = [ {'entryno': 1, 'level': 1, 'pageno': 17, 'title': 'title a'}, {'entryno': 2, 'level': 2, 'pageno': 19, 'title': 'title b'}, {'entryno': 3, 'level': 1, 'pageno':...
Python: How to create nested XML from a flat datastructure
I would like to create nested XML (as a string) from a list of dicts with python: toc = [ {'entryno': 1, 'level': 1, 'pageno': 17, 'title': 'title a'}, {'entryno': 2, 'level': 2, 'pageno': 19, 'title': 'title b'}, {'entryno': 3, 'level': 1, 'pageno': 25, 'title': 'title c'},] level means nesting level and there ...
[ "Non-ugly solution using the ElementTree API. One implementation is included with Python, as xml.etree.[c]ElementTree. Another is lxml.etree, which provides more functionality, including pretty-printing the output.\n# import xml.etree.cElementTree as et\nimport lxml.etree as et\nimport sys\n\ntoc = [\n {'entryno':...
[ 4, 1, 0 ]
[]
[]
[ "python", "serialization", "xml" ]
stackoverflow_0004980161_python_serialization_xml.txt
Q: A create_or_get method in Django I was looking if Django had some kind of create_or_get method but it seems that it doesn't have one. What I'm looking for the method to is that if the record doesn't exist, it is created but if it exits, it is returned. I wrote one and here's what it looks like: def create_or_get(...
A create_or_get method in Django
I was looking if Django had some kind of create_or_get method but it seems that it doesn't have one. What I'm looking for the method to is that if the record doesn't exist, it is created but if it exits, it is returned. I wrote one and here's what it looks like: def create_or_get(self, url): try: return Ho...
[ "There is already get_or_create, to be used like:\nobj, created = MyModel.objects.get_or_create(keywordArguments)\n\n" ]
[ 11 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004983873_django_django_models_python.txt
Q: python: unicode problem I am trying to decode a string I took from file: file = open ("./Downloads/lamp-post.csv", 'r') data = file.readlines() data[0] '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00 \x00M\x00o\x00n\x0...
python: unicode problem
I am trying to decode a string I took from file: file = open ("./Downloads/lamp-post.csv", 'r') data = file.readlines() data[0] '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00 \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00 \x00...
[ "This looks like UTF-16 data. So try\ndata[0].rstrip(\"\\n\").decode(\"utf-16\")\n\nEdit (for your update): Try to decode the whole file at once, that is\ndata = open(...).read()\ndata.decode(\"utf-16\")\n\nThe problem is that the line breaks in UTF-16 are \"\\n\\x00\", but using readlines() will split at the \"\...
[ 19, 10, 3 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0004735566_python_unicode.txt
Q: IntelliJ IDEA: Python plugin does not highlight Python code I have some problems whith IntelliJ IDEA Python plugin. I've got a Java project with a few modules. And I want to add one module for Python tools-scripts which I use to generate some files. I downloaded and installed Python plugin (version 2.6.6.) for my...
IntelliJ IDEA: Python plugin does not highlight Python code
I have some problems whith IntelliJ IDEA Python plugin. I've got a Java project with a few modules. And I want to add one module for Python tools-scripts which I use to generate some files. I downloaded and installed Python plugin (version 2.6.6.) for my IDEA (10.0.2 Ultimate). Then I added Python SDK to the project a...
[ "See Settings | File Types, verify that .py extension is associated with Python file type.\n" ]
[ 13 ]
[]
[]
[ "intellij_idea", "python" ]
stackoverflow_0004983715_intellij_idea_python.txt
Q: Canonical/standard way of restricting threads in python I've written a script that walks through the files in some directory, starts a thread and does something to the files. Because these are lengthy, expensive operations, I restricted the number of threads to one less than the number of cpus found on the given m...
Canonical/standard way of restricting threads in python
I've written a script that walks through the files in some directory, starts a thread and does something to the files. Because these are lengthy, expensive operations, I restricted the number of threads to one less than the number of cpus found on the given machine I'm running it on. It then constantly checks for the n...
[ "Perhaps a thread pool implementation is what you want here?\nhttp://code.activestate.com/recipes/577187/\nIt would look something like that:\npool = ThreadPool(num_threads)\nfor obj in objects:\n pool.add_task(obj.do_stuff, [arg1, arg2])\npool.wait_completion() \n\n", "Even if you can't upgrade Python, you...
[ 2, 2, 0 ]
[]
[]
[ "concurrency", "python" ]
stackoverflow_0004983128_concurrency_python.txt
Q: Django ORM and templates, how do I view all of the variables available for a given QuerySet? I always have issues trying to figure out what the names of variables are available to use in a template. I'm wondering if there is something in the shell I can do to print out all objects available. Let's say for example ...
Django ORM and templates, how do I view all of the variables available for a given QuerySet?
I always have issues trying to figure out what the names of variables are available to use in a template. I'm wondering if there is something in the shell I can do to print out all objects available. Let's say for example you have two models: class Foo1(models.Model) id = models.Integer(primary_key=True) foo2 =...
[ "You should use:\nFoo.objects.values_list()\n\nin the view and pass the object as a list rather than as a queryset.\nAlso check out:\nFoo.objects.values()\n\n", "There's no need to guess. You should be able to find out from the code of the models themselves. \nIf for some odd reason you haven't got access to the ...
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004983975_django_django_templates_python.txt
Q: How to get raw request headers in django? How can I get raw request headers in django? I am aware of HttpRequest.META dictionary, this is not what I want, I just want the raw headers as string. Is there any way to get it? A: AFAIK, as of the existing django releases (tagged <=1.2.5), there isn't a way to get at ...
How to get raw request headers in django?
How can I get raw request headers in django? I am aware of HttpRequest.META dictionary, this is not what I want, I just want the raw headers as string. Is there any way to get it?
[ "AFAIK, as of the existing django releases (tagged <=1.2.5), there isn't a way to get at the raw HTTP headers from the request object.\nHowever, looking at the source in the dev trunk (R15523) for django.http.HttpRequests, the base class for the request object exposes a file-like interface which would suggest that ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004982887_django_python.txt
Q: Django: css referencing media in static files (django dev / 1.3 / static files) Like any other user of django user I serve static files. I've chosen to use django-staticfiles to be ready for django 1.3 which will basically integrate it into the core. My question is pretty simple really - this works great for pulli...
Django: css referencing media in static files (django dev / 1.3 / static files)
Like any other user of django user I serve static files. I've chosen to use django-staticfiles to be ready for django 1.3 which will basically integrate it into the core. My question is pretty simple really - this works great for pulling together multiple media sources and referencing them in a uniform way in django te...
[ "You said you had trouble with relative paths, but I don't understand exactly what you meant.\nI ran into the same issue, and I've used relative paths to solve it. The only thing to keep in mind is that when deploying the images need to (obviously) remain in the same path relative to the CSS files.\nMy setup in a n...
[ 19, 1 ]
[]
[]
[ "css", "django", "django_1.3", "html", "python" ]
stackoverflow_0004867037_css_django_django_1.3_html_python.txt
Q: Python interpreter path search order on windows Many applications include a python interpreter, so now when I try to run a program, Subversion's 2.5 interpreter is used to execute it. I've already changed environment path order, putting subversion's last. Now when I run python from command line, the 2.7 is run, bu...
Python interpreter path search order on windows
Many applications include a python interpreter, so now when I try to run a program, Subversion's 2.5 interpreter is used to execute it. I've already changed environment path order, putting subversion's last. Now when I run python from command line, the 2.7 is run, but when I pass the script's filename, version 2.5 seem...
[ "PYTHONHOME was set to Subversion's python path. \nSystem Properties>Advanced tab>Environment Variables\nSystem Variables\nDelete entry.\nI don't know yet if this causes problems for subversion.\n", "If you are having problems with PATH in windows, set the one you want to use at the start of the path variable. Pl...
[ 2, 0 ]
[]
[]
[ "interpreter", "path", "python" ]
stackoverflow_0004984124_interpreter_path_python.txt
Q: How to convert \xXY encoded characters to UTF-8 in Python? I have a text which contains characters such as "\xaf", "\xbe", which, as I understand it from this question, are ASCII encoded characters. I want to convert them in Python to their UTF-8 equivalents. The usual string.encode("utf-8") throws UnicodeDecodeE...
How to convert \xXY encoded characters to UTF-8 in Python?
I have a text which contains characters such as "\xaf", "\xbe", which, as I understand it from this question, are ASCII encoded characters. I want to convert them in Python to their UTF-8 equivalents. The usual string.encode("utf-8") throws UnicodeDecodeError. Is there some better way, e.g., with the codecs standard l...
[ ".encode is for converting a Unicode string (unicode in 2.x, str in 3.x) to a a byte string (str in 2.x, bytes in 3.x).\nIn 2.x, it's legal to call .encode on a str object. Python implicitly decodes the string to Unicode first: s.encode(e) works as if you had written s.decode(sys.getdefaultencoding()).encode(e).\n...
[ 3, 3, 2 ]
[]
[]
[ "character_encoding", "non_ascii_characters", "python", "unicode", "utf_8" ]
stackoverflow_0004736261_character_encoding_non_ascii_characters_python_unicode_utf_8.txt
Q: Can I use both pip and easy_install or do the conflict? I am currently using easy_install, but have been advised to use pip. Can I start using pip or will things conflict? A: There's no problem at all. The same happened to me and I have no regrets. Pip is indeed much better. I would also recommend virtualenv. He...
Can I use both pip and easy_install or do the conflict?
I am currently using easy_install, but have been advised to use pip. Can I start using pip or will things conflict?
[ "There's no problem at all. The same happened to me and I have no regrets. Pip is indeed much better. I would also recommend virtualenv. Here's a tutorial: http://iamzed.com/2009/05/07/a-primer-on-virtualenv/\n" ]
[ 3 ]
[]
[]
[ "easy_install", "pip", "python" ]
stackoverflow_0004984239_easy_install_pip_python.txt
Q: Python: access to iterator-object in for-loops I want to step the loop iterator explicitly inside the loop. Is there a 'nicer' way to do this than: idx = iter(range(0, 10)) for i in idx: print i if i == 5: print "consuming %i in step %i" % (next(idx), i) Edit: I wander if there is a way to get acces...
Python: access to iterator-object in for-loops
I want to step the loop iterator explicitly inside the loop. Is there a 'nicer' way to do this than: idx = iter(range(0, 10)) for i in idx: print i if i == 5: print "consuming %i in step %i" % (next(idx), i) Edit: I wander if there is a way to get access to the loop-iterator other than defining it explic...
[ "data = list(range(10))\n\nit = iter(data)\nfor i in it:\n if i==5:\n j = it.next()\n print \"Consuming {0},{1}\".format(i,j)\n else:\n print i\n\nresults in\n0\n1\n2\n3\n4\nConsuming 5,6\n7\n8\n9\n\n", "You could define a generator to yield elements from the iterator singly or in pairs. Thi...
[ 3, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0004983013_for_loop_python.txt
Q: Why circular referenced objects with __del__ defined are uncollectable in Python? Will it cause memory leak if they cannot be cleaned by GC? A: It's a standard issue with garbage collection. It's not about memory leaks, but about the circular references themselves, and about other kinds of resources managed by t...
Why circular referenced objects with __del__ defined are uncollectable in Python?
Will it cause memory leak if they cannot be cleaned by GC?
[ "It's a standard issue with garbage collection.\nIt's not about memory leaks, but about the circular references themselves, and about other kinds of resources managed by those objects that may need cleanup. The references create a dependency - you can't delete the referrer until all objects it references are delete...
[ 7, 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004984849_python.txt
Q: Questions about Django development on Mac OS X I'm new to Mac (as of yesterday), and I have Snow Leopard. I've just easy_install virtualenv, and it doesn't work. I read a couple other SO questions about the same exception I had, and it seems that I need XCode installed. Before I go down a rabbit hole, installing a...
Questions about Django development on Mac OS X
I'm new to Mac (as of yesterday), and I have Snow Leopard. I've just easy_install virtualenv, and it doesn't work. I read a couple other SO questions about the same exception I had, and it seems that I need XCode installed. Before I go down a rabbit hole, installing a 3.5Gb Apple-specific code library for something Pyt...
[ "You will need XCode, yes. You'll need it for any libraries that need compiling, apart from anything else.\nPlease don't install MacPorts, though, as recommended by titaniumdecoy. It tries to install its own versions of everything, which is unnecessarily confusing, and takes you out of the usual Mac development sta...
[ 9, 4, 1 ]
[]
[]
[ "django", "macos", "python" ]
stackoverflow_0004982967_django_macos_python.txt
Q: Ajax, content-type header and python When using python for web as opposed to PHP, you have to manually write this header: Content-type:text/html. If I want to change the inner HTML of an element with ajax, should my python script (requested by ajax) output the above header or just plain HTML as a response? A: Ev...
Ajax, content-type header and python
When using python for web as opposed to PHP, you have to manually write this header: Content-type:text/html. If I want to change the inner HTML of an element with ajax, should my python script (requested by ajax) output the above header or just plain HTML as a response?
[ "Every HTTP Response must include a Content-Type header. PHP happens to insert one by default. Whatever Python library you are using apparently doesn't. Therefore you need to provide one explicitly. \nThis leaves the question as \"Should a fragment of HTML be served as text/html?\"\nThe RFC says:\n\nThe text/html m...
[ 1 ]
[]
[]
[ "ajax", "header", "python" ]
stackoverflow_0004985299_ajax_header_python.txt
Q: Implementing MSNP15 in Python - 911 error but all tickets are correct I am working on implementing the MSNP15 protocol in Python. I have verified that my hashing and encryption functions are working (or at least, they match up with examples I found online), however I am always receiving a 911 error back from the s...
Implementing MSNP15 in Python - 911 error but all tickets are correct
I am working on implementing the MSNP15 protocol in Python. I have verified that my hashing and encryption functions are working (or at least, they match up with examples I found online), however I am always receiving a 911 error back from the server. Thanks for any help. Python code is as follows; msntest.py: import s...
[ "Modified your msntest.py a little and now it should work:\nimport socket\nimport httplib\nfrom encryption import GetSSOTicket\nimport re\nfrom xml.sax import saxutils\n\nusername = \"login@hotmail.com\"\npassword = \"password\"\n\ndef ReadAll(sock):\n data = \"\"\n while 1:\n try:\n r = soc...
[ 1 ]
[]
[]
[ "msn_messenger", "python" ]
stackoverflow_0004970279_msn_messenger_python.txt
Q: Build HTTP GET request with port number and parameters I am trying to do a very simple thing, build an URL for a get request that contains a port number and some parameters, as it follows http://localhost:8080/read?date=whatever I have tried several ways without success, it shouldn't be too difficult but i cannot ...
Build HTTP GET request with port number and parameters
I am trying to do a very simple thing, build an URL for a get request that contains a port number and some parameters, as it follows http://localhost:8080/read?date=whatever I have tried several ways without success, it shouldn't be too difficult but i cannot come up with a solution. I hope someone helps me, it would b...
[ "The previous answer was not to the question you actually asked. Try this:\nimport urllib\n\nmyPort = \"8080\"\nmyParameters = { \"date\" : \"whatever\", \"another_parameters\" : \"more_whatever\" }\n\nmyURL = \"http://localhost:%s/read?%s\" % (myPort, urllib.urlencode(myParameters)) \n\nBasically, urllib has a fu...
[ 12, 1 ]
[ "data = urllib2.urlopen(url).read()\n\n" ]
[ -3 ]
[ "get", "http", "python", "request" ]
stackoverflow_0004985118_get_http_python_request.txt
Q: Speed up writing to files I've profiled some legacy code I've inherited with cProfile. There were a bunch of changes I've already made that have helped (like using simplejson's C extensions!). Basically this script is exporting data from one system to an ASCII fixed-width file. Each row is a record, and it has ma...
Speed up writing to files
I've profiled some legacy code I've inherited with cProfile. There were a bunch of changes I've already made that have helped (like using simplejson's C extensions!). Basically this script is exporting data from one system to an ASCII fixed-width file. Each row is a record, and it has many values. Each line is 7158 ch...
[ "Actually, your problem is not that file.write() takes 20% of your time. Its that 80% of the time you aren't in file.write()!\nWriting to the disk is slow. There is really nothing you can do about it. It simply takes a very large amount of time to write stuff out to disk. There is almost nothing you can do to speed...
[ 35, 22, 1 ]
[]
[]
[ "file_io", "performance", "python" ]
stackoverflow_0004961589_file_io_performance_python.txt
Q: KeyError when adding a constraint in python-constraint I am making a function that takes in a list of drivers and passengers with their locations, and returns a list of allocations of passengers to drivers that maximise the number of passengers assigned to a driver, subject to the following constraints: A passeng...
KeyError when adding a constraint in python-constraint
I am making a function that takes in a list of drivers and passengers with their locations, and returns a list of allocations of passengers to drivers that maximise the number of passengers assigned to a driver, subject to the following constraints: A passenger can only be in one car The number of passengers assigned ...
[ "Your variables have the form (driver, passenger):\np = [(driver, passenger) for driver in drivers for passenger in passengers]\nself.problem.addVariables(p, [0,1])\n\nThe variables you give to addConstraint(), however, have the form (passenger, driver):\npassenger_set = [zip([e1]*len(drivers), drivers) for e1 in p...
[ 4 ]
[]
[]
[ "constraint_programming", "python" ]
stackoverflow_0004985347_constraint_programming_python.txt
Q: Reading non-uniform data from file into array with NumPy Suppose I have a text file that looks like this: 33 3 46 12 23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16 33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19 ...
Reading non-uniform data from file into array with NumPy
Suppose I have a text file that looks like this: 33 3 46 12 23 10 23 11 23 12 23 13 23 14 23 15 23 16 24 10 24 11 24 12 24 13 24 14 24 15 24 16 25 14 25 15 25 16 26 16 27 16 28 16 29 16 33 17 33 18 33 19 34 17 34 18 34 19 35 17 35 18 35 19 36 19 41 32 41 33 42 32 42 33 I would like to read each line into a...
[ "Here's a one-liner:\narrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]\n\narrays is a list of numpy arrays.\n", "for line in textfile:\n a = np.array([int(v) for v in line.strip().split(\" \")])\n # Work on your array\n\n", "You can also use numpy.fromstring()\nfor line in f...
[ 17, 6, 3, 2 ]
[]
[]
[ "file_io", "numpy", "python" ]
stackoverflow_0004974290_file_io_numpy_python.txt
Q: Multi-threaded web requests in python -- 'Name or service not known' I have a large scraping job to do -- most of the script's time is spent blocking due to a lot of network latency. I'm trying to multi-thread the script so I can make multiple requests simultaneously, but about 10% of my threads die with the foll...
Multi-threaded web requests in python -- 'Name or service not known'
I have a large scraping job to do -- most of the script's time is spent blocking due to a lot of network latency. I'm trying to multi-thread the script so I can make multiple requests simultaneously, but about 10% of my threads die with the following error URLError: <urlopen error [Errno -2] Name or service not known>...
[ "Suggestion: Try enabling a DNS cache in your system, such as nscd. This should eliminate DNS lookup problems if your scraper always makes requests to the same domain.\nMake sure that the file objects returned by urllib2.urlopen are properly closed after being read, in order to free resources. Otherwise, you may re...
[ 1 ]
[]
[]
[ "dns", "multiprocessing", "multithreading", "python", "urllib2" ]
stackoverflow_0004979883_dns_multiprocessing_multithreading_python_urllib2.txt
Q: SqlAlchemy - Filtering by field defined as a ForeignKey I am trying to get instances of a class filtered by a field which is a foreign key but when I try to do that, I always get all the entries in the database, instead of the ones that match the criterion. Let's say I have a couple of classes using declarative ba...
SqlAlchemy - Filtering by field defined as a ForeignKey
I am trying to get instances of a class filtered by a field which is a foreign key but when I try to do that, I always get all the entries in the database, instead of the ones that match the criterion. Let's say I have a couple of classes using declarative base in a simple relationship N:1. I have that modeled like: #!...
[ "For a simple query, you can just query directly:\nsession.query(WhateverClass).filter(WhateverClass._containerClassId == 5).all()\n\nFor more complex relationships, you need a join:\nsession.query(WhateverClass).join(ContainerClass).filter(ContainerClass.id == 5).all()\n\n" ]
[ 31 ]
[]
[]
[ "foreign_key_relationship", "python", "relational_database", "sqlalchemy" ]
stackoverflow_0004985762_foreign_key_relationship_python_relational_database_sqlalchemy.txt
Q: Management of photos for Django applications My application uses a photo slideshow(diaporama). In the back-end management I would provide the path to the folder that contains the photos. How can I handle the management of photos in Django? A: I would use Photologue: Features: Complete photo gallery solution Ma...
Management of photos for Django applications
My application uses a photo slideshow(diaporama). In the back-end management I would provide the path to the folder that contains the photos. How can I handle the management of photos in Django?
[ "I would use Photologue:\nFeatures:\n\nComplete photo gallery solution\nManipulation functionality\nFully inlcuded in Django Admin interface\n\n", "What about using the django filebrowser and reference your photos from the folders you upload to?\ndjango-filebrowser\n" ]
[ 4, 0 ]
[]
[]
[ "django", "photo_gallery", "python", "upload" ]
stackoverflow_0004886962_django_photo_gallery_python_upload.txt
Q: Remove first occurrence that matches criteria from a list Suppose I have a list of strings: first item second item # first commented item third item # second commented item How do I remove the first item that starts with # from the list? Expected result: first item second item third item # second commented item ...
Remove first occurrence that matches criteria from a list
Suppose I have a list of strings: first item second item # first commented item third item # second commented item How do I remove the first item that starts with # from the list? Expected result: first item second item third item # second commented item
[ ">>> items = [\"First\", \"Second\", \"# First\", \"Third\", \"# Second\"]\n>>> for e in items:\n... if e.startswith('#'):\n... items.remove(e)\n... break\n... \n>>> items\n['First', 'Second', 'Third', '# Second']\n\n", "items = [\"First\", \"Second\", \"# First\", \"Third\", \"# Secon...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004985964_python.txt
Q: How do I test if a variable that I declared in an inner block exists in the outer block? Given this sample Python code: for item in items: if somecondition(item): requireditem = item break # use item How can I know if I'm allowed to access requireditem after the loop? i.e. if somecondition(it...
How do I test if a variable that I declared in an inner block exists in the outer block?
Given this sample Python code: for item in items: if somecondition(item): requireditem = item break # use item How can I know if I'm allowed to access requireditem after the loop? i.e. if somecondition(item) was True for some item in the list. One solution might be: requireditem = None for item i...
[ "Are you doing anything else in the loop? Are you setting somevar to anything besides True? If not, perhaps this would be better:\nif any(somecondition(item) for item in items):\n # do something\n\nThere's no real need for a variable.\nFrom your edit:\nThere's still a better way to do this:\nrequired_items = [it...
[ 5, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004986145_python.txt
Q: Using django-taggit, is it possible to limit the tags to pre approved values? I have a question about the use of django-taggit. I have a UserProfile (which I attach using AUTH_PROFILE_MODULE in the settings file) in which I store a set of skills for tutors such as: , , etc. Then, when someone wants to request a ...
Using django-taggit, is it possible to limit the tags to pre approved values?
I have a question about the use of django-taggit. I have a UserProfile (which I attach using AUTH_PROFILE_MODULE in the settings file) in which I store a set of skills for tutors such as: , , etc. Then, when someone wants to request a tutoring session, they can write a description of what they want and place tags for...
[ "So you want a set of predefined tags and the Users as well as the TutoringSessions should relate to one or more of these tags. Thats (as far as I can see) what m2m-fields are made for.\nMaybe taggit has some usability advantages (I'm not familiar with it), but the functionality described here can be achieved with ...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004985449_django_django_models_python.txt
Q: PyQt4, QThread and opening big files without freezing the GUI I would like to ask how to read a big file from disk and maintain the PyQt4 UI responsive (not blocked). I had moved the load of the file to a QThread subclass but my GUI thread get freezed. Any suggestions? I think it must be something with the GIL but...
PyQt4, QThread and opening big files without freezing the GUI
I would like to ask how to read a big file from disk and maintain the PyQt4 UI responsive (not blocked). I had moved the load of the file to a QThread subclass but my GUI thread get freezed. Any suggestions? I think it must be something with the GIL but I don't know how to sort it? EDIT: I am using vtkGDCMImageReader f...
[ "I'm guessing you're directly calling the run to begin the thread. That would make the GUI freeze because you're not activating the thread.\nSo you'd be missing the start there, which would indirectly and properly call the run:\nthread = ReadThread()\nthread.begin()\n\nclass ReadThread(QThread): \n def __init__(...
[ 3, 2, 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0001773716_pyqt_python.txt
Q: Why won't my script write to a file? import time import traceback import sys import tools from BeautifulSoup import BeautifulSoup f = open("randomwords.txt","w") while 1: try: page = tools.download("http://wordnik.com/random") soup = BeautifulSoup(page) si = soup.find("h1") w =...
Why won't my script write to a file?
import time import traceback import sys import tools from BeautifulSoup import BeautifulSoup f = open("randomwords.txt","w") while 1: try: page = tools.download("http://wordnik.com/random") soup = BeautifulSoup(page) si = soup.find("h1") w = si.string print w f.write...
[ "You can never leave the while loop, hence the f.close() call will never be called and the stream buffer to the file will never be flushed.\nLet me explain a little bit further, in your exception catch statement you've included continue so there's no \"exit\" to the loop condition. Perhaps you should add some sort...
[ 7, 3, 1, 1 ]
[]
[]
[ "file", "linux", "python", "unix" ]
stackoverflow_0004986463_file_linux_python_unix.txt
Q: Python Modules not Being Found? I'm new to Python, trying to get to know how to properly set up a Module. I have the following: dir1 pack1.py dir2 pack2.py ...and of course in my directories I have __init__.py Now, I am trying to get pack2.py to be inherited from pack1.py Got the following...
Python Modules not Being Found?
I'm new to Python, trying to get to know how to properly set up a Module. I have the following: dir1 pack1.py dir2 pack2.py ...and of course in my directories I have __init__.py Now, I am trying to get pack2.py to be inherited from pack1.py Got the following: class Pack2(Pack1): def __repr_...
[ "Have you set your Python path? If you haven't then the Python interpreter is unlikely to be able to find all of your modules.\nEach script's directory is in the Python path, so modules can import other modules in the same, or lower directories. But modules that need to import things from parent directories need to...
[ 2, 2 ]
[]
[]
[ "inheritance", "module", "python" ]
stackoverflow_0004986555_inheritance_module_python.txt
Q: Alternative to virsh (libvirt) I am using virsh list to display the list of vms running on the computer. I want the information printed in the process in the form of a 2d array. One way to go about this is to have the output, use tokenizer and store it in the array. But is there some other way where I can get dire...
Alternative to virsh (libvirt)
I am using virsh list to display the list of vms running on the computer. I want the information printed in the process in the form of a 2d array. One way to go about this is to have the output, use tokenizer and store it in the array. But is there some other way where I can get directly this into the form of an array ...
[ "There are indeed libvirt Python API bindings.\nimport libvirt\n\nconn = libvirt.openReadOnly(None) # $LIBVIRT_DEFAULT_URI, or give a URI here\nassert conn, 'Failed to open connection'\n\nnames = conn.listDefinedDomains()\ndomains = map(conn.lookupByName, names)\n\nids = conn.listDomainsID()\nrunning = map(conn.lo...
[ 14 ]
[]
[]
[ "libvirt", "list", "python", "virtual_machine" ]
stackoverflow_0004986076_libvirt_list_python_virtual_machine.txt
Q: Using pickle for in-memory "transaction"? A user can perform an action, which may trigger dependent actions (which themselves may have dependent actions) and I want to be able to cancel the whole thing if the user cancels a dependent action. The typical way I've seen this done is some variant of an undo stack and ...
Using pickle for in-memory "transaction"?
A user can perform an action, which may trigger dependent actions (which themselves may have dependent actions) and I want to be able to cancel the whole thing if the user cancels a dependent action. The typical way I've seen this done is some variant of an undo stack and each action will need to know how to undo itsel...
[ "Well, as you mentioned the data design is loosely coupled, so you I don't think you need to pickle it if it's in memory. Just take a copy of all the relevant variables, and the transaction.abort() would just copy them back, and transaction.commit() would then just remove the copy of the data.\nThere are issues, bu...
[ 1, 1 ]
[]
[]
[ "pickle", "python", "transactions", "undo" ]
stackoverflow_0004986467_pickle_python_transactions_undo.txt
Q: Need help parsing html in python3, not well formed enough for xml.etree.ElementTree I keep getting mismatched tag errors all over the place. I'm not sure why exactly, it's the text on craigslist homepage which looks fine to me, but I haven't skimmed it thoroughly enough. Is there perhaps something more forgiving I...
Need help parsing html in python3, not well formed enough for xml.etree.ElementTree
I keep getting mismatched tag errors all over the place. I'm not sure why exactly, it's the text on craigslist homepage which looks fine to me, but I haven't skimmed it thoroughly enough. Is there perhaps something more forgiving I could use or is this my best bet for html parsing with the standard library?
[ "The mismatched tag errors are likely caused by mismatched tags. Browsers are famous for accepting sloppy html, and have made it easy for web page coders to write badly formed html, so there's a lot of it. THere's no reason to believe that creagslist should be immune to bad web page designers.\nYou need to use a...
[ 4, 1, 0 ]
[]
[]
[ "parsing", "python", "python_3.x", "xml.etree" ]
stackoverflow_0004983203_parsing_python_python_3.x_xml.etree.txt
Q: BeautifulSoup SoupStrainer strain html and pdf links What do I need to pass as a regex pattern to grab both html and pdfs from an HTML webpage? So far, what I have is below. I assumed that I needed to use an OR statement, but that didn't really work as expected. status, response = http.request("http://www.example....
BeautifulSoup SoupStrainer strain html and pdf links
What do I need to pass as a regex pattern to grab both html and pdfs from an HTML webpage? So far, what I have is below. I assumed that I needed to use an OR statement, but that didn't really work as expected. status, response = http.request("http://www.example.com") htmlandpdfonly=SoupStrainer('a', href=re.compile('ht...
[ "import re\nfrom BeautifulSoup import BeautifulSoup\n\n# find \".html\" or \".pdf\" in a string\nmatch = re.compile('\\.(html|pdf)')\n\n# parse page content\nstatus, response = http.request(\"http://www.example.com\")\npage = BeautifulSoup(response)\n\n# check links\nfor link in page.findAll('a'):\n try:\n ...
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "scripting" ]
stackoverflow_0004986385_beautifulsoup_python_scripting.txt
Q: Interpret strings as packed binary data, Python vs Java I'm struggling a bit with binary in Java and Python to translate a program In python when I execute the following commands, I've got >>> print ord(pack('>H', 32809)[0]) 128 >>> print ord(pack('>H', 32809)[1]) 41 In Java, I expect to have the same result whe...
Interpret strings as packed binary data, Python vs Java
I'm struggling a bit with binary in Java and Python to translate a program In python when I execute the following commands, I've got >>> print ord(pack('>H', 32809)[0]) 128 >>> print ord(pack('>H', 32809)[1]) 41 In Java, I expect to have the same result when I execute the following command, but it's not there: bsh % ...
[ "Byte in java is a signed data type - and yeah I never understood why they did that either. You'll need to use a short (well since all bit ops are used on ints anyhow, just use a int really) and ignore the higher 8bit (otherwise sign extension would be a problem)\n System.out.println(((short) ((32809 & 0xFF00) >> 8...
[ 2, 1, 0 ]
[]
[]
[ "binary", "byte", "java", "python", "struct" ]
stackoverflow_0004986273_binary_byte_java_python_struct.txt
Q: Parsing a Comma Delimited File With Python and adding currency fields I'm trying to use Python to parse a comma delimited file with a layout similar to this: AccountNumber,Invoice_Number,Gross_Amt,Adjustments,TotalDue "234","56787","19.37",,"19.37" "234","56788","204.76","-10.00","194.76" "234","56789","139.77",,...
Parsing a Comma Delimited File With Python and adding currency fields
I'm trying to use Python to parse a comma delimited file with a layout similar to this: AccountNumber,Invoice_Number,Gross_Amt,Adjustments,TotalDue "234","56787","19.37",,"19.37" "234","56788","204.76","-10.00","194.76" "234","56789","139.77",,"139.77" "567","12543","44.89","30.00","74.89" What I want to accomplish i...
[ "You could use itertools.groupby():\nimport csv\nfrom itertools import groupby\nfrom operator import itemgetter\n\nwith open(\"data.csv\", \"rb\") as f:\n next(f) # Skip header\n for account, lines in groupby(csv.reader(f), itemgetter(0)):\n gross_amount = 0.\n for line in lines:\n ...
[ 4, 2, 0 ]
[]
[]
[ "csv", "field", "python" ]
stackoverflow_0004986523_csv_field_python.txt
Q: Why is this string always the highest possible number if month == 1 or 10: month1 = 0 if month == 2 or 3 or 11: month1 = 3 if month == 4 or 7: month1 = 6 if month == 5: month1 = 1 if month == 6: month1 = 4 if month == 8: month1 = 2 if month == 9 or 12: month1 = 5 This code always retur...
Why is this string always the highest possible number
if month == 1 or 10: month1 = 0 if month == 2 or 3 or 11: month1 = 3 if month == 4 or 7: month1 = 6 if month == 5: month1 = 1 if month == 6: month1 = 4 if month == 8: month1 = 2 if month == 9 or 12: month1 = 5 This code always returns month1 equal to 5. I'm quite new at programming, what am...
[ "EDIT: I first gave the wrong reason why this is not working. As others have pointed out,\nif month == 1 or 10:\n # ...\n\nis equivalent to\nif (month == 1) or 10:\n # ...\n\nSo ... always gets executed.\nYou could use\nif month in (1, 10):\n month1 = 0\n\nor even better\na = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0...
[ 7, 5, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004986756_python.txt
Q: django-photologue: How to scale image to box and fill background I´m using django-photologue (with 1pinax) and want to scale images to a box (100px x 100px). Portrait images should be scaled to height 100px and the width should be filled with a color. A: You can use PIL with a transformation matrix. For example,...
django-photologue: How to scale image to box and fill background
I´m using django-photologue (with 1pinax) and want to scale images to a box (100px x 100px). Portrait images should be scaled to height 100px and the width should be filled with a color.
[ "You can use PIL with a transformation matrix. For example, the following \nfunction resize and crop in a single operation. Personally I prefer to crop \nrather than fill it with a color, but you can adjust it to your needs.\ndef resize_and_crop(im, mask_width=1000, mask_height=1000):\n width, height = im.size\n...
[ 2 ]
[]
[]
[ "django", "pinax", "python", "python_imaging_library" ]
stackoverflow_0004986320_django_pinax_python_python_imaging_library.txt
Q: Question about Django's feed framework I'm trying to setup a feed for my app, but I'm a little confused. I'm aiming for something like the one on bitbucket/github's dashboard. So my user creates lists, and the lists will have items. Users can also follow other users and their lists. I want my feed to show: The a...
Question about Django's feed framework
I'm trying to setup a feed for my app, but I'm a little confused. I'm aiming for something like the one on bitbucket/github's dashboard. So my user creates lists, and the lists will have items. Users can also follow other users and their lists. I want my feed to show: The activities for the user on his lists The acti...
[ "The Django Syndication Framework focuses on providing RSS (or other syndication format) feeds. Feeds are usually just an XML document that provide the fields required for the format involved. The framework does not include any kind of feed reader, which is what the front-end to githubs dashboard is.\nI believe you...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004985331_django_python.txt
Q: Use 1 out of 2 returned values as string divmod(X, Y) returns (A, B) How would I turn either A or B into a string? EDIT: to clarify, I'd like to use them 1 at a time :) A: If you'd like to randomly select one or the other: import random str(random.choice(divmod(X,Y))) A: Are you looking for str(divmod(x, y)[0...
Use 1 out of 2 returned values as string
divmod(X, Y) returns (A, B) How would I turn either A or B into a string? EDIT: to clarify, I'd like to use them 1 at a time :)
[ "If you'd like to randomly select one or the other:\nimport random\nstr(random.choice(divmod(X,Y)))\n\n", "Are you looking for\nstr(divmod(x, y)[0])\n\nand\nstr(divmod(x, y)[1])\n\nrespectively?\nYou can also write\na, b = divmod(x, y)\nstr(a)\nstr(b)\n\n(Of course you should do something with str(a) instead of s...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004986906_python.txt
Q: Is ipython a replacement or it works side by side with regular python? Is ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will use? A: Is ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will ...
Is ipython a replacement or it works side by side with regular python?
Is ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will use?
[ "\nIs ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will use?\n\nYes. It is an advanced interactive shell and an environment for parallel computing (but most people only use it as an interactive shell).\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004986938_python.txt
Q: What is the most efficient way to traverse a tree in Python? Assuming I have a list of objects that have the following fields parent value and this defines a tree structure, similar to a directory tree. I want to traverse the list in a pre-order fashion. What's the most efficient way? Normally, in other (more impe...
What is the most efficient way to traverse a tree in Python?
Assuming I have a list of objects that have the following fields parent value and this defines a tree structure, similar to a directory tree. I want to traverse the list in a pre-order fashion. What's the most efficient way? Normally, in other (more imperative) languages I would iterate the values, finding the ones wit...
[ "I would first create a more suitable data structure -- capturing the link from a parent to its children:\nchildren = {}\nfor obj in tree:\n children.setdefault(obj.parent, []).append(obj)\n\ndef preorder(root, children):\n yield root.value\n for child in children.get(root, []):\n for value in preor...
[ 8 ]
[]
[]
[ "python", "traversal", "tree" ]
stackoverflow_0004986988_python_traversal_tree.txt
Q: Python PIL image reproduction I am new to PIL and Python and I have a question related to the API. I have an Image img = Image.new('RGB', (1, 2)) And I have a list of tuples x = [(255, 255, 255), (255, 255, 255)] I do img.putdata(x) and img.save('C:\\somename.jpeg') Later on when I reload the Image and do img2 =...
Python PIL image reproduction
I am new to PIL and Python and I have a question related to the API. I have an Image img = Image.new('RGB', (1, 2)) And I have a list of tuples x = [(255, 255, 255), (255, 255, 255)] I do img.putdata(x) and img.save('C:\\somename.jpeg') Later on when I reload the Image and do img2 = Image.open('C:\\somename.jpeg') y...
[ "jpeg is a lossy compression format and doesn't guarantee pixel by pixel reproduction. Try saving the image in a lossless format.\n" ]
[ 9 ]
[]
[]
[ "image", "image_processing", "python", "python_imaging_library" ]
stackoverflow_0004987070_image_image_processing_python_python_imaging_library.txt
Q: Subprocess Popen invalid argument/broken pipe while communicating to C program I have this code All the needed libraries are imported class VERTEX(Structure): _fields_ = [("index", c_int), ("x", c_float), ("y", c_float)] Other stuff This create and array from a list of vertex def writelis...
Subprocess Popen invalid argument/broken pipe while communicating to C program
I have this code All the needed libraries are imported class VERTEX(Structure): _fields_ = [("index", c_int), ("x", c_float), ("y", c_float)] Other stuff This create and array from a list of vertex def writelist_buf(size, nomeID): Nvert_VERTEX_Array_Type = VERTEX * len(bpy.data.objects[nomeI...
[ "From your comments I understand that you pass millions of items hundreds of times to a C program. The approach below (pipe input using subprocess) might be too slow in your case. Possible alternatives could be to write a C extension (e.g., using Cython) or to use ctypes to call C functions directly. You could ask...
[ 2 ]
[]
[]
[ "arrays", "pipe", "python", "subprocess" ]
stackoverflow_0004979421_arrays_pipe_python_subprocess.txt
Q: virtualenv only creates /lib/Python2.6 when I also have Python2.7 (OS X) I installed virtualenv on my new MacBook Pro (first time Mac user) before I did anything else (probably a bad idea). When I create an env it contains /lib/Python2.6 inside of it. Afterward I installed Python2.7, but it still only includes a P...
virtualenv only creates /lib/Python2.6 when I also have Python2.7 (OS X)
I installed virtualenv on my new MacBook Pro (first time Mac user) before I did anything else (probably a bad idea). When I create an env it contains /lib/Python2.6 inside of it. Afterward I installed Python2.7, but it still only includes a Python2.6 folder in lib, so I assume something is messed up. Note: If I go to t...
[ "virtualenv foo_env --python=Python2.7\n\nWhen you pass the python argument, it sets up the bin and lib for that version (assuming you have that version installed, of course).\n" ]
[ 4 ]
[ "This does not answer your question, but I have found the easiest way to get multiple versions of Python up and running on OS X is to use macports. For major tools like PIP and VirtualEnv, macports tends to have the latest versions and it manages everything fairly well. \nThen you can install a PIP specific to each...
[ -1 ]
[ "easy_install", "homebrew", "pip", "python", "virtualenv" ]
stackoverflow_0004986666_easy_install_homebrew_pip_python_virtualenv.txt
Q: Step by step setting up python with pip and virtualenv? Are there any good step by step tutorials on setting up a Mac to use python, pip and virtualenv setup? A: Download and install the Python 2.7.1 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6) or Python 2.7.1 Mac OS X 32-bit i386/PPC Install...
Step by step setting up python with pip and virtualenv?
Are there any good step by step tutorials on setting up a Mac to use python, pip and virtualenv setup?
[ "Download and install the Python 2.7.1 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6) or Python 2.7.1 Mac OS X 32-bit i386/PPC Installer (for Mac OS X 10.3 through 10.6).\nInstructions for installing virtualenv and pip on OS X\nThis is how I installed virtualenv and pip on OS X:\ncurl -O http://pe...
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004986896_python.txt
Q: PyQt4: How to specify the length and width of the squares of the QGridLayout I'm wondering about the length and width of the row in PyQt4 and can only find methods to ask the number of them, or to set the geometry of the whole layout but not to see or specify the length of each square. I have conceptualized my dra...
PyQt4: How to specify the length and width of the squares of the QGridLayout
I'm wondering about the length and width of the row in PyQt4 and can only find methods to ask the number of them, or to set the geometry of the whole layout but not to see or specify the length of each square. I have conceptualized my draft as to accomodate as 125x125 grid. On a separate but not completly unrelated, is...
[ "The purpose of Layouts is to arrange them with respect to each other.\nIf you want to have fixed widget sizes and position, you can position them yourself, manually:\nw = QWidget()\nw.resize(800, 800)\n\ni = QWidget(w)\ni.move(200, 200)\ni.setFixedSize(400, 400)\n#alternatively: i.setGeometry(200, 200, 400, 400)\n...
[ 2 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0004987383_pyqt4_python.txt
Q: Inside a decorator-class, access instance of the class which contains the decorated method I have the following decorator, which saves a configuration file after a method decorated with @saveconfig is called: class saveconfig(object): def __init__(self, f): self.f = f def __call__(self, *args): ...
Inside a decorator-class, access instance of the class which contains the decorated method
I have the following decorator, which saves a configuration file after a method decorated with @saveconfig is called: class saveconfig(object): def __init__(self, f): self.f = f def __call__(self, *args): self.f(object, *args) # Here i want to access "cfg" defined in pbtools pri...
[ "You have to make your decorator class behave as a descriptor to be able to access the instance:\nclass saveconfig(object):\n def __init__(self, f):\n self.f = f\n\n def __get__(self, instance, owner):\n def wrapper(*args):\n print \"Saving configuration\"\n print instance....
[ 11, 4, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0004987471_decorator_python.txt
Q: reading specific lines from a file What's the best way of reading only the specific lines (based on matching text) from a file? This is what I'm doing now: match_txt = "lhcb" for inFile in os.listdir('.'): readFile = open(inFile, 'r') lines = readFile.readlines() readFile.close() for line in lines...
reading specific lines from a file
What's the best way of reading only the specific lines (based on matching text) from a file? This is what I'm doing now: match_txt = "lhcb" for inFile in os.listdir('.'): readFile = open(inFile, 'r') lines = readFile.readlines() readFile.close() for line in lines: if line.find(match_txt)==0: ...
[ "To do it without loading the whole file into memory, just iterate over the file:\nmatch_txt = \"lhcb\"\nfor file_name in os.listdir('.'):\n with open(file_name) as f:\n for line in f:\n if line.startswith(match_txt):\n #< do stuff here >\n\nIf you want to check for match_txt any...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004987598_python.txt
Q: What's a safe way to do one-off initialization in Django/mod_wsgi? I'm building a Django app that is designed to be multithreaded but reside in a single process running under mod_wsgi. At start of day I need to do various, possibly-lengthy, initialization tasks such as loading a cache of data from the database in...
What's a safe way to do one-off initialization in Django/mod_wsgi?
I'm building a Django app that is designed to be multithreaded but reside in a single process running under mod_wsgi. At start of day I need to do various, possibly-lengthy, initialization tasks such as loading a cache of data from the database into a quick lookup dict. I need the intialization to run exactly once be...
[ "I have my initialization code in a middleware that is called when the first request is served.\nAfter the initialization is done, you can raise a MiddlewareNotinuse exception, which causes Django not to execute that middleware again.\nRemember that because of the way apache and http work, no code will be executed ...
[ 2, 0, 0 ]
[]
[]
[ "django", "initialization", "mod_wsgi", "multithreading", "python" ]
stackoverflow_0004986986_django_initialization_mod_wsgi_multithreading_python.txt
Q: Google App Engine Appstats Is it possible to use the data provided by Appstats inside my code? I want to get the RPC Total and Grand Total values of each of my task. Is there a way to do this? A: It's certainly possible, but you'll need to reach into the innards of appstats to do so - see the source code. It's p...
Google App Engine Appstats
Is it possible to use the data provided by Appstats inside my code? I want to get the RPC Total and Grand Total values of each of my task. Is there a way to do this?
[ "It's certainly possible, but you'll need to reach into the innards of appstats to do so - see the source code. It's probably not a good idea, though. If you need these measurements, you should probably learn from the appstats source and instrument your code yourself.\n" ]
[ 1 ]
[]
[]
[ "appstats", "google_app_engine", "python" ]
stackoverflow_0004982014_appstats_google_app_engine_python.txt
Q: Installed pip, but can't find where the virtualenvwrapper_bashrc How can I find out where the virtualenvwrapper_bashrc file is? I'm looking in: /System/Library/Frameworks/Python.framework/Versions/2.6/bin But I don't see it? A: You say that you installed pip, but you don't say whether or not you installed virtu...
Installed pip, but can't find where the virtualenvwrapper_bashrc
How can I find out where the virtualenvwrapper_bashrc file is? I'm looking in: /System/Library/Frameworks/Python.framework/Versions/2.6/bin But I don't see it?
[ "You say that you installed pip, but you don't say whether or not you installed virtualenvwrapper, which is neither included with pip nor virtualenv.\nIf you have installed virtualenvwrapper using\npip install virtualenvwrapper\n\nor something similar, then you can use the following to find where it is located:\n$ ...
[ 13 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0004988235_pip_python.txt
Q: Google Appengine Reading text from TextProperty or BlobProperty line by line like a file I am working on a Google Appengine Python project where users will upload a "csv type" file, which i can store in either a TextProperty or BlobProperty as they will be way under 1 mb. What I can't figure out is how to read the...
Google Appengine Reading text from TextProperty or BlobProperty line by line like a file
I am working on a Google Appengine Python project where users will upload a "csv type" file, which i can store in either a TextProperty or BlobProperty as they will be way under 1 mb. What I can't figure out is how to read the file later from the blob, and process it line by line. import csv class Upload(db.Model): ...
[ "I think what's going on is you are handing a string to csv.reader when it wants a file object or a list.\ntry: self.file.split('\\n') to turn the string into a list of strings.\n", "You want a BlobReader, which is a file-like object for reading from a blob. You can get one by calling .open() on your BlobInfo obj...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004981213_google_app_engine_google_cloud_datastore_python.txt
Q: How to get the list of divisors of a given number? So the function inputs a list, and a number. Then it should return the index of the list that the number is able to be divided by. If there is no numbers in the list it can be divided by, then it should just return a blank list. For example, div([5,10,15,2,34],10)...
How to get the list of divisors of a given number?
So the function inputs a list, and a number. Then it should return the index of the list that the number is able to be divided by. If there is no numbers in the list it can be divided by, then it should just return a blank list. For example, div([5,10,15,2,34],10) [0,1,3] Here is my coding: def div(nlst, n): nlst ...
[ "There are a few issues in your code:\ndef div(nlst, n):\n nlst = [] # You are deleting the original list here!\n for div in nlst: # The list nlst is empty\n if n % nlst == 0: # Cannot use a list 'nlst' as an operand of the % operation.\n return nlst.index(div) # You are returning a single eleme...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004988301_python.txt
Q: remove every nth word from file The function should return the rest of the words from the file, just not the nth words. I've got the opening, reading and closing the text file down, but I've been struggling to figure out the rest. I tried using append but quickly realized that's not the way to go about it. My fail...
remove every nth word from file
The function should return the rest of the words from the file, just not the nth words. I've got the opening, reading and closing the text file down, but I've been struggling to figure out the rest. I tried using append but quickly realized that's not the way to go about it. My failed coding so far: def message(fname, ...
[ "To remove every nth word, the pseudocode is to read every word and write them all out except the ones where wordnumber modulo n is equal to 0.\nIn other words:\nnth = 7\nwordnumber = 0\nwhile not end-of-file:\n read word\n wordnumber = wordnumber + 1\n if wordnumber % nth is not 0:\n write word\n\n...
[ 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004988106_python.txt
Q: How can one process POST requests with a basic Python CGI script on Apache? I am building a simple python CGI script to work with Twilio. Right now, it only outputs some simple XML, but I would like it to be able to process and respond to POST requests (to get thinks like incoming caller ID). Eventually, I will us...
How can one process POST requests with a basic Python CGI script on Apache?
I am building a simple python CGI script to work with Twilio. Right now, it only outputs some simple XML, but I would like it to be able to process and respond to POST requests (to get thinks like incoming caller ID). Eventually, I will use a full web application framework, like Django; but, for now, I just want a simp...
[ "I found cherrypy very easy to use. You can get argument passing (including support for POST file upload) but not not much else, i.e. you choose whatever template, if any, you want to use, whatever DB ...\nHere is the helloworld example from their homepage...\nimport cherrypy\n\nclass HelloWorld(object):\n def i...
[ 5, 2, 1 ]
[]
[]
[ "apache", "cgi", "post", "python", "twilio" ]
stackoverflow_0004985428_apache_cgi_post_python_twilio.txt
Q: Same hash value but not same object after overriding __hash__ I'm having a problem correctly hashing my objects. Consider the following code: class Foo: def __init__(self, bar): self.keys = list(bar.keys()) self.values = list(bar.values()) def __str__(self): return ', '.join( '...
Same hash value but not same object after overriding __hash__
I'm having a problem correctly hashing my objects. Consider the following code: class Foo: def __init__(self, bar): self.keys = list(bar.keys()) self.values = list(bar.values()) def __str__(self): return ', '.join( '%s: %s' % z for z in zip(self.keys, self.values)) def __has...
[ "Since the __hash__ method is only use for the internal hash-table, you need to redefine __eq__ as well.\nOverriding only __eq__ is not correct either. If two object are equal, ie, a.__eq__(b) == True, then both hash(a) and hash(b) must be equal as well.\nThe default __hash__ method is:\ndef __hash__(self):\n re...
[ 4, 4 ]
[]
[]
[ "hash", "overriding", "python" ]
stackoverflow_0004988400_hash_overriding_python.txt
Q: Transforming level depth to subordinate count Let's consider this sample example text file: Level: 1 Level: 1 Level: 2 Level: 2 Level: 2 Level: 3 Level: 3 Level: 1 Level: 2 Level: 2 Level: 1 I need to transform those lines using provided level data to subordinate count (excluding subordinates of subordinates) The...
Transforming level depth to subordinate count
Let's consider this sample example text file: Level: 1 Level: 1 Level: 2 Level: 2 Level: 2 Level: 3 Level: 3 Level: 1 Level: 2 Level: 2 Level: 1 I need to transform those lines using provided level data to subordinate count (excluding subordinates of subordinates) The result should look like this: :0 :3 :0 :0 :2 :0 :0...
[ "A possible solution:\ninput_text = \"\"\"Level: 1\nLevel: 1\nLevel: 2\nLevel: 2\nLevel: 2\nLevel: 3\nLevel: 3\nLevel: 1\nLevel: 2\nLevel: 2\nLevel: 1\"\"\"\n\n# Parse input text into a list of levels (as int)\nlevels = []\nfor line in input_text.split('\\n'):\n try:\n levels.append(int(line.split(': ', 1...
[ 1 ]
[]
[]
[ "parsing", "python", "tree" ]
stackoverflow_0004988188_parsing_python_tree.txt
Q: python string u"%(word)s" I'm a new user of Python, and I don't know some parts when I read the code. So I asked here. cmd = u"sudo umount %(mountpoint)s >>%(log)s 2>&1" I know that %(word) is used to replace the word latter use such as cmd % {'word':'new word'}, but I don't down why there is a trailing s. and I ...
python string u"%(word)s"
I'm a new user of Python, and I don't know some parts when I read the code. So I asked here. cmd = u"sudo umount %(mountpoint)s >>%(log)s 2>&1" I know that %(word) is used to replace the word latter use such as cmd % {'word':'new word'}, but I don't down why there is a trailing s. and I don't know the 'u' meaning at t...
[ "The beginning u means \"Unicode\" (i.e. it's a Unicode string). The s after each formatting code means to interpret the value as a string, as opposed to d for decimal, etc.\nSee the documentation at http://docs.python.org/library/stdtypes.html#string-formatting-operations for all the details.\n", "The u at the b...
[ 7, 3, 1, 1 ]
[]
[]
[ "python", "string", "syntax" ]
stackoverflow_0004988419_python_string_syntax.txt
Q: Python virutalenv issues, tried the --no-site-packages and got this virtualenv --no-site-packages foobar New python executable in foobar/bin/python Installing setuptools............done. What happened here? lsvirtualenv returns nothing. A: There is a difference between virtualenv and virtualenvwrapper. An en...
Python virutalenv issues, tried the --no-site-packages and got this
virtualenv --no-site-packages foobar New python executable in foobar/bin/python Installing setuptools............done. What happened here? lsvirtualenv returns nothing.
[ "There is a difference between virtualenv and virtualenvwrapper. \nAn env created by virtualenv --no-site-packages foobar will not be seen by the virtualenvwrapper functions, such as lsvirtualenv. \nIf you want to tap the unbridled power of the virtualenvwrapper, follow these instructions and create a new env by ...
[ 6 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0004988497_python_virtualenv.txt
Q: Is my pip with virtualenv working? creating a new virtualenvironment and it says django already satisfied? I installed pip, virutalenv and set my WORKON_HOME etc. according to the insturctions. Now I did this: mkvirtualenv test1 then did: pip install django and got: Requirement already satisfied (use --upgrade t...
Is my pip with virtualenv working? creating a new virtualenvironment and it says django already satisfied?
I installed pip, virutalenv and set my WORKON_HOME etc. according to the insturctions. Now I did this: mkvirtualenv test1 then did: pip install django and got: Requirement already satisfied (use --upgrade to upgrade): django in /Library/Python/2.6/site-packages In terminal, it does have (test1) at my prompt.... Does...
[ "Do this instead: \nmkvirtualenv --no-site-packages test1\n\nThen, your env will be actually clean and isolated. \n", "On OS X, that folder in /Library is in the default search path, so if Django got installed in there, it will satisfy the dependency for pip. Maybe you wanted to use the --no-site-packages option...
[ 2, 1 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0004988390_pip_python.txt
Q: converting a List property to individual values in a CSV export from GAE I have a list of String inside a class in my App Engine project, and in the database export to a CSV (through bulkloader.yaml) the resulting field is the proper List. The problem is that this CSV is imported again into a MySQL database and su...
converting a List property to individual values in a CSV export from GAE
I have a list of String inside a class in my App Engine project, and in the database export to a CSV (through bulkloader.yaml) the resulting field is the proper List. The problem is that this CSV is imported again into a MySQL database and such field remains as a single list of strings. Any idea about how to tweak the ...
[ "You can't make the bulkloader export multiple rows for a single entity using the YAML configuration. You'll either need to write a custom exporter, or a custom converter - see the bulkloader source for details (in the docstrings).\n" ]
[ 0 ]
[]
[]
[ "csv", "google_app_engine", "python" ]
stackoverflow_0004949425_csv_google_app_engine_python.txt
Q: Problem running webpy Hello World demo I'm trying to run the hello world demo from the official web site: import web urls = ('/.*', 'index') app = web.application(urls, globals()) class index: def GET(self): return 'Hello,world......' if __name__ == "__main__": web.wsgi.runwsgi = lambda f...
Problem running webpy Hello World demo
I'm trying to run the hello world demo from the official web site: import web urls = ('/.*', 'index') app = web.application(urls, globals()) class index: def GET(self): return 'Hello,world......' if __name__ == "__main__": web.wsgi.runwsgi = lambda func, addr = None: web.wsgi.runfcgi(func, add...
[ "I don't know if that helps, but I just commented out this line:\n web.wsgi.runwsgi = lambda func, addr = None: web.wsgi.runfcgi(func, addr) \nIt runs ok.\n" ]
[ 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0004988467_python_web.py.txt
Q: Issue with basic SQLite database access in Python I have a database called "default.db" and it is a working database [I can access it through the SQLite utilities and see the tables inside]. I have this code for accessing the database: from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect("default.db") c...
Issue with basic SQLite database access in Python
I have a database called "default.db" and it is a working database [I can access it through the SQLite utilities and see the tables inside]. I have this code for accessing the database: from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect("default.db") cur = conn.cursor() #retrieve all database data cur.ex...
[ "I think you should iterate over cur.fetchall() not the cur -> cursor itself.\nIt should be like;\nfor i in cur.fetchall():\n print \"item\"\n print i\n\nAnd you should also drop the previous cur.fetcall() command.\n", "You should probably read the DBAPI docs. But basically, the cursor is not iterable itsel...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004987705_python_sqlite.txt
Q: python solution for feed provider I want to build a site same as : http://www.feedmyinbox.com/ , and post all my google reader subscriptions(100+) to my gmail, (in separate mails) so I need create a feed fetcher server, get all the feeds, post new ones to my gmail. are there any python based feed fetcher library?...
python solution for feed provider
I want to build a site same as : http://www.feedmyinbox.com/ , and post all my google reader subscriptions(100+) to my gmail, (in separate mails) so I need create a feed fetcher server, get all the feeds, post new ones to my gmail. are there any python based feed fetcher library? I know there is some feed parser, I th...
[ "I had a similar question about a year ago.\nHonestly, Most things like this are built off of the Universal Feed Parser (some feed parser).\nUsing the feed parser is a huge step in the direction you are moving.\nThe world of Python is full of modules you could use, Beautiful Soup, etc, but honestly, the UFP is wha...
[ 1, 0 ]
[]
[]
[ "feed", "python" ]
stackoverflow_0004988519_feed_python.txt
Q: Parsing indeterminate amount of data into a python tuple I have a config file that contains a list of strings. I need to read these strings in order and store them in memory and I'm going to be iterating over them many times when certain events take place. Since once they're read from the file I don't need to add ...
Parsing indeterminate amount of data into a python tuple
I have a config file that contains a list of strings. I need to read these strings in order and store them in memory and I'm going to be iterating over them many times when certain events take place. Since once they're read from the file I don't need to add or modify the list, a tuple seems like the most appropriate da...
[ "As you said, you're going to read the data gradually - so a tuple isn't a good idea after all, as it's immutable.\nIs there a reason for not using a simple list for holding the strings?\n", "I wouldn't worry about the overhead of first creating a list and then a tuple from that list. My guess is that the overhea...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0003706553_list_python_tuples.txt
Q: My KeyboardInterrupt is only getting caught 90% of the time. What am I failing at? Here's some slimmed down code that demonstrates my use of threading: import threading import Queue import time def example(): """ used in MainThread as the example generator """ while True: yield 'asd' class Threa...
My KeyboardInterrupt is only getting caught 90% of the time. What am I failing at?
Here's some slimmed down code that demonstrates my use of threading: import threading import Queue import time def example(): """ used in MainThread as the example generator """ while True: yield 'asd' class ThreadSpace: """ A namespace to be shared among threads/functions """ # set this to ...
[ "KeyboardInterrupts are received by arbitrary threads. If the receiver isn't the main thread, it dies, the main thread is unaffected, ThreadSpace.exit_flag remains false, and the script keeps running.\nIf you want sigint to work, you can have each thread catch KeyboardInterrupt and call thread.interrupt_main() to ...
[ 2 ]
[]
[]
[ "exception", "keyboardinterrupt", "multithreading", "python" ]
stackoverflow_0004988932_exception_keyboardinterrupt_multithreading_python.txt
Q: Lattice Multiplication with threads, is it more efficient? which one is faster: Using Lattice Multiplication with threads(big numbers) OR Using common Multiplication with threads(big numbers) Do you know any source code, to test them? -----------------EDIT------------------ The theads should be implemented in C, ...
Lattice Multiplication with threads, is it more efficient?
which one is faster: Using Lattice Multiplication with threads(big numbers) OR Using common Multiplication with threads(big numbers) Do you know any source code, to test them? -----------------EDIT------------------ The theads should be implemented in C, or Java for testing
[ "If I understand you correctly, \"lattice multiplication\" is different way of doing base-10 multiplication by hand that is supposed to be easier for kids to understand than the classic way. I assume \"common multiplication\" is the classic way.\nSo really, I think that the best answer is:\n\nNeither \"lattice mul...
[ 1 ]
[]
[]
[ "c", "java", "multiplication", "python" ]
stackoverflow_0004988830_c_java_multiplication_python.txt