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: Bypass "Do you want to continue (y/n, default n)" for "setup.py"? I'd like to bypass the "Do you want to continue (y/n, default n)" prompt via a shell script. I've tried: python setup.py install --force and python setup.py install wait y both don't work ... anyone have other ideas? A: If this question is dis...
Bypass "Do you want to continue (y/n, default n)" for "setup.py"?
I'd like to bypass the "Do you want to continue (y/n, default n)" prompt via a shell script. I've tried: python setup.py install --force and python setup.py install wait y both don't work ... anyone have other ideas?
[ "If this question is displayed multiple times, just do a:\nyes | command\n\nHowever this will also aknowledge all other questions. If you want something more sophisticated have a look at expect.\n", "Pipe the string \"y\" into the command.\neg:\necho \"y\" | python setup.py install\n\n" ]
[ 8, 5 ]
[]
[]
[ "bash", "installation", "python", "shell" ]
stackoverflow_0007973986_bash_installation_python_shell.txt
Q: ImportError: No Module name Multiarray So I am using IronPython in PyDev and I am trying to import numpy. However, when I am getting the following error: Traceback (most recent call last): File "C:\Users\Dan\workspace\Practice\src\practice.py", line 8, in <module> File "C:\Python27\Lib\site-packages\numpy\__init_...
ImportError: No Module name Multiarray
So I am using IronPython in PyDev and I am trying to import numpy. However, when I am getting the following error: Traceback (most recent call last): File "C:\Users\Dan\workspace\Practice\src\practice.py", line 8, in <module> File "C:\Python27\Lib\site-packages\numpy\__init__.py", line 137, in <module> File "C:\Python...
[ "I don't think you can import the 'regular' numpy from IronPython (but it seems there's a port for IronPython you could use... http://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net )\n" ]
[ 0 ]
[]
[]
[ "importerror", "ironpython", "numpy", "python", "python_c_extension" ]
stackoverflow_0007965240_importerror_ironpython_numpy_python_python_c_extension.txt
Q: Why does python keep buffering stdout even when flushing and using -u? $ cat script.py import sys for line in sys.stdin: sys.stdout.write(line) sys.stdout.flush() $ cat script.py - | python -u script.py The output is right but it only starts printing once I hit Ctrl-D whereas the following starts printi...
Why does python keep buffering stdout even when flushing and using -u?
$ cat script.py import sys for line in sys.stdin: sys.stdout.write(line) sys.stdout.flush() $ cat script.py - | python -u script.py The output is right but it only starts printing once I hit Ctrl-D whereas the following starts printing right away : $ cat script.py - | cat which led me to think that the buff...
[ "Python manpage reveals the answer to your question:\n -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that\n there is internal buffering in xreadlines(), readlines() and file-object iterators (\"...
[ 5, 1 ]
[]
[]
[ "buffering", "pipe", "python", "stdout" ]
stackoverflow_0007973870_buffering_pipe_python_stdout.txt
Q: Removing duplicate elements from a Python list containing unhashable elements while preserving order? I have a datastructure like this: [ [('A', '1'), ('B', '2')], [('A', '1'), ('B', '2')], [('A', '4'), ('C', '5')] ] And I want to obtain this: [ [('A', '1'), ('B', '2')], [('A', '4'), ('C', '5')] ] Is there a goo...
Removing duplicate elements from a Python list containing unhashable elements while preserving order?
I have a datastructure like this: [ [('A', '1'), ('B', '2')], [('A', '1'), ('B', '2')], [('A', '4'), ('C', '5')] ] And I want to obtain this: [ [('A', '1'), ('B', '2')], [('A', '4'), ('C', '5')] ] Is there a good way of doing this while preserving order as shown? Commands for copy-pasting: sample = [] sample.append([...
[ "This is a somewhat famous question which was well answered by a famous Pythonista long ago: http://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/\nIf you can assume equal records are adjacent, there is a recipe in the itertools docs:\nfrom operator import itemgetter\nfrom itertools import g...
[ 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007973933_python.txt
Q: How to watch a directory for changes? Could not find anything in python core to do this. Can anyone recommend a library or "battery" to do this? Ideally I would like this to be portable but it's OK if it is available only for Unix (my server). A: On Linux, you could be interested in pyinotify https://github.com...
How to watch a directory for changes?
Could not find anything in python core to do this. Can anyone recommend a library or "battery" to do this? Ideally I would like this to be portable but it's OK if it is available only for Unix (my server).
[ "On Linux, you could be interested in pyinotify\n\nhttps://github.com/seb-m/pyinotify\n\nOther related libraries:\n\nhttp://people.gnome.org/~veillard/gamin/python.html\nPython FAM interface: http://python-fam.sourceforge.net/\nhttp://gorakhargosh.github.com/watchdog/\n\n", "I don't think there's something portab...
[ 11, 5, 4 ]
[]
[]
[ "filesystemwatcher", "python" ]
stackoverflow_0004708511_filesystemwatcher_python.txt
Q: How to convert a file line to a float/int in python Whenever I try to run this code: #Open file f = open("i.txt", "r") line = 1 #Detect start point def findstart( x ): length = 0 epsilon = 7 a = 3 line_value = int(f.readline(x)) if line_value == a: ...
How to convert a file line to a float/int in python
Whenever I try to run this code: #Open file f = open("i.txt", "r") line = 1 #Detect start point def findstart( x ): length = 0 epsilon = 7 a = 3 line_value = int(f.readline(x)) if line_value == a: length = length + 1 x = x + 1 ...
[ "I'm not sure about your code, but the error message suggests that your file has an empty line in it and you're trying to convert it to an int. For example, a lot of text files have an empty line at the end.\nI'd suggest first checking your line before converting it:\nline = ...\nline = line.strip() # strip whitesp...
[ 2, 1, 1 ]
[]
[]
[ "file", "ioerror", "python", "python_2.7" ]
stackoverflow_0007974269_file_ioerror_python_python_2.7.txt
Q: lambda in python I'm revisiting some scheme excercises in python (if that makes sense) to find out what python can do in terms of FP. My problem concerns lambda in python : Can i define a general function in python with an operator as one of the arguments? Think this : def f (op,x,y): #return some lambda func...
lambda in python
I'm revisiting some scheme excercises in python (if that makes sense) to find out what python can do in terms of FP. My problem concerns lambda in python : Can i define a general function in python with an operator as one of the arguments? Think this : def f (op,x,y): #return some lambda function that combines x a...
[ "I can see some points in your question, lets go through them in order:\n1. Can I pass a function as a parameter to someone?\nYes:\ndef f(op, x, y):\n return op(x, y)\n\ndef add(x, y):\n return x + y\n\nf(add, 10, 7) #gives 17\n\n2. What about operators then?\nUnlike scheme, Python operators are not functions...
[ 14, 8, 2, 1, 0 ]
[]
[]
[ "functional_programming", "lambda", "python" ]
stackoverflow_0007974442_functional_programming_lambda_python.txt
Q: Incomprehensible Django Runserver Error I have had many problems in Django (not all of them solved), but this is by far the weirdest and most incomprehensible one. It happens when I load a page: >python manage.py runserver Validating models... 0 errors found Django version 1.3.1, using settings 'ponysite.settin...
Incomprehensible Django Runserver Error
I have had many problems in Django (not all of them solved), but this is by far the weirdest and most incomprehensible one. It happens when I load a page: >python manage.py runserver Validating models... 0 errors found Django version 1.3.1, using settings 'ponysite.settings' Development server is running at http://1...
[ "Based on this line:\nFile \"C:\\Users\\kiwi\\Dropbox\\Programming Projects\\Django Projects\\ponysite\\forum\\admin.py\" in\n1. from forum.models import Category, Thread, Post, Report, Subscription, Ban\n\nDjango is finding in forum/admin.py \nfrom forum.models import Category, Thread, Post, Report, Subscription...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007974395_django_python.txt
Q: What's a good medium/large project for a Python programmer? Just like the title asks. I've been learning Python for a while now and I'd say I'm pretty decent with it. I'm looking for a medium or large project to keep me busy for quite a while. Your suggestions are greatly appreciated. A: Find a local charitable ...
What's a good medium/large project for a Python programmer?
Just like the title asks. I've been learning Python for a while now and I'd say I'm pretty decent with it. I'm looking for a medium or large project to keep me busy for quite a while. Your suggestions are greatly appreciated.
[ "Find a local charitable orgainzation with a lousy web presence. Solve their problem. Help other people. Learn more Python. Everyone wins. \n", "You can invent a game and code it with pygame. They're always fun to code and you still learn a lot when you code a game.\n", "What are you interested in doing? You ...
[ 15, 10, 6, 1, 1, 1, 1, 0, 0 ]
[ "I think the best thing you can do now is spend time learning a new technology, preferably including a new programming language.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0000455075_python.txt
Q: how to return only filter passed images from the list Suppose we have a function processed_filter_description(a, b, c) which takes 3 parameters. a = user input description b = file extensions for potential images (jpg, gif), c = the list of all the images (['image1.jpg', 'image1.gif', 'image2.jpg', 'image2.gif',...
how to return only filter passed images from the list
Suppose we have a function processed_filter_description(a, b, c) which takes 3 parameters. a = user input description b = file extensions for potential images (jpg, gif), c = the list of all the images (['image1.jpg', 'image1.gif', 'image2.jpg', 'image2.gif', 'image3.jpg', 'image3.gif']) The function checks the desc...
[ "If I understand you spec correctly, it looks something like this:\n>>> def processed_filter_description(desc, exts, all_images):\n result = []\n for image in all_images:\n base, ext = os.path.splitext(image)\n if base.startswith(desc) and ext in exts:\n result.app...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007974437_python.txt
Q: Apache + mod_wsgi interaction Before posting this, I have read quite a few resources online, including the mod_wsgi wiki, but I am confused about how exactly Apache processes/threads interact with mod_wsgi. This is my current understanding: Apache can be configured to run such that one or more child processes can...
Apache + mod_wsgi interaction
Before posting this, I have read quite a few resources online, including the mod_wsgi wiki, but I am confused about how exactly Apache processes/threads interact with mod_wsgi. This is my current understanding: Apache can be configured to run such that one or more child processes can handle incoming requests, and each...
[ "Answers to each of the points.\n1 - WSGIDaemonProcess/WSGIProcessGroup indicate that mod_wsgi should fork of a separate process for running the WSGI application in. This is a fork only and not a fork/exec, so mod_wsgi is still in control of it. When it is detected that a URL maps to a WSGI application running in d...
[ 11 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0007968840_apache_mod_wsgi_python.txt
Q: Counting "something" in multiple text files in one folder I am trying to count the number times "Tmp" occurs in a file and what file the count belongs to. I created a script that works but I have to setup the input file and output directory for each file. To improve it I would like the script to go through each ...
Counting "something" in multiple text files in one folder
I am trying to count the number times "Tmp" occurs in a file and what file the count belongs to. I created a script that works but I have to setup the input file and output directory for each file. To improve it I would like the script to go through each file in a folder after setting it up once. I have been experime...
[ "That should be:\ndata = open(infile, 'r').read()\nprint data.count('Tmp')\n\n", "I would use os.walk rather than glob:\nimport tkFileDialog\nimport os\nimport os.path\nimport re\n\ndirectory = tkFileDialog.askdirectory()\n\nfor dirpath, dirnames, filenames in os.walk(directory):\n for filename in filenames:\n...
[ 1, 1, 0 ]
[]
[]
[ "count", "file", "python", "text" ]
stackoverflow_0007974530_count_file_python_text.txt
Q: How do I use Django Command Extensions with a new Eclipse/Pydev run configuration When I create new run configurations in Eclipse it creates a run command like the following: python.exe -u manage.py runscript my_script.py, regardless of whether I try making a Python Run config, or a Django run config. How do I mak...
How do I use Django Command Extensions with a new Eclipse/Pydev run configuration
When I create new run configurations in Eclipse it creates a run command like the following: python.exe -u manage.py runscript my_script.py, regardless of whether I try making a Python Run config, or a Django run config. How do I make it run python.exe manage.py runscript my_script.py instead? (no -u switch). I've assu...
[ "Try \"run -> run...\" and then edit the arguments. \nhttp://www.cs.colostate.edu/helpdocs/cmd.pdf\n" ]
[ 0 ]
[]
[]
[ "django", "django_command_extensions", "eclipse", "python" ]
stackoverflow_0006118429_django_django_command_extensions_eclipse_python.txt
Q: Web2py + MS SQL Server 2008 R2 + LDAP Authentication HelloWorld application? I have been using Web2py in the awesome *nix environment for sometime along with opensource RDMS (MySQL,Postgre,SQLLite,etc) for my personal projects. For my workplace which is completely working in a .Net environment I need to make a qui...
Web2py + MS SQL Server 2008 R2 + LDAP Authentication HelloWorld application?
I have been using Web2py in the awesome *nix environment for sometime along with opensource RDMS (MySQL,Postgre,SQLLite,etc) for my personal projects. For my workplace which is completely working in a .Net environment I need to make a quick web app (employee master data maintenance) which runs on the local intranet wit...
[ "This is a partial answer, it only deals with authentication using Active Directory (I assuma it is the same or similar to Domain Authentication). I am not a Windows expert, but had the local windows admin help me. This is code that I put in the db.py file for this app in web2py.\nif localauth:\n # I set localau...
[ 0, 0 ]
[]
[]
[ "python", "sql_server_2008_r2", "web2py", "windows_server_2008" ]
stackoverflow_0007962840_python_sql_server_2008_r2_web2py_windows_server_2008.txt
Q: Python: create dict from list and auto-gen/increment the keys (list is the actual key values)? i've searched pretty hard and cant find a question that exactly pertains to what i want to.. I have a file called "words" that has about 1000 lines of random A-Z sorted words... 10th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th a...
Python: create dict from list and auto-gen/increment the keys (list is the actual key values)?
i've searched pretty hard and cant find a question that exactly pertains to what i want to.. I have a file called "words" that has about 1000 lines of random A-Z sorted words... 10th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th a AAA AAAS Aarhus Aaron AAU ABA Ababa aback abacus abalone abandon abase abash abate abater abbas abb...
[ "key = +1\n\n+1 is the same thing as 1. I assume you meant key += 1. I also can't see a reason why you'd split each line when there's only one item per line.\nHowever, there's really no reason to do the looping yourself.\nwith open('words') as f3data:\n mydict = dict(enumerate(line.strip() for line in f3data))\n...
[ 3, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "file_io", "python" ]
stackoverflow_0007974959_dictionary_file_io_python.txt
Q: Join Recarrays by attributes in Python I am trying to join recarrys in python such that the same value joins to many elements. The following code works when it is a 1:1 ratio, but when I am trying to do many:1, it only joins one instance: import numpy as np import matplotlib # First data structure sex = np.array(...
Join Recarrays by attributes in Python
I am trying to join recarrys in python such that the same value joins to many elements. The following code works when it is a 1:1 ratio, but when I am trying to do many:1, it only joins one instance: import numpy as np import matplotlib # First data structure sex = np.array(['M', 'F', 'M', 'F', 'M', 'F']) causes = np....
[ "There might be a good use of record array, but I thought python dict should be as good here... Want to know numpy way of doing this myself, too, if it is good.\ndct = dict(zip(data2['causes'], data2['analyst']))\nall_data = mlab.rec_append_fields(data1, 'analyst',\n [dct[x] for x in data1['causes']])\n\n" ]
[ 1 ]
[]
[]
[ "join", "numpy", "python", "recarray" ]
stackoverflow_0007974824_join_numpy_python_recarray.txt
Q: Google App Engine Bulkloader "Unexpected Thread Death" I am trying to upload a moderetly sized csv file to google app engine using the bulkloader functionality, and it appears to die some of the way through with the following result: [INFO ] Logging to bulkloader-log-20110328.181531 [INFO ] Throttling transf...
Google App Engine Bulkloader "Unexpected Thread Death"
I am trying to upload a moderetly sized csv file to google app engine using the bulkloader functionality, and it appears to die some of the way through with the following result: [INFO ] Logging to bulkloader-log-20110328.181531 [INFO ] Throttling transfers: [INFO ] Bandwidth: 250000 bytes/second [INFO ] HT...
[ "Lifting the batch limit (batch_size) and rps limit (rps_limit) works, I use 1000 for the batch size and an rps limit of 500: \nappcfg.py upload_data --url= --application= --filename= --email= --batch_size=1000 --rps_limit=500\n\n" ]
[ 6 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0005466900_bulkloader_google_app_engine_python.txt
Q: Django Models and Serial Ports I am playing around with using Django and a few arduinos. From my models.py I have class Arduino(models.Model): ... address = models.CharField(max_length=100) ... I am wondering if it is possible for 'address' to have an auto-generated choice-tuple from a script (or if ...
Django Models and Serial Ports
I am playing around with using Django and a few arduinos. From my models.py I have class Arduino(models.Model): ... address = models.CharField(max_length=100) ... I am wondering if it is possible for 'address' to have an auto-generated choice-tuple from a script (or if this is even the right approach). I ...
[ "Set the choices for the field in the initializer.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "serial_port" ]
stackoverflow_0007975140_django_python_serial_port.txt
Q: Optimise comparison between two lists, giving indices that differ I have three lists: old, new and ignore. old and new are lists of strings. ignore is a list of indices that should be ignored if they do not match. The objective is to create a list of indices which are different and not ignored. old and new may con...
Optimise comparison between two lists, giving indices that differ
I have three lists: old, new and ignore. old and new are lists of strings. ignore is a list of indices that should be ignored if they do not match. The objective is to create a list of indices which are different and not ignored. old and new may contain a different number of elements. If there is a difference in size b...
[ "For both of these solutions, you should do:\nignore = set(ignore)\n\nwhich will give you constant (average) time in tests.\nI think this is the itertools / zip based method you were looking for:\n[i for i, (o, n) in enumerate(izip_longest(old, new)) \n if o != n and i not in ignore]\n\nNo ...
[ 4, 1, 1 ]
[]
[]
[ "list", "optimization", "python" ]
stackoverflow_0007974883_list_optimization_python.txt
Q: How can I make this loop with Jinja2? With Jinja2, how can I make an iteration like the folllowing which works with django and not Jinja: {% for key,value in location_map_india.items %} {{value.name}} {% endfor %} The above is valid django but with Jinja2 it returns an error message TypeError: 'builtin_function_...
How can I make this loop with Jinja2?
With Jinja2, how can I make an iteration like the folllowing which works with django and not Jinja: {% for key,value in location_map_india.items %} {{value.name}} {% endfor %} The above is valid django but with Jinja2 it returns an error message TypeError: 'builtin_function_or_method' object is not iterable Thanks f...
[ "In Jinja2, functions and methods must be explicitly called.\n{% for key,value in location_map_india.items() %}\n{{value.name}}\n{% endfor %}\n\n" ]
[ 15 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0007975365_jinja2_python.txt
Q: Unable to get regex to capture last group I'm trying to write a regex in python to parse a Newick tree, but for the life of me I can't get the last part of it to match. There are three types of Newick formats I need to parse: ((A,B),C); ((A:0.1,B:0.2),C:0.3); ((A:[c1]0.1,B:[c2]0.2),C:[c2]0.3); ...each of which co...
Unable to get regex to capture last group
I'm trying to write a regex in python to parse a Newick tree, but for the life of me I can't get the last part of it to match. There are three types of Newick formats I need to parse: ((A,B),C); ((A:0.1,B:0.2),C:0.3); ((A:[c1]0.1,B:[c2]0.2),C:[c2]0.3); ...each of which contains three labels (A, B, C) and various other...
[ "The problem is probably that you're looking for non-overlapping instances of the regex.\nMethods like findall won't return B as the match for A consumes the , before B.\n>>> regex.findall(\"((A:[c1]0.1,B:[c2]0.2),C:[c2]0.3);\")\n[('(A:[c1]0.1,', '(', 'A', ':', '[c1]', '0.1', ','), (',C:[c2]0.3)', ',', 'C', ':', '[...
[ 3, 0 ]
[]
[]
[ "bioinformatics", "python", "regex" ]
stackoverflow_0007975214_bioinformatics_python_regex.txt
Q: ValueError: invalid literal for int() with base 10: 'Blusson Hall' This is homework but I'm not looking for a handout. Error messages haven't really been explained yet so I don't know how to fix this or why it's happening. I know it happens when I try to make s into an integer but I get a different error if I don'...
ValueError: invalid literal for int() with base 10: 'Blusson Hall'
This is homework but I'm not looking for a handout. Error messages haven't really been explained yet so I don't know how to fix this or why it's happening. I know it happens when I try to make s into an integer but I get a different error if I don't so I'm a little lost... I've also tried looking at some of the other ...
[ "Your problem is that you are calling spaced with a non-numeric string and then trying to convert that to an integer:\n>>> int(\"Blusson Hall\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for int() with base 10: 'Blusson Hall'\n\nIf you want a range bas...
[ 6, 2, 0 ]
[]
[]
[ "python", "spaces" ]
stackoverflow_0007975441_python_spaces.txt
Q: unicode in python turns into '\xXX\xXX' I'm using MySQLdb, I use: cursor.execute(QUERY) Where QYERY is: INSERT (A,B,C) VALUES("%s","%s",something);'%(k1, u'W')** w Is a persian letter (literally it is! I just replaced it with W in case you have problem viewing persian letters, it is something like ب), and k1 is ...
unicode in python turns into '\xXX\xXX'
I'm using MySQLdb, I use: cursor.execute(QUERY) Where QYERY is: INSERT (A,B,C) VALUES("%s","%s",something);'%(k1, u'W')** w Is a persian letter (literally it is! I just replaced it with W in case you have problem viewing persian letters, it is something like ب), and k1 is english. but i get: `Traceback (most recent c...
[ "You're missing an INTO table_name clause. That's the only actual problem I see.\nThe changing of ب to \\xd8\\xa8 just means that your Unicode is getting encoded as UTF-8 on the way to the database (which is probably what you want). MySQL is reporting the UTF-8-encoded bytes by using a \\xXX notation (hexadecimal e...
[ 3, 0 ]
[]
[]
[ "mysql_python", "python", "unicode" ]
stackoverflow_0007975307_mysql_python_python_unicode.txt
Q: Database recommendation for dictionary storage Using Python I managed to make myself a kind of dictionary of terms and their meaning and it's rather big - x00,000 items (can't estimate right now as they are stored in multiple files by first letter). Files are pickled dictionary objects with this structure: dict{wo...
Database recommendation for dictionary storage
Using Python I managed to make myself a kind of dictionary of terms and their meaning and it's rather big - x00,000 items (can't estimate right now as they are stored in multiple files by first letter). Files are pickled dictionary objects with this structure: dict{word, (attribute, kind, [meani...
[ "Yes, I've used sqlite3 for this kind of thing. The dictionary values had to first be pickled though:\nimport sqlite3\nimport pickle\nimport collections\n\nclass DBDict(collections.MutableMapping):\n 'Database driven dictlike object (with non-persistent in-memory option).'\n\n def __init__(self, db_filename=...
[ 0, 0 ]
[]
[]
[ "database", "python", "recommendation_engine" ]
stackoverflow_0007975531_database_python_recommendation_engine.txt
Q: Split shell-like syntax in Haskell? How can I split a string in shell-style syntax in Haskell? The equivalent in Python is shlex.split. >>> shlex.split('''/nosuchconf "/this doesn't exist either" "yep"''') ['/nosuchconf', "/this doesn't exist either", 'yep'] A: I'm not sure what exactly you mean: are you wanting...
Split shell-like syntax in Haskell?
How can I split a string in shell-style syntax in Haskell? The equivalent in Python is shlex.split. >>> shlex.split('''/nosuchconf "/this doesn't exist either" "yep"''') ['/nosuchconf', "/this doesn't exist either", 'yep']
[ "I'm not sure what exactly you mean: are you wanting to get get all quoted sub-strings from a String? Note that unlike Python, etc. Haskell only has one set of quotes that indicate something is a String, namely \"...\".\nPossibilities to consider:\n\nThe words and lines functions\nThe split package\nWrite a custom...
[ 1 ]
[]
[]
[ "haskell", "lexical_analysis", "python", "shlex", "split" ]
stackoverflow_0007975451_haskell_lexical_analysis_python_shlex_split.txt
Q: Inserting large text data into postgres with python I am trying to do a bulk insert of long xml strings as text into a postgresql 9.1 database. I am using Python 3.2 and pyscopg2. I am enclosing the xml string in $$ and using a named variable in the query string. For example: query = "insert into cms_object_metada...
Inserting large text data into postgres with python
I am trying to do a bulk insert of long xml strings as text into a postgresql 9.1 database. I am using Python 3.2 and pyscopg2. I am enclosing the xml string in $$ and using a named variable in the query string. For example: query = "insert into cms_object_metadata (cms_object_id, cms_object_metadata_data, cms_object_m...
[ "Summarizing the comment thread. Do this:\nquery = \"insert into cms_object_metadata (cms_object_id, cms_object_metadata_data, cms_object_metadata_type_id, \\\n cms_object_metadata_status_id) values ((select id from cms_objects where cms_object_ident = %(objIdent)s), \\\n %(objMetaString)s, (select...
[ 1 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0007930589_postgresql_psycopg2_python.txt
Q: Linux BC: Decimal/Floating Calculation NOT Accurate I am writing a command line program in BASH on Ubuntu 10.08. However, I found one problem: VSize=`echo 370.02 \* 1024 \* 1024 |bc` echo ${VSize} 387994091.52 However, 370.02 * 1 024 * 1 024 = 387994092 I have Python 2.6 installed, even python says: print 370.02*...
Linux BC: Decimal/Floating Calculation NOT Accurate
I am writing a command line program in BASH on Ubuntu 10.08. However, I found one problem: VSize=`echo 370.02 \* 1024 \* 1024 |bc` echo ${VSize} 387994091.52 However, 370.02 * 1 024 * 1 024 = 387994092 I have Python 2.6 installed, even python says: print 370.02*1024*1024 387994091.52 How can I get the accurate answer...
[ "\nHowever, 370.02 * 1 024 * 1 024 = 387994092\n\nNot quite.\n>>> 387994092. / 1024 / 1024\n370.02000045776367\n>>> 0.00000045776367 * 1024 * 1024\n0.47999999803392002\n\nThe inaccurate one is you.\n" ]
[ 4 ]
[]
[]
[ "32_bit", "command_line", "linux", "python", "ubuntu" ]
stackoverflow_0007976045_32_bit_command_line_linux_python_ubuntu.txt
Q: How to only print certain text using BeautifulSoup I am trying to pull some financial data for city governments using BeautifulSoup (had to convert the files from pdf). I just want to get the data as a csv file and then I'll analyze it in Excel or SAS. My problem is that I do not want to print the "& nbsp;" that i...
How to only print certain text using BeautifulSoup
I am trying to pull some financial data for city governments using BeautifulSoup (had to convert the files from pdf). I just want to get the data as a csv file and then I'll analyze it in Excel or SAS. My problem is that I do not want to print the "& nbsp;" that is in the original HTML, just the numbers and the row hea...
[ "soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)\n\nIt converts &nbsp; and other html entities to appropriate characters.\nTo write it to a csv file:\n>>> import csv\n>>> import sys\n>>> csv_file = sys.stdout\n>>> writer = csv.writer(csv_file, delimiter=\"|\")\n>>> soup = BeautifulSoup(\"<tr...
[ 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007975770_beautifulsoup_python.txt
Q: mixing url dispatch and traversal I've been working on an app that uses url dispatch. I setup my root factory based on some great info found here: https://github.com/mmerickel/pyramid_auth_demo (thanks Michael!) Now I'm trying to use pyramid_formalchemy as well. It seems pyramid_formalchemy uses traversal for de...
mixing url dispatch and traversal
I've been working on an app that uses url dispatch. I setup my root factory based on some great info found here: https://github.com/mmerickel/pyramid_auth_demo (thanks Michael!) Now I'm trying to use pyramid_formalchemy as well. It seems pyramid_formalchemy uses traversal for determining authorization. That's ok, bu...
[ "I've answered some similar questions on handling ACLs within pyramid_formalchemy here:\nPyramid and FormAlchemy admin interface\nBasically pyramid_formalchemy defines it's own root factory for all of the admin URLs. You can override it and define an __acl__ there (see ModelsWithACL) which will probably solve most ...
[ 0 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0007975564_pyramid_python.txt
Q: Is it a sin to use infinite recursion for infinite loops in Python? This question is more about curiosity than utility. If I'm writing a function that's supposed to run for ever, for instance a daemon, how would Python handle it if I called the function again from the end of the function? def daemonLoop(): # ...
Is it a sin to use infinite recursion for infinite loops in Python?
This question is more about curiosity than utility. If I'm writing a function that's supposed to run for ever, for instance a daemon, how would Python handle it if I called the function again from the end of the function? def daemonLoop(): # Declare locals # Do stuff daemonLoop() I'm fairly sure that do...
[ "In almost all Python interpreters that will cause a stack overflow, as it would in C. The higher-level feature that would permit this is called Tail Call Optimization or Tail Recursion Elimination, and the benevolent dictator of Python opposes adding this to the language.\nThis style is considered to be non-idioma...
[ 17, 5, 1, 1, 0, 0 ]
[]
[]
[ "c", "function_calls", "infinite_loop", "python", "recursion" ]
stackoverflow_0007975515_c_function_calls_infinite_loop_python_recursion.txt
Q: How can I get generators/iterators to evaluate as False when exhausted? Other empty objects in Python evaluate as False -- how can I get iterators/generators to do so as well? A: Guido doesn't want generators and iterators to behave that way. Objects are true by default. They can be false only if they define __...
How can I get generators/iterators to evaluate as False when exhausted?
Other empty objects in Python evaluate as False -- how can I get iterators/generators to do so as well?
[ "Guido doesn't want generators and iterators to behave that way.\nObjects are true by default. They can be false only if they define __len__ that returns zero or __nonzero__ that returns False (the latter is called __bool__ in Py3.x).\nYou can add one of those methods to a custom iterator, but it doesn't match Gui...
[ 9, 7, 4 ]
[]
[]
[ "boolean", "generator", "iterator", "python" ]
stackoverflow_0007976269_boolean_generator_iterator_python.txt
Q: TypeError Exception ###views.py### def profile_interest_mempick(request,pk,code=None): """allows user to subscribe to profile interests""" me = Register.objects.get(user=request.user) mem = Register.objects.get(pk=pk) if code == 's': interests = mem.profile_interests.all() if not interests: content_s...
TypeError Exception
###views.py### def profile_interest_mempick(request,pk,code=None): """allows user to subscribe to profile interests""" me = Register.objects.get(user=request.user) mem = Register.objects.get(pk=pk) if code == 's': interests = mem.profile_interests.all() if not interests: content_string = "You currently ha...
[ "Check url regular expression on urls.py.\nhttps://docs.djangoproject.com/en/dev/topics/http/urls/\nPattern should be as:\nurlpatterns = patterns('',\n (r'^profile_interest_mempick/(?P\\d{4})/$', 'news.views.profile_interest_mempick'),\n", "The traceback suggests that the problem isn't in the definition of pro...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007976578_python.txt
Q: Having trouble using BeautifulSoup to parse WeatherUnderground I'm trying to adapt a code to extract information from wunderground. However the script that I'm trying to adapt was written in 2008 and the formating on weather underground has changed. I'm having trouble with soup.body.nobr.b.string. I want to extrac...
Having trouble using BeautifulSoup to parse WeatherUnderground
I'm trying to adapt a code to extract information from wunderground. However the script that I'm trying to adapt was written in 2008 and the formating on weather underground has changed. I'm having trouble with soup.body.nobr.b.string. I want to extract daily percipitation data from a given site. http://www.wundergroun...
[ "Don't mess with parsing the HTML, it'll likely change again without notice.\nGet one of their CSV files (there are links at the bottom of the HTML pages), and parse it with the csv module.\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007976200_beautifulsoup_python.txt
Q: Python Opengl Texture Repeat I am a beginner in opengl. I am trying to repeat the texture on the GL_QUADS. So far Here is the code for loading the texture, file = os.path.join('image','texture.png') surface = image.load(file) self.t1 = surface.image_data.create_texture(image.Texture) glBindTexture...
Python Opengl Texture Repeat
I am a beginner in opengl. I am trying to repeat the texture on the GL_QUADS. So far Here is the code for loading the texture, file = os.path.join('image','texture.png') surface = image.load(file) self.t1 = surface.image_data.create_texture(image.Texture) glBindTexture(GL_TEXTURE_2D, t1.id) glTexPa...
[ "\nHow can I repeat the texture? Pardon me if i did wrong.\n\nBy using texture coordinates (glTexCoord) outside the range [0,1].\n" ]
[ 2 ]
[]
[]
[ "opengl", "pyglet", "python", "repeat", "textures" ]
stackoverflow_0007976684_opengl_pyglet_python_repeat_textures.txt
Q: Django Translation : User data --vs-- Site Content --vs-- UI static text? I am confused with how to proceed on Internationalization & Localizations, so I categorized a website's data as follows : Site Content : Content that is hosted by the website i.e. the data about the subject. Eg: Mobile Phone Site (Data abou...
Django Translation : User data --vs-- Site Content --vs-- UI static text?
I am confused with how to proceed on Internationalization & Localizations, so I categorized a website's data as follows : Site Content : Content that is hosted by the website i.e. the data about the subject. Eg: Mobile Phone Site (Data about mobile models, specs, prices, etc.) User Data : Data that is added by the use...
[ "\nUI text: gettext is the way to go.\nUser Data (Dynamic): Very simple: you don't translate it at all. The only things you could do is asking the users to provide more than one language (only few will do) or using machine translations (will piss of people - usually they prefer english over a crappy translation). E...
[ 0 ]
[]
[]
[ "django", "internationalization", "localization", "python" ]
stackoverflow_0007976495_django_internationalization_localization_python.txt
Q: Python application communicating with a web server? Ideas? I'm looking for a bit of web development advice. I'm fairly new to the area but I'm sure there are some gurus out there willing to part with some wisdom. Objective: I'm interested in controlling a Python application on my computer from my personal web hos...
Python application communicating with a web server? Ideas?
I'm looking for a bit of web development advice. I'm fairly new to the area but I'm sure there are some gurus out there willing to part with some wisdom. Objective: I'm interested in controlling a Python application on my computer from my personal web hosted site. I know, this question has been asked several times bef...
[ "Just thinking out loud for how I would start out with this. First, regarding the website itself, you can just use what's easiest to you, or to the environment you're in. For example, a basic PHP page will do just fine, but if you can get a site running in Python as well, I'd prefer using the same language all over...
[ 2 ]
[]
[]
[ "http", "python", "sockets" ]
stackoverflow_0007975031_http_python_sockets.txt
Q: Wrong tag name for lxml I am using lxml to parse xml I got from amazon product advertisement API. The tree is parsed as: root=etree.XML(self.sendRequest(parameters)) When I use root.tag or root.child.tag, I always get something like: {http://webservices.amazon.com/AWSECommerceService/2005-10-05}RequestProcessingT...
Wrong tag name for lxml
I am using lxml to parse xml I got from amazon product advertisement API. The tree is parsed as: root=etree.XML(self.sendRequest(parameters)) When I use root.tag or root.child.tag, I always get something like: {http://webservices.amazon.com/AWSECommerceService/2005-10-05}RequestProcessingTime The link appears in the ...
[ "The part between the braces is the XML namespace, which is read from the xmlns attribute of the element. You can't get rid of it, because this is just how the element tree API which lxml is based on is defined: All tag names are prefixed with their namespace in curly braces. \nSome notion of namespacing is manda...
[ 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0007976277_lxml_python.txt
Q: How do I make python processes run with correct process name? I have a few long term processes and temporary processes in Python. While shell and C programs run under their own names, all Python processes run as 'python filename.py', which makes it tough to identify processes. How can I make python processes show...
How do I make python processes run with correct process name?
I have a few long term processes and temporary processes in Python. While shell and C programs run under their own names, all Python processes run as 'python filename.py', which makes it tough to identify processes. How can I make python processes show up as 'logserver.py' or such in Linux? I use Python 2.7 in Ubuntu ...
[ "Add a shebang to the Python file in question, make the Python file executable (e.g. by chmod a+x ./logserver.py) and start it directly by ./logserver.py.\nA shebang is a line telling the kernel which interpreter to use. It's simply a line like #!/usr/bin/env python at the very beginning of the file.\n", "If you...
[ 9, 4 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0007976926_linux_python.txt
Q: Auction site with Django If one is to build an online auction site using Django, then would it be a good idea to modify an existing CMS? If so, could someone suggest a CMS for the scaffolding? Thanks A: You could starting building with django-cms which is a great CMS that is very much aimed at extensibility. It ...
Auction site with Django
If one is to build an online auction site using Django, then would it be a good idea to modify an existing CMS? If so, could someone suggest a CMS for the scaffolding? Thanks
[ "You could starting building with django-cms which is a great CMS that is very much aimed at extensibility. It has a plugin architecture which allows you to integrate your existing (or third party) apps. \nIf you are making an auction site though, it mightn't so much be a CMS you are after as much as a app-platform...
[ 3, 0 ]
[]
[]
[ "django", "e_commerce", "python" ]
stackoverflow_0007947032_django_e_commerce_python.txt
Q: What is the best way to loop through and process a large (10GB+) text file? I need to loop through a very large text file, several gigabytes in size (a zone file to be exact). I need to run a few queries for each entry in the zone file, and then store the results in a searchable database. My weapons of choice at t...
What is the best way to loop through and process a large (10GB+) text file?
I need to loop through a very large text file, several gigabytes in size (a zone file to be exact). I need to run a few queries for each entry in the zone file, and then store the results in a searchable database. My weapons of choice at the moment, mainly because I know them, are Python and MySQL. I'm not sure how wel...
[ "You shouldn't have any real trouble storing that amount of data in MySQL, although you will probably not be able to store the entire database in memory, so expect some IO performance issues. As always, make sure you have the appropriate indices before running your queries.\nThe most important thing is to not try ...
[ 6, 0 ]
[]
[]
[ "large_files", "mysql", "parsing", "python", "scripting" ]
stackoverflow_0007975774_large_files_mysql_parsing_python_scripting.txt
Q: How to iterate over case insensitive sorted dictionary items? Example: >>> d = {'answer':1, 'Question':2} >>> for i, j in sorted(d.items()): print i Question answer I would like case insensitive list: answer Question and I believe it can be done in simple Pythonic way. A: If it's just about printing the keys: ...
How to iterate over case insensitive sorted dictionary items?
Example: >>> d = {'answer':1, 'Question':2} >>> for i, j in sorted(d.items()): print i Question answer I would like case insensitive list: answer Question and I believe it can be done in simple Pythonic way.
[ "If it's just about printing the keys:\nfor i in sorted(d.keys(), key=lambda x: x.lower()): print i\n\nIf you need the values afterwards, you could do \nfor i, j in sorted(d.items(), key=lambda x: x[0].lower()): print i, j\n\nEDIT: Even shorter and better (since you have d in scope):\nfor i in sorted(d, key=str.low...
[ 10, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007977318_python.txt
Q: fast bubble sort def bubble(lst): swap = 'True' counter = 0 n = len(lst) m = len(lst) while swap == 'True': for j in range(n-1): if lst[j] > lst[j+1]: lst[j],lst[j+1] = lst[j+1],lst[j] counter += 1 ...
fast bubble sort
def bubble(lst): swap = 'True' counter = 0 n = len(lst) m = len(lst) while swap == 'True': for j in range(n-1): if lst[j] > lst[j+1]: lst[j],lst[j+1] = lst[j+1],lst[j] counter += 1 swa...
[ "Change algorithm.\nUse MergeSort or QuickSort.\nBubbleSort is O(n*n).\nThe only reason it exists is to show students how they should not sort arrays :)\nMergeSort is worst case O(n log n).\nQuickSort is O(n * n) worst case, average case O(n log n), but with \"low constants\", so it's usually faster than merge sort...
[ 4 ]
[ "def bubble(lol):\n lol.sort()\n return lol\n\n" ]
[ -3 ]
[ "python", "sorting" ]
stackoverflow_0007975994_python_sorting.txt
Q: How can I capture output and show it at the same time with Python? I have a pretty long running job, which runs for several minutes and then gets restarted. The task outputs various information which I capture like this: output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate() The thing is, I will only...
How can I capture output and show it at the same time with Python?
I have a pretty long running job, which runs for several minutes and then gets restarted. The task outputs various information which I capture like this: output = subprocess.Popen(cmd,stdout=subprocess.PIPE).communicate() The thing is, I will only get the entire output at a time. I would like to show output as the pro...
[ "You can try something like this : \ncmd = [\"./my_program.sh\"]\np = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE) # launch the process\nwhile p.poll() is None: # check if the process is still alive\n out = p.stdout.readline() # if it is still alive, grab the output\n do_something...
[ 5, 3 ]
[ "You can use the \"tee\" command. It does exactly what you need from it.\nhttp://www.computerhope.com/unix/utee.htm\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007977829_python.txt
Q: Python - short way to unpack list for string formatting operator? Variations of the * or ** operators don't seem to work, unfortunately: lstData = [1,2,3,4] str = 'The %s are %d, %d, %d, and %d' % ('numbers', *lstData) Is there an easy way? A: Use format: str = 'The {} are {}, {}, {}, and {}'.format('numbers', ...
Python - short way to unpack list for string formatting operator?
Variations of the * or ** operators don't seem to work, unfortunately: lstData = [1,2,3,4] str = 'The %s are %d, %d, %d, and %d' % ('numbers', *lstData) Is there an easy way?
[ "Use format:\nstr = 'The {} are {}, {}, {}, and {}'.format('numbers', *lstData)\n\nsee the docs for more details about possible formatting (floats, decimal points, conversion, ..).\n", "s = 'The %s are %d, %d, %d, and %d' % tuple(['numbers'] + lstData)\n\n", ">>> data = range(5)\n>>> 'The {0} are {1}, {2}, {3},...
[ 13, 4, 2 ]
[]
[]
[ "formatting", "python", "string", "tuples" ]
stackoverflow_0007978144_formatting_python_string_tuples.txt
Q: Python-Cannot convert string to float...manipulating a text file To all: I have a question about converting from string to float in python and any python advice you can give about my code. I think the best way to show you my problem is to explain what I am doing. I have a txt file that is generated from a fortr...
Python-Cannot convert string to float...manipulating a text file
To all: I have a question about converting from string to float in python and any python advice you can give about my code. I think the best way to show you my problem is to explain what I am doing. I have a txt file that is generated from a fortran program. This text file is of the form: 0.000 0.000 0.000...
[ "The biggest problem you'll run into is making sure you can tell the difference between states. As someone else pointed out, how do you know you don't have a time and 99 cells or an additional 100 cells that are carrying over from the previous line?\nI would start by trying to find out something unique about the da...
[ 0, 0 ]
[]
[]
[ "python", "text" ]
stackoverflow_0007969457_python_text.txt
Q: Can eventlet manage an AMQP connection with messages passing asynchronously both in and out? Actual Design: For those returning to this question, the helpful answer below pushed me towards a workable design that is running fine. Three insights were key: Eventlet is a very safe environment — if two greenlets both ...
Can eventlet manage an AMQP connection with messages passing asynchronously both in and out?
Actual Design: For those returning to this question, the helpful answer below pushed me towards a workable design that is running fine. Three insights were key: Eventlet is a very safe environment — if two greenlets both try recv() to or both try send() from the same socket simultaneously, then Eventlet elegantly kill...
[ "After reading your post and working with gevent a similar libary as eventlet a few things became clear to me because I just solved a similar problem\nIn general there is no need for locking since there ever is only one eventlet or greenlet running at the same time as long none of them are blocking everything seems...
[ 5 ]
[]
[]
[ "amqp", "asynchronous", "eventlet", "python" ]
stackoverflow_0007974618_amqp_asynchronous_eventlet_python.txt
Q: XML indentation on minidom python I'm trying to append a new child on a XML file, the problem is that I can't give the appropriate format to the child before inserting it in the XML document. I Have created the child with minidom.Document() and then appendChild to books. Do I explained well? Thanks in advance. A:...
XML indentation on minidom python
I'm trying to append a new child on a XML file, the problem is that I can't give the appropriate format to the child before inserting it in the XML document. I Have created the child with minidom.Document() and then appendChild to books. Do I explained well? Thanks in advance.
[ "Indentation of snippets of XML is a tricky business for XML processors: they are allowed to perform many transformation that you would not expect and they are not allowed to reindent elements in the way you would like without your explicit consent.\nHave a look at Pretty printing XML in Python to see how you can i...
[ 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0007978293_minidom_python_xml.txt
Q: Timeit Python. How does it work? I want to time a function and I'd like to use the timeit library. I can't find any good example on the net. I have to time the function "largest_eigenvector" which is in the maxcut library, this function takes as input a graph G wich is returned by a function in the networkx librar...
Timeit Python. How does it work?
I want to time a function and I'd like to use the timeit library. I can't find any good example on the net. I have to time the function "largest_eigenvector" which is in the maxcut library, this function takes as input a graph G wich is returned by a function in the networkx library. So I want to time this block of cod...
[ "You have statement and setup swapped. Pass the arguments to Timer() the other way round.\n", "Try this:\ndef tmp():\n import maxcut as mc \n import networkx as nx \n G = nx.complete_graph(3)\n mc.largest_eigenvector(G)\n\nt = timeit.Timer(s, 'tmp()')\n\nThe following might work, too:\nt = timeit.Time...
[ 4, 2 ]
[]
[]
[ "python", "syntax", "timeit", "timer" ]
stackoverflow_0007978892_python_syntax_timeit_timer.txt
Q: How can I detect if IntelliJ IDEA or PyCharm is installed and get the path to the exe on Windows by using Python? I am looking for a piece of code Python code that would give me the path to IntelliJ IDEA or PyCharm exe if they are installed. Usually, I would want to detect the same for Eclipse but it seems that Ec...
How can I detect if IntelliJ IDEA or PyCharm is installed and get the path to the exe on Windows by using Python?
I am looking for a piece of code Python code that would give me the path to IntelliJ IDEA or PyCharm exe if they are installed. Usually, I would want to detect the same for Eclipse but it seems that Eclipse doesn't have an installer :(
[ "The installation path is stored in the registry:\nHKEY_CURRENT_USER\\JetBrains\\IntelliJ IDEA\\<build number>\\(Default)\n(replace IntelliJ IDEA with PyCharm if you need the PyCharm installation path)\nYou can use the _winreg module to read the registry and retrieve the path.\n" ]
[ 1 ]
[]
[]
[ "intellij_idea", "pycharm", "python" ]
stackoverflow_0007971603_intellij_idea_pycharm_python.txt
Q: What is the use of the first argument to Django's patterns method? What is the significance of the first argument (containing '' in the example below) to patterns? urlpatterns = patterns('', (r'^articles/2003/$', 'news.views.special_case_2003'), (r'^articles/(\d{4})/$', 'news.views.year_archive'), ) Somet...
What is the use of the first argument to Django's patterns method?
What is the significance of the first argument (containing '' in the example below) to patterns? urlpatterns = patterns('', (r'^articles/2003/$', 'news.views.special_case_2003'), (r'^articles/(\d{4})/$', 'news.views.year_archive'), ) Sometimes I've seen it filled in, like this: urlpatterns = patterns( 'zin...
[ "It's a prefix to the view paths. See the documentation for patterns.\nThe equivalent of your first example using this argument is:\nurlpatterns = patterns('news.views',\n (r'^articles/2003/$', 'special_case_2003'),\n (r'^articles/(\\d{4})/$', 'year_archive'),\n)\n\nThe equivalent of your second example with ...
[ 6, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007979248_django_python.txt
Q: Is there an existing library or set of scripts to write recurring event strings for the Google Calendar API in Python? I have a Python-based program that adds events to a Google Calendar. To add events that repeat, I need to specify a recurrent_data string that conforms to the RFC 2445 standard. An example is belo...
Is there an existing library or set of scripts to write recurring event strings for the Google Calendar API in Python?
I have a Python-based program that adds events to a Google Calendar. To add events that repeat, I need to specify a recurrent_data string that conforms to the RFC 2445 standard. An example is below, from http://code.google.com/apis/calendar/data/1.0/developers_guide_python.html#CreatingRecurring: 'DTSTART;VALUE=DATE:20...
[ "All I found was the iCalendar module which can create RFC 2445-compliant data. Your best bet right now might be creating a template based on the Example section here provided by Google.\n", "There is another library called icalendar which is available as node.js npm module called icalendar.\n" ]
[ 1, 0 ]
[]
[]
[ "google_calendar_api", "icalendar", "python", "rfc2445" ]
stackoverflow_0005370607_google_calendar_api_icalendar_python_rfc2445.txt
Q: Python regular words cut I have string: './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]' I need string: '27-10-2011 17:07:02' How can i do this in python? A: There are many ways to do this, one way is to use str.partition: text='./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]' before...
Python regular words cut
I have string: './money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]' I need string: '27-10-2011 17:07:02' How can i do this in python?
[ "There are many ways to do this, one way is to use str.partition:\ntext='./money.log_rotated.27.10.2011_17:15:01:[27-10-2011 17:07:02]'\nbefore,_,after = text.partition('[')\nprint(after[:-1])\n# 27-10-2011 17:07:02\n\nAnother is to use str.split:\nbefore,after = text.split('[',1)\nprint(after[:-1])\n# 27-10-2011 1...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007979446_python.txt
Q: Python: Split numpy array I have an array produced by numpy which looks as follows: [ 54.51399994 -12.10200024 -11.88099957] [ 56.23899841 -8.30799961 -2.03500009] How do i convert this to a list? So it looks as follows: ['54.51399994','-12.10200024','-11.88099957'] ['56.23899841','-8.30799961','-2.035000...
Python: Split numpy array
I have an array produced by numpy which looks as follows: [ 54.51399994 -12.10200024 -11.88099957] [ 56.23899841 -8.30799961 -2.03500009] How do i convert this to a list? So it looks as follows: ['54.51399994','-12.10200024','-11.88099957'] ['56.23899841','-8.30799961','-2.03500009']
[ "You could use astype() to create a new array of string dtype:\nimport numpy as np\narr=np.array([\n ( 54.51399994, -12.10200024, -11.88099957),\n ( 56.23899841, -8.30799961, -2.03500009)])\nprint(arr.astype('|S10'))\n\nyields\n[['54.51399994', '-12.10200024', '-11.88099957'], ['56.23899841', '-8.30799961', '...
[ 5 ]
[]
[]
[ "arrays", "list", "numpy", "python" ]
stackoverflow_0007979632_arrays_list_numpy_python.txt
Q: Python crawling from main sites' urls and clean tags save to files with www and urls directly import urllib2 import urllib from lxml.html import fromstring from lxml.html.clean import Cleaner from formatter import NullFormatter import cookielib import urllib,time import urlparse import datetime import new from htm...
Python crawling from main sites' urls and clean tags save to files with www and urls directly
import urllib2 import urllib from lxml.html import fromstring from lxml.html.clean import Cleaner from formatter import NullFormatter import cookielib import urllib,time import urlparse import datetime import new from htmllib import HTMLParser from lxml.html import fromstring from lxml.html.clean import Cleaner import ...
[ "I'm going on a wild guess here since I don't really know what you are trying to achieve, but don't you mean to replace\nparser.feed( open(tmp[0]).read( ) )\n\nwith\nparser.feed( tagclean(url) )\n\nIf not, you really need to elaborate your question.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007978637_python.txt
Q: How to refactor methods in Python in order to make them private? I know that there is no such thing as true private in Python for sometimes you need to following: prevent people from calling some methods or warn them when they do, but allow them to be called from other modules detect where these methods are used ...
How to refactor methods in Python in order to make them private?
I know that there is no such thing as true private in Python for sometimes you need to following: prevent people from calling some methods or warn them when they do, but allow them to be called from other modules detect where these methods are used and raise an warning on the console or even an exception, this would a...
[ "Python has the philosophy of \"consenting adults\": Prefix methods with an underscore to mark them as private. Don't call any methods with a leading underscore from the outside. If you do, you're on your own. You are free to do so, but you have been warned.\nTo adopt this convetion in an existing code base, ren...
[ 7, 1, 0, 0 ]
[]
[]
[ "private", "python" ]
stackoverflow_0007979714_private_python.txt
Q: Creating a variable that can be compared across processes I have code like the following, class _Process(multiprocessing.Process): STOP = multiprocessing.Manager().Event() def __init__(self, queue, process_fn): self._q = queue self._p = process_fn super().__init__() def run(...
Creating a variable that can be compared across processes
I have code like the following, class _Process(multiprocessing.Process): STOP = multiprocessing.Manager().Event() def __init__(self, queue, process_fn): self._q = queue self._p = process_fn super().__init__() def run(self): while True: dat = self._q.get() ...
[ "This is a weird way to use an Event object... If you can't use None or a boolean, I suggest you use a dedicated class and test the type of what you get from the queue:\nclass StopProcessing(object):\n pass\n\n#...\n\nq.put(StopProcessing())\n\n#...\n\nwhile True:\n dat = self._q.get()\n if type(dat) is St...
[ 3 ]
[]
[]
[ "multiprocessing", "process", "python", "python_3.x" ]
stackoverflow_0007979771_multiprocessing_process_python_python_3.x.txt
Q: Splitting large text file by a delimiter in Python I imaging this is going to be a simple task but I can't find what I am looking for exactly in previous StackOverflow questions to here goes... I have large text files in a proprietry format that look comething like this: :Entry - Name John Doe - Date 20/12/1979 :...
Splitting large text file by a delimiter in Python
I imaging this is going to be a simple task but I can't find what I am looking for exactly in previous StackOverflow questions to here goes... I have large text files in a proprietry format that look comething like this: :Entry - Name John Doe - Date 20/12/1979 :Entry -Name Jane Doe - Date 21/12/1979 And so forth. T...
[ "You could use itertools.groupby to group lines that occur after :Entry into lists:\nimport itertools as it\nfilename='test.dat'\n\nwith open(filename,'r') as f:\n for key,group in it.groupby(f,lambda line: line.startswith(':Entry')):\n if not key:\n group = list(group)\n print(group...
[ 15, 6 ]
[]
[]
[ "python", "text_parsing" ]
stackoverflow_0007980288_python_text_parsing.txt
Q: Item_search not returning all offers I'm using the item_search method of the amazon product api, but noticed that even though the total number of offers returned can be pretty high, not all the offers are returned by item_search. Is there a way to get item_search to return all the offers? I'm using the 'Large' res...
Item_search not returning all offers
I'm using the item_search method of the amazon product api, but noticed that even though the total number of offers returned can be pretty high, not all the offers are returned by item_search. Is there a way to get item_search to return all the offers? I'm using the 'Large' response group.
[ "You need to use the OfferFull response group to get a full page of offers (10 offers per page). \nThe TotalOfferPages node returned in the response shows how many pages of offers there are. To get a particular page, set the OfferPage request parameter to a number less than or equal to TotalOfferPages.\nFor examp...
[ 1 ]
[]
[]
[ "amazon", "amazon_product_api", "amazon_web_services", "python" ]
stackoverflow_0007303041_amazon_amazon_product_api_amazon_web_services_python.txt
Q: In Git, how do I configure a hook to run a server-side commands after a commit is accepted? I'm trying to figure out my way with the Django localistion stuff and from what i've understood, the makemessages command needs to be run every time you change some strings in code. I was thinking of simplifying this proces...
In Git, how do I configure a hook to run a server-side commands after a commit is accepted?
I'm trying to figure out my way with the Django localistion stuff and from what i've understood, the makemessages command needs to be run every time you change some strings in code. I was thinking of simplifying this process by using a server-side Git hook. I have no knowledge about Git hooks and couldn't find any res...
[ "Sure thing!\nAdd a script called post-receive to the server side git repository in the .git/hooks/ directory. \nMake sure that the file is executable.\nCall makemessages from the script.\nDone! (I think...)\nYou'll find some example scripts in the directory already, with most available hooks.\nHave a look at the o...
[ 10 ]
[]
[]
[ "django", "git", "githooks", "localization", "python" ]
stackoverflow_0007980053_django_git_githooks_localization_python.txt
Q: Getting the red price listed on products on amazon through the product services api I'm trying to get a list of products and their prices using the item_search api, that corresponds to the list of products on amazon. I am able to get a matching set of products, but am not able to consistently get the prices listed...
Getting the red price listed on products on amazon through the product services api
I'm trying to get a list of products and their prices using the item_search api, that corresponds to the list of products on amazon. I am able to get a matching set of products, but am not able to consistently get the prices listed in red on the website. I am getting the price through the first offer, Offers>>Offer>>Of...
[ "\nIf by \"red price\" you mean the $17.87 pointed to in the image above then this is the price that the product is sold at by the MerchantId of Amazon.com which is returned in the OfferFull response group.\nTo get only Amazon.com offer listings returned in the response, set the MerchantId request attribute to Amaz...
[ 1 ]
[]
[]
[ "amazon", "amazon_product_api", "amazon_web_services", "python" ]
stackoverflow_0007302593_amazon_amazon_product_api_amazon_web_services_python.txt
Q: Python: Matching a string to list item? cords = [] for y in range(10): for x in range(10): cords.append((x, y)) print cords print cords[11] user_x=raw_input("X: ") user_y=raw_input("Y: ") xy = "("+user_x+", "+user_y+")" print xy if xy in cords: print "Found Match" My question is, why does...
Python: Matching a string to list item?
cords = [] for y in range(10): for x in range(10): cords.append((x, y)) print cords print cords[11] user_x=raw_input("X: ") user_y=raw_input("Y: ") xy = "("+user_x+", "+user_y+")" print xy if xy in cords: print "Found Match" My question is, why doesn't it print "Found Match", when given 1 and...
[ "Because a string will never be equal to a tuple.\nxy = (int(user_x), int(user_y))\n\n", "I haven't run the code, but it looks like:\n\nxy = \"(\"+user_x+\", \"+user_y+\")\"\n\nis a string like so: \n\n\"(3, 2)\"\n\nYour list is a list of tuples.\n", "Because \"(\"+user_x+\", \"+user_y+\")\" results in a string...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007980645_python.txt
Q: how to customize ModelForm filled data I have this model: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") With this form: class GalleryForm(ModelForm): class Meta: model = Gallery And this view: gform = GalleryForm(request.POST, request.FILES, instance=galleryInstance...
how to customize ModelForm filled data
I have this model: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") With this form: class GalleryForm(ModelForm): class Meta: model = Gallery And this view: gform = GalleryForm(request.POST, request.FILES, instance=galleryInstance) In template a filled form is shown. For t...
[ "To prevent it from showing, use any of these three options:\n\nSet editable=False on the model field;\nUse the fields attribute of the ModelForm's inner Meta class.\nUse the exclude attribute of the ModelForm's inner Meta class.\n\nWhich one to use depends on how often you want the field to show (never, or in sele...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007980433_django_django_forms_python.txt
Q: how do I escape a forward slash in xpath? How do I escape the forward slash character in an xpath query? My tags contain a url, so I need to be able to do this. I am using lxml in python. Alternatively, is it possible for xpath to query a substring of the path? Examples are below: xml=""" <entry xmlns="http://w...
how do I escape a forward slash in xpath?
How do I escape the forward slash character in an xpath query? My tags contain a url, so I need to be able to do this. I am using lxml in python. Alternatively, is it possible for xpath to query a substring of the path? Examples are below: xml=""" <entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsa="http://schemas....
[ "Look into namespace prefixes[docs].\nIf you want an element that's in the http://schemas.google.com/gsa/2007 namespace you need to search for it like so:\nimport lxml.etree as et\n\nxml=\"\"\"\n<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:gsa=\"http://schemas.google.com/gsa/2007\">\n <gsa:content name=\"rep...
[ 3 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0007980841_lxml_python_xml_xpath.txt
Q: Trying to zip files in one directory only I have the path /home/mine/new that contains files and sub directories. I want to zip the files that are in that path only (in the 'new' path), so that my zipped folder contains /new/file1, new/file2, etc. I tried this : import zipfile import os,glob def zipfunc(path, myz...
Trying to zip files in one directory only
I have the path /home/mine/new that contains files and sub directories. I want to zip the files that are in that path only (in the 'new' path), so that my zipped folder contains /new/file1, new/file2, etc. I tried this : import zipfile import os,glob def zipfunc(path, myzip): for path,dirs, files in os.walk(path)...
[ "You're calling os.path.basename on the path variable. That means that if you're trying to zip the file new/dir1/file1, you drop the new/ part of the path and end up with dir1/file1, which isn't a valid path relative to your current directory.\nIf you simply remove the call to os.path.basename it will zip up the f...
[ 2, 0, 0 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0007980919_python_zip.txt
Q: How to make an if loop of a file existence, in python? I'm trying to run a series of commands for two input files, but I want to avoid doing the same thing if it has already been done. To make it more clear, these are my commands: from subprocess import call import os.path pathway = raw_input("Please give the p...
How to make an if loop of a file existence, in python?
I'm trying to run a series of commands for two input files, but I want to avoid doing the same thing if it has already been done. To make it more clear, these are my commands: from subprocess import call import os.path pathway = raw_input("Please give the pathway of your Genome Folder ( .fa files): ") genome= raw_in...
[ "Try:\nif not os.path.isfile(\"%s.stidx\"%genome):\n cmd = \"python /space/tierzucht/mgholami/stampy-1.0.13/stampy.py -G %s %s/*.fa\" %(genome, pathway)\n\nIn your original code, the paretheses were misplaced (the % was getting interpreted as the remainder operator, so the interpreter did not complain about a synt...
[ 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007981290_if_statement_python.txt
Q: Efficient reading of values in a binary file I have a lot of binary files containing output of a numerical model. They are flat binary files containing output as floating point numbers. The files correspond to a four-dimensional array sorted in t-z-y-x order with x varying fastest. The thing is that for given x,y ...
Efficient reading of values in a binary file
I have a lot of binary files containing output of a numerical model. They are flat binary files containing output as floating point numbers. The files correspond to a four-dimensional array sorted in t-z-y-x order with x varying fastest. The thing is that for given x,y and z I need the values for all t. The simple solu...
[ "Possible options could involve\n\nto use mmap.\nWith this, you map a file into the memory area, making its contents accessible as if it were in RAM. The components are read in as soon as they are accessed/needed, probably in the normal page size of the OS (4 kiB).\n\nto read the complete file into memory. This doe...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007981516_python.txt
Q: Trouble repeating elements using TAL, Chameleon and Pyramid I'm really struggling to get TAL and Chameleon/Pyramid to play nice. . . I have a view in Pyramid that returns, for example, the following: def view(request): return {'results' : [ {'name':'alice', 'value':22}, {'name':'bob...
Trouble repeating elements using TAL, Chameleon and Pyramid
I'm really struggling to get TAL and Chameleon/Pyramid to play nice. . . I have a view in Pyramid that returns, for example, the following: def view(request): return {'results' : [ {'name':'alice', 'value':22}, {'name':'bob', 'value':11}, {'name':'charlie', 'val...
[ "Weird. I think this should work.\nAnyway, your use of tal:replace here is wrong as it's gonna replace the whole tag. What you want is to replace the contents of the tag with tal:content:\n<tr tal:repeat=\"row results\">\n <td tal:content=\"python:row['name']\">the name</td>\n <td tal:content=\"python:row['v...
[ 5 ]
[]
[]
[ "chameleon", "pyramid", "python", "template_tal" ]
stackoverflow_0007981275_chameleon_pyramid_python_template_tal.txt
Q: join produced number convert to int Example: import re rx = re.compile("{0-9}") Var1 =bla bla bla 54467 Var2= rx.findall(Var1) number = ''.join(Var2) My question is how to convert the number variable to int, i try to do so with int() but i get an error. Or is there a way to create such a variable as int with anot...
join produced number convert to int
Example: import re rx = re.compile("{0-9}") Var1 =bla bla bla 54467 Var2= rx.findall(Var1) number = ''.join(Var2) My question is how to convert the number variable to int, i try to do so with int() but i get an error. Or is there a way to create such a variable as int with another method?
[ "Don't use regular expressions for this. filter() is uch easier and quicker:\n>>> s = \"bla bla bla 54467 bla\"\n>>> int(filter(str.isdigit, s))\n54467\n\nThe above code will merge all numbers in the string into a single string. If you don't want this, use\n>>> s = \"bla 1223 bla 54467 bla\"\n>>> map(int, filter(...
[ 5, 4 ]
[]
[]
[ "join", "python" ]
stackoverflow_0007982050_join_python.txt
Q: Why do indented explicit line continuations not allow comments in Python? I'm writing a Python parser to learn Flex and Bison, and I'm trying to find out why only the first of these programs is valid Python. a.py: \ # This is valid Python produces no error. b.py: \ # This is not valid Python produces this er...
Why do indented explicit line continuations not allow comments in Python?
I'm writing a Python parser to learn Flex and Bison, and I'm trying to find out why only the first of these programs is valid Python. a.py: \ # This is valid Python produces no error. b.py: \ # This is not valid Python produces this error: File "b.py", line 1 \ ^ IndentationError: unexpected indent and...
[ "It's an implementation detail.\nHere's how a few different implementations respond to your code:\n a.py b.py c.py \n ---- ---- ----\nCPython 2.6.5 ok bad bad\nCPython 3.? ok bad bad\nJython 2.2.1 ok ok bad\nJython 2.5.2 bad bad bad\nIro...
[ 4, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007981757_python.txt
Q: Why does this python re match? Can someone explain this weird behavior of python re? Obviously the string 'test' does not contain either 'Bid' or 'Ask'. Why is this matching? import re pat=r'[Bid|Ask]' reg=re.compile(pat) if reg.search('test'): print "matched!" ... matched! A: [...]defines a character class, m...
Why does this python re match?
Can someone explain this weird behavior of python re? Obviously the string 'test' does not contain either 'Bid' or 'Ask'. Why is this matching? import re pat=r'[Bid|Ask]' reg=re.compile(pat) if reg.search('test'): print "matched!" ... matched!
[ "[...]defines a character class, matching any character listed inside. What you wanted is par = r'(Bid|Ask)'.\nHowever, you should not use regex for this at all, do the following instead:\nif whatever in ('Bid', 'Ask'):\n # it's one of these two\nelse:\n # it isn't\n\nIf you need to perform a substring check ...
[ 10, 5, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007982446_python_regex.txt
Q: Does Python use copy-on-write for copies of lists? Suppose I copy an existing list: existing_list = [ 1, 2, 3 ]; copied_list = existing_list[:] ... copied_list[2] = 'a' // COW happens here [Some edits] I heard that Python uses copy-on-write when either copied_list or existing_list is mutated. Is this true? Seem...
Does Python use copy-on-write for copies of lists?
Suppose I copy an existing list: existing_list = [ 1, 2, 3 ]; copied_list = existing_list[:] ... copied_list[2] = 'a' // COW happens here [Some edits] I heard that Python uses copy-on-write when either copied_list or existing_list is mutated. Is this true? Seems to me like an over-complication that requires locking ...
[ "There is no copy-on-write. When you run copied_list = existing_list[:], a new list is built and populated immediately. Here is the source: http://hg.python.org/cpython/file/2.7/Objects/listobject.c#l467\n", "This isn't \"copy-on-write\", this is \"existing references continue to exist until replaced\". Nothin...
[ 8, 2, 2, 1 ]
[]
[]
[ "copy_on_write", "python" ]
stackoverflow_0007981312_copy_on_write_python.txt
Q: How do i create a test Suite in python unittest i tried: def buildTestSuite(): suite = unittest.TestSuite() for testcase in glob.glob('src/testsuite/test_*.py'): module = os.path.splitext(testcase)[0] print module print type(module) suite.addTest(__import__(module).buildTest...
How do i create a test Suite in python unittest
i tried: def buildTestSuite(): suite = unittest.TestSuite() for testcase in glob.glob('src/testsuite/test_*.py'): module = os.path.splitext(testcase)[0] print module print type(module) suite.addTest(__import__(module).buildTestSuite()) return suite but i get eror: Traceback ...
[ "def buildTestSuite():\n suite = unittest.TestSuite()\n for testcase in glob.glob('src/testsuite/test_*.py'):\n modname = os.path.splitext(testcase)[0]\n module=__import__(modname,{},{},['1'])\n suite.addTest(unittest.TestLoader().loadTestsFromModule(module))\n return suite\n\n", "Tr...
[ 5, 0 ]
[]
[]
[ "python", "python_unittest" ]
stackoverflow_0007982439_python_python_unittest.txt
Q: Fastest stdin/out IO in python 3? I've been solving a few problems on SPOJ.pl using python 3.1.2 and some peoples fast result on simple problems makes me wonder if there is a faster way to handle input and output. I've tried using input() print() and sys.stdin.readline() sys.stdout.write() or rather for line in...
Fastest stdin/out IO in python 3?
I've been solving a few problems on SPOJ.pl using python 3.1.2 and some peoples fast result on simple problems makes me wonder if there is a faster way to handle input and output. I've tried using input() print() and sys.stdin.readline() sys.stdout.write() or rather for line in sys.stdin: #Handle input sys.s...
[ "The following will probably be fastest:\n\nRead all the input at once using os.read(0, some_big_enough_number).\nProcess the output, collecting the results in a list results.\nWrite all the output at once using os.write(1, \"\".join(results)).\n\nI remember one case where I noticed that os.read() and os.write() ar...
[ 15, 2, 1 ]
[]
[]
[ "io", "performance", "python", "python_3.x", "stdin" ]
stackoverflow_0007982146_io_performance_python_python_3.x_stdin.txt
Q: Multiple figure arrangement using Matplotlib Can we control where Matplotlib places figures on the screen? I want to generate four figures (in four separate windows) that do not overlap. A: From IPython you can do the following: figure() get_current_fig_manager().window.wm_geometry("400x600+20+40") Or equivalen...
Multiple figure arrangement using Matplotlib
Can we control where Matplotlib places figures on the screen? I want to generate four figures (in four separate windows) that do not overlap.
[ "From IPython you can do the following:\nfigure()\nget_current_fig_manager().window.wm_geometry(\"400x600+20+40\")\n\nOr equivalently in a Python script:\nimport pylab as pl\npl.figure()\npl.get_current_fig_manager().window.wm_geometry(\"400x600+20+40\")\npl.show()\n\nNote that this assumes you're using the TkAgg b...
[ 8, 3, 0, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0001677571_matplotlib_python.txt
Q: py3k: Maximum Number In Given List - short form We are given list of numbers l , example: l=[5,2,4,3] What is short form of extracting maximum number - in other words - short form of this: x=l[0] for i in l: if x<i : x=i ? A: You are probably looking for the max() function. >>> my_list = [5, 2, 4, 3] >>> ma...
py3k: Maximum Number In Given List - short form
We are given list of numbers l , example: l=[5,2,4,3] What is short form of extracting maximum number - in other words - short form of this: x=l[0] for i in l: if x<i : x=i ?
[ "You are probably looking for the max() function.\n>>> my_list = [5, 2, 4, 3]\n>>> max(my_list)\n5\n\n" ]
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007983030_python_python_3.x.txt
Q: Opening a text file in Python I am having trouble reading a text file to a list, what I have at the moment is: lines = open ('dracula.txt', 'r'). readlines () where dracula.txt is the text file in the same directory as the program, however upon running the program Python comes up with: No such file or directory:...
Opening a text file in Python
I am having trouble reading a text file to a list, what I have at the moment is: lines = open ('dracula.txt', 'r'). readlines () where dracula.txt is the text file in the same directory as the program, however upon running the program Python comes up with: No such file or directory: 'dracula.txt' I have no idea why ...
[ "The file name is looked up in the current working directory, which is not necessarily the same as the directory the script lives in. Try using the full path to the file, or make sure the working directory is correct. You can check the working directory py printing os.getcwd() from inside your script (make sure y...
[ 7, 1 ]
[]
[]
[ "file", "file_io", "python", "text" ]
stackoverflow_0007983099_file_file_io_python_text.txt
Q: cherrypy.request.body.read() error I'm having some problems accessing http requests' bodies with the CherryPy framework. I'm using CherryPy 3.2.0 on a x86_64 Arch Linux machine w/ Python3 and Aptana Web Studio IDE. When I try to access a request's body via the usual cherrypy.request.body.read(), i get the error Fi...
cherrypy.request.body.read() error
I'm having some problems accessing http requests' bodies with the CherryPy framework. I'm using CherryPy 3.2.0 on a x86_64 Arch Linux machine w/ Python3 and Aptana Web Studio IDE. When I try to access a request's body via the usual cherrypy.request.body.read(), i get the error File "/usr/lib/python3.2/site-packages/che...
[ "The body.read() method works properly only if the request body was processed, which happens only when request.process_request_body is True (it is by default) and when the request method is in request.method_with_bodies which is only PUT and POST by default, but not GET (which you probably used when requesting the ...
[ 10 ]
[]
[]
[ "cherrypy", "python", "request" ]
stackoverflow_0007982518_cherrypy_python_request.txt
Q: Sending mutlitple requests of httplib, raising traceback exceptions Here is the code: conn = httplib.HTTPConnection("127.0.0.1:8000") conn.request("POST", "/api/job/", some_params, headers) conn.close() no problem with sending request to server but if i use loop for example: for i in range(n): conn = httplib.H...
Sending mutlitple requests of httplib, raising traceback exceptions
Here is the code: conn = httplib.HTTPConnection("127.0.0.1:8000") conn.request("POST", "/api/job/", some_params, headers) conn.close() no problem with sending request to server but if i use loop for example: for i in range(n): conn = httplib.HTTPConnection("127.0.0.1:8000") conn.request("POST", "/api/job/", some...
[ "Looks to me like your buffer is getting filled. Your buffer will fill with any network requests you make, then is cleared when the server acknowledges receipt of the data. Not sure if there isn't a better way to do this, but you could try giving the server some time to acknowledge receipt by doing a short time.pau...
[ 1 ]
[]
[]
[ "django", "httplib", "python" ]
stackoverflow_0007982441_django_httplib_python.txt
Q: Rendering dynamically generated HTML through pyramid Response I am new to python's pyramid framework so kindly help me. I have a HTML dynamically generated. This HTML is generated by a python script which dynamically writes (tags/tables) which are extracted from some 'xyz.html' [using beautifulsoup] to another 'ab...
Rendering dynamically generated HTML through pyramid Response
I am new to python's pyramid framework so kindly help me. I have a HTML dynamically generated. This HTML is generated by a python script which dynamically writes (tags/tables) which are extracted from some 'xyz.html' [using beautifulsoup] to another 'abc.html'. Now i need to send this html page ('abc.html') back as a ...
[ "I'm a little surprised your first example doesn't work. Check out this cookbook entry on it from the Pyramid docs and see if that helps.\nhttp://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/static_assets/files.html#serving-file-content-dynamically\n" ]
[ 2 ]
[]
[]
[ "pyramid", "python", "python_2.6", "python_2.7", "python_2.x" ]
stackoverflow_0007981402_pyramid_python_python_2.6_python_2.7_python_2.x.txt
Q: parse annotated file I'm trying to parse a file that contains annotation of person names in the form <name> James Gold </name> said to meet with <name> Mable Helen </name> tomorrow night I'm trying to do this with python regex but it isn't working. I'm using annotation = re.findall(' <name>(.*)</name>', line...
parse annotated file
I'm trying to parse a file that contains annotation of person names in the form <name> James Gold </name> said to meet with <name> Mable Helen </name> tomorrow night I'm trying to do this with python regex but it isn't working. I'm using annotation = re.findall(' <name>(.*)</name>', lines) I want to recover all ...
[ "Assuming that it is just an annotated file and not an XML file (use Acorn's solution in that case), you should use some re flags to skip the newlines and use the . better:\n>>> src = \"\"\"<name> James Gold\n... </name> said to meet with <name> Mable Helen </name> tomorrow night\"\"\"\n>>>\n>>> [s.strip() for s i...
[ 4, 3, 0 ]
[]
[]
[ "annotations", "parsing", "python", "tags" ]
stackoverflow_0007982690_annotations_parsing_python_tags.txt
Q: py3k: mapping dictionary (string->number) into list (of strings) Assume we have dictionary that translates strings into numbers. How to reverse it into list ? Let assume, we can fill not mapped numbers with empty string ''. Here example how it works: >>> dic_into_list({'x':0, 'z':2, 'w':3}) ['x', '', 'z', 'w'] A:...
py3k: mapping dictionary (string->number) into list (of strings)
Assume we have dictionary that translates strings into numbers. How to reverse it into list ? Let assume, we can fill not mapped numbers with empty string ''. Here example how it works: >>> dic_into_list({'x':0, 'z':2, 'w':3}) ['x', '', 'z', 'w']
[ "d = {'x':0, 'z':2, 'w':3}\nlst = [\"\"] * (max(d.values()) + 1)\nfor k, v in d.items():\n lst[v] = k\nprint(lst)\n\nprints\n['x', '', 'z', 'w']\n\n", "The simplest way is to flip the dict and then iterate up to the maximum value (now key) in the dict:\noriginal = {'x':0, 'z':2, 'w':3}\nd = dict((v, k) for k, ...
[ 3, 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007983313_python_python_3.x.txt
Q: Cannot JSON serialize python Appengine GeoModel subclass using simple json I am working on a simple app engine application that utilize the geo-searching proximity_fetch. I perform the search and some extra filtering on the data, and all goes well (I checked the number of returned results, and it was just as expec...
Cannot JSON serialize python Appengine GeoModel subclass using simple json
I am working on a simple app engine application that utilize the geo-searching proximity_fetch. I perform the search and some extra filtering on the data, and all goes well (I checked the number of returned results, and it was just as expected ) However, when I tried to dump it into a json using simple json, I got the ...
[ "Complex Python objects must be representable as a dictionary of simple types in order to serialize to JSON. The \"object is not JSON serializable\" error basically means that Python's JSON encoder did not know how to serialize your object.\nSo if result is a GeoPt, you can serialize it like this:\nreturn json.dump...
[ 4 ]
[]
[]
[ "google_app_engine", "json", "python", "simplejson" ]
stackoverflow_0007983048_google_app_engine_json_python_simplejson.txt
Q: python: HTTP PUT with binary data So I adapted urllib2 as suggested by answers to another question: class HttpRequest(urllib2.Request): def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', 'GET') urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): return self._...
python: HTTP PUT with binary data
So I adapted urllib2 as suggested by answers to another question: class HttpRequest(urllib2.Request): def __init__(self, *args, **kwargs): self._method = kwargs.pop('method', 'GET') urllib2.Request.__init__(self, *args, **kwargs) def get_method(self): return self._method and it works nicely for PUT wit...
[ "It's because \n\ndata should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. \n\nfrom urllib2 doc\n", "You are trying to automatically convert a python unicode string to a regular by...
[ 1, 1 ]
[ "According to the urllib2 documentation, you will need to percent-encode the byte-string.\n" ]
[ -1 ]
[ "binary", "http", "put", "python" ]
stackoverflow_0007983303_binary_http_put_python.txt
Q: How to Include PyQt with Jython 2.5.2? I am planning to use PyQt with Jython because my app is based on Java. I have installed Jython successfully. But i am lacking in including PyQt with Jython. Any suggestions would be appreciative! P.S: I am totally new to Python. Thanks A: Hi, you cannot use PyQt with Jython...
How to Include PyQt with Jython 2.5.2?
I am planning to use PyQt with Jython because my app is based on Java. I have installed Jython successfully. But i am lacking in including PyQt with Jython. Any suggestions would be appreciative! P.S: I am totally new to Python. Thanks
[ "\nHi,\nyou cannot use PyQt with Jython.\nPyQt are Qt bindings for 'standard' Python implementation (CPython).\nIf you want to use Qt in your Java app, \nthen you can take a look at Qt Jambi (Qt bindings for Java, deprecated in 2009).\n" ]
[ 3 ]
[]
[]
[ "jython", "pyqt", "python" ]
stackoverflow_0007983075_jython_pyqt_python.txt
Q: How to test Python function decorators? I'm trying to write unit tests to ensure correctness of various decorators I've written. Here's the start of the code I'm trying to write: import unittest from memoizer import Memoizer from strategies.mru import MRU @Memoizer(strategy=MRU(maxsize=10)) def fib(x): if x < ...
How to test Python function decorators?
I'm trying to write unit tests to ensure correctness of various decorators I've written. Here's the start of the code I'm trying to write: import unittest from memoizer import Memoizer from strategies.mru import MRU @Memoizer(strategy=MRU(maxsize=10)) def fib(x): if x < 2: return 1 else: return fib(x-1) ...
[ "Take a look at the tests in the standard library for examples: http://hg.python.org/cpython/file/3.2/Lib/test/test_functools.py#l553\nI usually add some instrumentation to the function being wrapped so that I can monitor the calls.\nInstead of memoizing the test function at the module level, I create the memoized...
[ 12, 2 ]
[]
[]
[ "decorator", "python", "unit_testing" ]
stackoverflow_0007983709_decorator_python_unit_testing.txt
Q: Get the last 4 characters of a string I have the following string: "aaaabbbb" How can I get the last four characters and store them in a string using Python? A: Like this: >>> mystr = "abcdefghijkl" >>> mystr[-4:] 'ijkl' This slices the string's last 4 characters. The -4 starts the range from the string's end. ...
Get the last 4 characters of a string
I have the following string: "aaaabbbb" How can I get the last four characters and store them in a string using Python?
[ "Like this:\n>>> mystr = \"abcdefghijkl\"\n>>> mystr[-4:]\n'ijkl'\n\nThis slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:\n>>> mystr[:-4]\n'abcdefgh'\n\nFor more information on slicing se...
[ 1007, 79 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007983820_python_string.txt
Q: Creating fewer files when freezing a Python application I'm using cxFreeze to freeze my Python application. All seems to be working as expected but peering into the build directory got me thinking... Is there a way I could have fewer files in the build directory? Currently, there's a bunch of PYD files and the nec...
Creating fewer files when freezing a Python application
I'm using cxFreeze to freeze my Python application. All seems to be working as expected but peering into the build directory got me thinking... Is there a way I could have fewer files in the build directory? Currently, there's a bunch of PYD files and the necessary DLL files lying around. Then I have some configuration...
[ "PyInstaller is cross-platform too, and has more features than cx_Freeze, but doesn't support Python 3. See also py2exe - generate single executable file.\n" ]
[ 0 ]
[]
[]
[ "cx_freeze", "python" ]
stackoverflow_0003241325_cx_freeze_python.txt
Q: cx_Freeze and moving files around In cx_Freeze, is it possible to move all pyd files and the library.zip to some subdirectory? I can live with two dlls along with the exe but I'd rather hide 15 other files from my users, even if only in a subdirectory. A: That appears to be impossible. Use PyInstaller, py2exe, ...
cx_Freeze and moving files around
In cx_Freeze, is it possible to move all pyd files and the library.zip to some subdirectory? I can live with two dlls along with the exe but I'd rather hide 15 other files from my users, even if only in a subdirectory.
[ "That appears to be impossible. Use PyInstaller, py2exe, or py2app if possible. See also py2exe - generate single executable file.\n" ]
[ 3 ]
[]
[]
[ "cx_freeze", "python" ]
stackoverflow_0004381470_cx_freeze_python.txt
Q: Using Django ORM get_or_create with multiple databases Django's ORM supports querying from a specific database (when multiple are defined in your project) via the .using() function for filter-based operations. e.g. MyModel.objects.filter(name='Bob').using('my_non_default_database') How would you do the equivalent ...
Using Django ORM get_or_create with multiple databases
Django's ORM supports querying from a specific database (when multiple are defined in your project) via the .using() function for filter-based operations. e.g. MyModel.objects.filter(name='Bob').using('my_non_default_database') How would you do the equivalent when creating new records, via the class MyModel() or shortc...
[ "using is a method on the MyModel.objects manager, so you can do \nMyModel.objects.using('my_non_default_database').get_or_create(name=\"Bob\")\n\nIf you have a MyModel instance, you can use the using keyword to specify the database to save to. The django docs point out some gotchas.\nmy_model = MyModel(name=\"Bob\...
[ 10, 4 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0007983711_django_django_orm_python.txt
Q: Reading tuples stored in textfile I was looking for a way to permanently store tuples created by a python program also after runtime. So I just decided for simplicity to write that data into a textfile (or is there some much more elegant yet simple solution to recommend?) so the command for doing that looks like: ...
Reading tuples stored in textfile
I was looking for a way to permanently store tuples created by a python program also after runtime. So I just decided for simplicity to write that data into a textfile (or is there some much more elegant yet simple solution to recommend?) so the command for doing that looks like: import codecs txt = codecs.open("data.t...
[ "Consider using pickle.dump and pickle.load to do all the work for you. That is a reasonable choice if you don't mind the file being in a Python specific format.\nAlso consider using sqlite3 to store the data. This format is readable by other programs and it is queryable (i.e. you can retrieve just the filename fi...
[ 5, 3 ]
[]
[]
[ "list", "python", "text_files", "tuples" ]
stackoverflow_0007983974_list_python_text_files_tuples.txt
Q: How to determine Windows Edition in Python with using Squish QT? Anyone know how to determine the Windows Edition ?? E.g. for both 32bit and 64bit of Windows: - Windows XP Home/Professional - Windows Vista Business/Ultimate...etc - Windows 7 Home Basic/Home Premium/Professional/Ultimate...etc I wonder if could ret...
How to determine Windows Edition in Python with using Squish QT?
Anyone know how to determine the Windows Edition ?? E.g. for both 32bit and 64bit of Windows: - Windows XP Home/Professional - Windows Vista Business/Ultimate...etc - Windows 7 Home Basic/Home Premium/Professional/Ultimate...etc I wonder if could retrieve this info from registry or Python API ?? Thanks.
[ "Take a look at platform.win32_ver(). Also, see How to check if OS is Vista in Python?\n", "If ctypes doesn't work (due to 32 vs 64 bits?), this hack should:\ndef get_Windows_name():\n import subprocess, re\n o = subprocess.Popen('systeminfo', stdout=subprocess.PIPE).communicate()[0]\n try: o = str(o, \"...
[ 1, 1 ]
[]
[]
[ "python", "registry", "windows" ]
stackoverflow_0007913914_python_registry_windows.txt
Q: Would puka work well with gevent or eventlet? I was reading about the newer Python AMQP library Puka (not to be confused with Pika) and was wondering if the way it handles it's event loop would be compatible with gevent or eventlet. Based on my limited knowledge, it seems like you could automatically patch it with...
Would puka work well with gevent or eventlet?
I was reading about the newer Python AMQP library Puka (not to be confused with Pika) and was wondering if the way it handles it's event loop would be compatible with gevent or eventlet. Based on my limited knowledge, it seems like you could automatically patch it with gevent/eventlet. Thanks! Source: http://github.co...
[ "Puka doesn't do gevent/eventlet out of the box, but it shouldn't be hard to modify it.\nPuka blocks only in one place (in the event loop), so replacing this part should be enough.\n", "Upon initial inspection it appears to be pure Python so gevent and eventlet should work fine.\n" ]
[ 3, 0 ]
[]
[]
[ "amqp", "eventlet", "gevent", "python", "rabbitmq" ]
stackoverflow_0007122995_amqp_eventlet_gevent_python_rabbitmq.txt
Q: Exporting ISO date in Numpy I am new in python and have a basic question I can not find a solution on the net. I have a table named IBTsample.txt, containing: Season,ISO_time,Latitude,Longitude,Enum 2009,2009-12-24 12:00:00,6.50,85.00,2 2009,2009-12-25 06:00:00,8.00,84.50,6 2009,2009-12-25 00:00:00,7.00,84.50,4 2...
Exporting ISO date in Numpy
I am new in python and have a basic question I can not find a solution on the net. I have a table named IBTsample.txt, containing: Season,ISO_time,Latitude,Longitude,Enum 2009,2009-12-24 12:00:00,6.50,85.00,2 2009,2009-12-25 06:00:00,8.00,84.50,6 2009,2009-12-25 00:00:00,7.00,84.50,4 2009,2009-12-24 18:00:00,6.50,85.0...
[ "You could use matplotlib.dates.num2date to convert the nums back into datetime objects. Then call isoformat() to get the date as a string in ISO-8601 format.\nimport numpy as np\nimport matplotlib.dates as md\n\ndef num2isodate(num):\n result=md.num2date(num).isoformat()\n return result\n\nrawtable = np.load...
[ 3, 1 ]
[]
[]
[ "date", "matplotlib", "numpy", "python" ]
stackoverflow_0007981153_date_matplotlib_numpy_python.txt
Q: scrapy script called from cron only constructor called scrapy crawler is called through a shell script, which is used as the command line in a crontab entry. The shell script looks like: scrapy crawl targethost.com when time is due and it did execute, but seems only the constructor is called (I verified with debug...
scrapy script called from cron only constructor called
scrapy crawler is called through a shell script, which is used as the command line in a crontab entry. The shell script looks like: scrapy crawl targethost.com when time is due and it did execute, but seems only the constructor is called (I verified with debug output). The problem is solved by re-write the shell script...
[ "Scrapy executes correctly, but doesn't output all its messages to STDOUT, so the simple pipe (>) doesn't redirect everything into your file, only that stuff that goes to STDOUT (which as you say, seems to be the constructor only).\nWith &> it fetches all messages from scrapy and puts them into your log.\n" ]
[ 1 ]
[]
[]
[ "crontab", "python", "scrapy" ]
stackoverflow_0007984714_crontab_python_scrapy.txt
Q: Freebase API get other types queries I'm using freebase python to access the freebase api. I have the following query I would like to execute: query = [{ "id": None, "name" : [], "type" : "/people/person", "/common/topic/image":[{}], "limit" : 10, "type" : [] ...
Freebase API get other types queries
I'm using freebase python to access the freebase api. I have the following query I would like to execute: query = [{ "id": None, "name" : [], "type" : "/people/person", "/common/topic/image":[{}], "limit" : 10, "type" : [] }] results = freebase.mqlread(query) ...
[ "Your query has two clauses called \"type\" which is not valid JSON and therefore not a valid MQL query. Most JSON parsers will just overwrite the first \"type\" clause with the second one which means that you actually end up running the following query:\n[{\n \"id\": null,\n \"name\": [],\n ...
[ 1 ]
[]
[]
[ "api", "freebase", "mql", "python" ]
stackoverflow_0007983941_api_freebase_mql_python.txt
Q: Python: handle broken unicode bytes when parsing JSON string My code makes gets some content from an UserVoice site. As you might know, UserVoice is a shitty piece of software that can't handle data correctly; indeed, to reduce the amount of text on the search page, they cut the text at, let's say, 300 characters ...
Python: handle broken unicode bytes when parsing JSON string
My code makes gets some content from an UserVoice site. As you might know, UserVoice is a shitty piece of software that can't handle data correctly; indeed, to reduce the amount of text on the search page, they cut the text at, let's say, 300 characters and then add a "..." to the end. Thing is, they don't care cutting...
[ "You don't ask simplejson to ignore them. When I got similar problem like yours I just ran .decode('utf-8', 'ignore').encode('utf-8') and proceed.\n", "Just pass Unicode string to json.loads():\n>>> badstr = \"qualité\"[:-1]+\"..\"\n>>> badstr\n'qualit\\xc3..'\n>>> json_str = '[\"%s\"]' % badstr\n>>> import json\...
[ 13, 10 ]
[]
[]
[ "json", "python", "unicode" ]
stackoverflow_0007984146_json_python_unicode.txt
Q: Appending a list that tallies the length of words I am taking words from a text file, stripping each word of \n and creating a new list out of these words. Now I need to go through systematically word by word finding the length of the word, then adding 1 to a tally of that word length i.e. I would start off with a...
Appending a list that tallies the length of words
I am taking words from a text file, stripping each word of \n and creating a new list out of these words. Now I need to go through systematically word by word finding the length of the word, then adding 1 to a tally of that word length i.e. I would start off with an empty tally: length_of_words = [0,0,0,0,0,0,0,0,0,0,0...
[ "The collections.Counter class is helpful for that sort of thing:\n>>> from collections import Counter\n>>> words = 'the quick brown fox jumped over the lazy dog'.split()\n>>> Counter(map(len, words))\nCounter({3: 4, 4: 2, 5: 2, 6: 1})\n\nThe code you've posted in your question works fine as-is, so I'm not sure whe...
[ 2, 0 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0007984809_append_list_python.txt
Q: Can I use GAE + python 2.7 + django.utils.translation? I use i18n for localization like django does using a custom request handler for switching between different languages and upgrading to python 2.7 this presents trouble since it uses the cookie from django.utils.translation. In worst case I must to move from ou...
Can I use GAE + python 2.7 + django.utils.translation?
I use i18n for localization like django does using a custom request handler for switching between different languages and upgrading to python 2.7 this presents trouble since it uses the cookie from django.utils.translation. In worst case I must to move from our custom request handler to some other system that can switc...
[ "I believe this is because WebOb has been upgraded with the new Python 2.7 runtime.\nYou should use:\nres.headers.add('Set-Cookie', header_value)\n\nAs pointed in the webob documentation\nNote that webapp has also been replaced by webapp2.\n" ]
[ 3 ]
[]
[]
[ "django", "google_app_engine", "internationalization", "localization", "python" ]
stackoverflow_0007956842_django_google_app_engine_internationalization_localization_python.txt
Q: Python Strings with Specific WIdth I have been having a bit of trouble looking up a good explanation on how to do this so pointing me to the right direction would be helpful for the following problem. I need to have a header printed out in a pretty format along with data, unfortunately what happened is shown belo...
Python Strings with Specific WIdth
I have been having a bit of trouble looking up a good explanation on how to do this so pointing me to the right direction would be helpful for the following problem. I need to have a header printed out in a pretty format along with data, unfortunately what happened is shown below. DeviceName KB used KB quota KB ...
[ "You could use '%*s':\nHEADER = \"DeviceName |KB used|KB quota|KB hard limit| grace\".split('|')\ndata = [\"/media/Stuff\", 58384, 5242880, 0, None]\nprint '|'.join(HEADER)\nprint '|'.join(\"%*s\" % (width, val) for width, val in zip(map(len,HEADER), data))\n\nOutput\nDeviceName |KB used|KB quota|KB hard limit|...
[ 3, 2, 1, 0 ]
[]
[]
[ "formatting", "python", "python_2.4", "string" ]
stackoverflow_0007985009_formatting_python_python_2.4_string.txt
Q: Percentages and rounding in Python I have a code which creates a list of percentage abundance of certain word lengths in a text file e.g. 1 letter words appear 13% of the time, what I was wondering is if there was 1 twenty letter word in a 50,000 word text file, would it round the percentage for twenty letter word...
Percentages and rounding in Python
I have a code which creates a list of percentage abundance of certain word lengths in a text file e.g. 1 letter words appear 13% of the time, what I was wondering is if there was 1 twenty letter word in a 50,000 word text file, would it round the percentage for twenty letter words down to 0 or up to 1? here is the enti...
[ "By default you got truncated number, if both numerator and denominator are integer. \n>>> 1 / 50000\n0\n\nto work around and real percentage, you change one or both of value to be floating poing number\n>>> 1.0 / 50000\n2e-05\n\nAnd in case you are talking about variables,\n>>> cnt, all = 1, 50000\n>>> float(cnt...
[ 3, 3, 2, 2 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0007985209_python_rounding.txt