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: If clause in regular Python for-loop Is it possible to basically do the following in Python: for elem in my_list if elem: #Do something with elem... Note that I want to specifically avoid using map, lambdas, or filter to create a second list that gives the Boolean condition, and I don't want to do the followi...
If clause in regular Python for-loop
Is it possible to basically do the following in Python: for elem in my_list if elem: #Do something with elem... Note that I want to specifically avoid using map, lambdas, or filter to create a second list that gives the Boolean condition, and I don't want to do the following: for elem in [item for item in my_list ...
[ "You can use a generator expression instead of a list comprehension.\nfor elem in (item for item in my_list if not (item=='')):\n #Do something...\n\n", "Check out the ifilter() function in itertools.\n" ]
[ 11, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008075077_python.txt
Q: django many to many association How do I create the association in MyListAssoc from here? How would I delete it? class Group(models.Model): name = models.CharField(max_length=32, unique=True) def __unicode__(self): return '%s %s' % (self.name) class MyKeywords(models.Model): name = models.Char...
django many to many association
How do I create the association in MyListAssoc from here? How would I delete it? class Group(models.Model): name = models.CharField(max_length=32, unique=True) def __unicode__(self): return '%s %s' % (self.name) class MyKeywords(models.Model): name = models.CharField(max_length=32, unique=True) ...
[ "You just need a many to many relation, something like:\nclass Group(models.Model):\n name = models.CharField(max_length=32, unique=True)\n keywords = models.ManyToManyField(MyKeywords)\n\n def __unicode__(self):\n return '%s' % (self.name)\n\nclass MyKeywords(models.Model):\n name = models.CharF...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008075042_django_python.txt
Q: Python 3.1 installed from Macports on 10.5.8 - shelve error (bug or not?) I am running python 3.1.4 from macports and I am attempting to use the shelve module here. I can use it successfully on another dev. machine (different OS, etc.) so I am not sure what I may be doing incorrectly... Any thoughts or suggestions...
Python 3.1 installed from Macports on 10.5.8 - shelve error (bug or not?)
I am running python 3.1.4 from macports and I am attempting to use the shelve module here. I can use it successfully on another dev. machine (different OS, etc.) so I am not sure what I may be doing incorrectly... Any thoughts or suggestions would be greatly appreciated! Here is the error "dbm.error: db type could not ...
[ "This looks like a bug in the MacPorts port or in Python 3. For me, your sample works with a current MacPorts Python 2.7.2 but fails with a current MacPorts Python 3.2.2 in the same way as you've reported. MacPorts automatically builds and includes gdbm as a database manager for Python 3 ports; for Python 2 it in...
[ 1, 0 ]
[]
[]
[ "macos", "macports", "python", "shelve" ]
stackoverflow_0008075324_macos_macports_python_shelve.txt
Q: Preserving session ID's in django.test.client I'm storing django's session key (request.session.session_key) in a database column-- It's an app that doesn't require logins, and sessions are a acceptable enough proxy for a unique user. It works fine, except now that I'm writing tests. Since the test client preserve...
Preserving session ID's in django.test.client
I'm storing django's session key (request.session.session_key) in a database column-- It's an app that doesn't require logins, and sessions are a acceptable enough proxy for a unique user. It works fine, except now that I'm writing tests. Since the test client preserves cookies, I assumed it the session id would be sta...
[ "There is the feature request for simplification of anonymous sessions usage in unit tests. In this ticket you can find the hard way to do it. Here is the link - https://code.djangoproject.com/ticket/10899\n" ]
[ 0 ]
[]
[]
[ "django", "python", "session", "testing" ]
stackoverflow_0008069613_django_python_session_testing.txt
Q: What's the different between a constructor & method in Python, can I mix them together? I implemented a plugable framework like below. It works but I'm confused about the implementation of Plugin2. Seems it uses a normal method instead of a class constructor. Can I do so? Is there any cons? Is it a normal-used 'pa...
What's the different between a constructor & method in Python, can I mix them together?
I implemented a plugable framework like below. It works but I'm confused about the implementation of Plugin2. Seems it uses a normal method instead of a class constructor. Can I do so? Is there any cons? Is it a normal-used 'pattern'? If it is, what's the pattern name? 'Duck typing'? Should I avoid usage like this? UPD...
[ "This is an often-used pattern called a factory function. It's a good idea to have your interface open to any callable that returns an object, whether the callable is a function or a class. It keeps you flexible for whatever you want to do in the future.\n", "Plugin2 is a module function that returns an object wh...
[ 4, 0 ]
[]
[]
[ "constructor", "frameworks", "methods", "plugins", "python" ]
stackoverflow_0008075634_constructor_frameworks_methods_plugins_python.txt
Q: How to do logging.DEBUG in django code? In django we have settings.py that defines the DEBUG for the whole project. Now, My have debug level is independently configured in settings.py. How should I use logging.DEBUG ? Way1: if settings.DEBUG: logging.debug("Debug message") Way2: # Without checking settings.DE...
How to do logging.DEBUG in django code?
In django we have settings.py that defines the DEBUG for the whole project. Now, My have debug level is independently configured in settings.py. How should I use logging.DEBUG ? Way1: if settings.DEBUG: logging.debug("Debug message") Way2: # Without checking settings.DEBUG logging.debug("Debug message") What is a...
[ "I think it's not a good thing to rely too much on a global setting such as DEBUG, which changes the whole behavior of your app. \nWhat if you want to audit code and log stuff in production ? You're not going to turn DEBUG to true to do this, are you ? You'd rather tone down your log filter.\nOn a more stylistic po...
[ 4, 1 ]
[]
[]
[ "debugging", "django", "django_settings", "logging", "python" ]
stackoverflow_0008061083_debugging_django_django_settings_logging_python.txt
Q: Converting .txt file to .xls in Python I have a file that is really in csv format but is being handed to me as a .txt. I need to take this file and transfer it to .xls format so I can upload it into Google Docs. Currently I have the code below but it is spitting out the file with everything on the line into the ...
Converting .txt file to .xls in Python
I have a file that is really in csv format but is being handed to me as a .txt. I need to take this file and transfer it to .xls format so I can upload it into Google Docs. Currently I have the code below but it is spitting out the file with everything on the line into the first cell instead of breaking out different...
[ "Just renaming it to .xls doesn't convert it to an Excel spreadsheet. But regardless, why would you convert it to .xls just to upload it to Google Docs? \nIf it's a .csv, just rename the file to .csv and upload it and it'll properly be detected as a spreadsheet.\nUse os.rename:\nimport os\n\nos.rename(\"C:\\Users\\...
[ 6, 0, 0 ]
[]
[]
[ "csv", "python", "text_files", "xls" ]
stackoverflow_0008074643_csv_python_text_files_xls.txt
Q: initsip() crashes with a corrupted stack When getting a pointer to the sip API: sip_API = reinterpret_cast<const sipAPIDef*>( PyCapsule_Import("sip._C_API", 0)); a crash is reported in initsip(). Also, when constructing C++ classes using boost.Python, a strange error is returned: TypeError: __init__() should ...
initsip() crashes with a corrupted stack
When getting a pointer to the sip API: sip_API = reinterpret_cast<const sipAPIDef*>( PyCapsule_Import("sip._C_API", 0)); a crash is reported in initsip(). Also, when constructing C++ classes using boost.Python, a strange error is returned: TypeError: __init__() should return None, not 'NoneType'
[ "Both of these problems are caused by linking against a different version of python than sip/boost are compiled with.\n" ]
[ 0 ]
[]
[]
[ "boost_python", "python", "python_sip" ]
stackoverflow_0008073213_boost_python_python_python_sip.txt
Q: How to get filename when running mapreduce job on EC2? I am learning elastic mapreduce and started off with the Word Splitter example provided in the Amazon Tutorial Section(code shown below). The example produces word count for all the words in all the input documents provided. But I want to get output for Word C...
How to get filename when running mapreduce job on EC2?
I am learning elastic mapreduce and started off with the Word Splitter example provided in the Amazon Tutorial Section(code shown below). The example produces word count for all the words in all the input documents provided. But I want to get output for Word Counts by file names i.e the count of a word in just one part...
[ "In the typical WordCount example, the file name which the map file is processing is ignored, since the the job output contains the consolidated word count for all the input files and not at a file level. But to get the word count at a file level, the input file name has to be used. Mappers using Python can get the...
[ 5 ]
[]
[]
[ "amazon_ec2", "amazon_emr", "mapreduce", "python" ]
stackoverflow_0008074730_amazon_ec2_amazon_emr_mapreduce_python.txt
Q: How to link script directory in App Engine for python? I have file app.yaml: application: v2011 version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /.* script: helloworld.py When i try to add: application: v2011 version: 1 runtime: python api_version: 1 ha...
How to link script directory in App Engine for python?
I have file app.yaml: application: v2011 version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - url: /.* script: helloworld.py When i try to add: application: v2011 version: 1 runtime: python api_version: 1 handlers: - url: /stylesheets static_dir: stylesheets - u...
[ "A sample code below. It does a pattern matching and if found, looks for file in the static/ folder. The url is http://app-id.appspot.com/my-script.js - also check the logs output at appengine.google.com, posting that error message here helps too. \nhandlers:\n- url: /(.*\\.(html|css|js|gif|jpg|png|ico))\n static_...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008071886_python.txt
Q: How to get the access token from facebook's oauth redirect in python? I'm new to FB app development. Once the user authorize my app, facebook does the following request http://www.example.com/response#access_token=...&expires_in=3600 Now my python do not see the part after the '#'. How do i get the part, or am ...
How to get the access token from facebook's oauth redirect in python?
I'm new to FB app development. Once the user authorize my app, facebook does the following request http://www.example.com/response#access_token=...&expires_in=3600 Now my python do not see the part after the '#'. How do i get the part, or am i doing something wrong?
[ "You cannot use this. That is part of client side auth. URI fragments (the stuff after the #) are never sent to the server by the browser. You need to look up server side auth.\n", "Short answer: you need to fill in YOUR_URL in https://www.facebook.com/dialog/oauth?\n client_id=YOUR_APP_ID&redirect_uri=YOUR_U...
[ 3, 0 ]
[]
[]
[ "facebook", "facebook_apps", "google_app_engine", "python" ]
stackoverflow_0008067387_facebook_facebook_apps_google_app_engine_python.txt
Q: sys.exc_info or sys.last_*? Should I prefer sys.exc_info() over sys.last_value and friends (sys.last_type, sys.last_traceback)? A: Looking at the documentation of sys.last_value and friends: Their intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging withou...
sys.exc_info or sys.last_*?
Should I prefer sys.exc_info() over sys.last_value and friends (sys.last_type, sys.last_traceback)?
[ "Looking at the documentation of sys.last_value and friends:\n\nTheir intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re-execute the command that caused the error.\n\nSo, if you are in an interpreter doing debugging I suggest using sys.l...
[ 4 ]
[]
[]
[ "exception", "python", "python_3.x", "sys", "traceback" ]
stackoverflow_0008076900_exception_python_python_3.x_sys_traceback.txt
Q: Have an SQLAlchemy + SQLite "create_function" issue with datetime representations We have sqlite databases, and datetimes are actually stored in Excel format (there is a decent reason for this; it's our system's standard representation of choice, and the sqlite databases may be accessed by multiple languages/syste...
Have an SQLAlchemy + SQLite "create_function" issue with datetime representations
We have sqlite databases, and datetimes are actually stored in Excel format (there is a decent reason for this; it's our system's standard representation of choice, and the sqlite databases may be accessed by multiple languages/systems) Have been introducing Python into the mix with great success in recent months, and ...
[ "Instead of letting Excel/Microsoft dictate how you store date/time, it would be less trouble and work for you to rely on standard/\"obvious way\" of doing things.\n\nProcess objects according to the standards of their domain - Python's way (datetime objects) inside Python/SQLAlchemy, SQL's way inside SQLite (nativ...
[ 1 ]
[]
[]
[ "datetime", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0008076126_datetime_python_sqlalchemy_sqlite.txt
Q: ssdeep's fuzzy_compare always returns 0 loaded from ctypes python Having a problem with getting the fuzzy_compare function to return a proper comparison value. It should be returning 0~100 but always returns 0. from ctypes import * fuzzy = CDLL('fuzzy.dll') out1 = create_string_buffer('\x00'*512) out2 = create_str...
ssdeep's fuzzy_compare always returns 0 loaded from ctypes python
Having a problem with getting the fuzzy_compare function to return a proper comparison value. It should be returning 0~100 but always returns 0. from ctypes import * fuzzy = CDLL('fuzzy.dll') out1 = create_string_buffer('\x00'*512) out2 = create_string_buffer('\x00'*512) print fuzzy.fuzzy_hash_buf('hashme', len('hashme...
[ "I compiled the included sample.c, and it seemed to work. So I tried something similar in Python. Note that it uses a very large input buffer (0x50000) and only modifies 16 bytes, yielding a close match of 99.\nimport ctypes\nfrom random import randrange, seed\n\nseed(42)\n\nSPAMSUM_LENGTH = 64\nFUZZY_MAX_RESULT = ...
[ 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0008076292_ctypes_python.txt
Q: Run bash scripts from python. MAC OS I am trying to run scripts for python in MAC OS. I was unable to run scripts that run Bash.sh scripts, any one here have an idea about how can I run bash.sh From python in Mac OS. Thanks you for any help :)! (This is the scripts: Called: RunScript.sh, and I need to run it from...
Run bash scripts from python. MAC OS
I am trying to run scripts for python in MAC OS. I was unable to run scripts that run Bash.sh scripts, any one here have an idea about how can I run bash.sh From python in Mac OS. Thanks you for any help :)! (This is the scripts: Called: RunScript.sh, and I need to run it from Python Script.)
[ "Does os.system not work?\nimport os\nos.system(\"/path/to/script.sh\")\n\n", "Presumably you would use the subprocess module.\nThe questions become: \n\nDo you intend to capture output from this script?\nDo you intend to feed input into it?\nDoes it need to interact with the user via the terminal (that Python is...
[ 6, 1 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0008076924_macos_python.txt
Q: Django Output Indices for an Ordered Set of Objects I currently have a data model set up where each School object has a name. On the primary page of the my website I am outputting all the School objects sorted alphabetically by name. I was hoping there would be a way for Django to create index titles for the objec...
Django Output Indices for an Ordered Set of Objects
I currently have a data model set up where each School object has a name. On the primary page of the my website I am outputting all the School objects sorted alphabetically by name. I was hoping there would be a way for Django to create index titles for the objects? By this I mean categorize each School object by the f...
[ "you can't get the database to group them, but it's a fairly easy piece of code:\n# obviously adapt this to your actual model\nschools = School.objects.order_by('name').all()\n\nschool_dict = {}\nfor school in schools:\n first_letter = school.name[0].lower()\n if first_letter in school_dict:\n school_d...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008074428_django_python.txt
Q: How to send the non-english message using python email library? I'm using simple python script to send email. Using this this script how to send non english message. import sys, smtplib if len(sys.argv) < 4: print "usage: %s server fromaddr toaddr [toaddr...]" % sys.argv[0] sys.exit(2) server, fromaddr, toaddrs...
How to send the non-english message using python email library?
I'm using simple python script to send email. Using this this script how to send non english message. import sys, smtplib if len(sys.argv) < 4: print "usage: %s server fromaddr toaddr [toaddr...]" % sys.argv[0] sys.exit(2) server, fromaddr, toaddrs = sys.argv[1], sys.argv[2], sys.argv[3:] message = """To: %s From: %...
[ "Short answer, you need to encode the message in base64 with email.encoders.encode_base64(). However, you need to read up on setting the email headers right (eg: Content-Type:) else the receiver's email program won't be able to decode it. \n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0008066291_email_python.txt
Q: Purpose of star operator when used on List What is the star operator doing to the input argument list in this example? def main(name, data_dir='.'): print 'name', type(name) if __name__ == '__main__': main(*sys.argv) Concretely, if I run the program with the star operator it prints: name <type 'str'> if...
Purpose of star operator when used on List
What is the star operator doing to the input argument list in this example? def main(name, data_dir='.'): print 'name', type(name) if __name__ == '__main__': main(*sys.argv) Concretely, if I run the program with the star operator it prints: name <type 'str'> if run without the star main(sys.argv) it prints: ...
[ "The * operator unpacks an argument list. It allows you to call a function with the list items as individual arguments.\nFor instance, if sys.argv is [\"./foo\", \"bar\", \"quux\"], main(*sys.argv) is equivalent to main(\"./foo\", \"bar\", \"quux\").\n", "main(*sys.argv)\n\ncalls main with the content of the list...
[ 50, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008077268_python.txt
Q: Advice regarding IPython + MacVim Workflow I've just found IPython and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like the one I have with screen. Ipython and screen happen to be the best of friends too so it's a triangular drama. Pure...
Advice regarding IPython + MacVim Workflow
I've just found IPython and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like the one I have with screen. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you. The reason IPython hits t...
[ "I use Linux, but I believe this tip can be used in OS X too. I use GNU Screen to send IPython commands from Vim as recommended by this tip. This is how I do it:\nFirst, you should open a terminal and start a screen session called 'ipython' or whatever you want, and then start IPython:\n$ screen -S ipython\n$ ipyth...
[ 14, 5, 1, 1 ]
[]
[]
[ "ipython", "python", "vim" ]
stackoverflow_0000453329_ipython_python_vim.txt
Q: Python class methods overloading How can I overload class methods? I failed with: class D(object): def create(self): foo = 100 bar = 'squirrels' baz = 'I have %d insane %s in my head.' % (foo, bar) return baz class C(D): def create(self): super(C, self).create(...
Python class methods overloading
How can I overload class methods? I failed with: class D(object): def create(self): foo = 100 bar = 'squirrels' baz = 'I have %d insane %s in my head.' % (foo, bar) return baz class C(D): def create(self): super(C, self).create() baz = 'I have %s cute %s in ...
[ "You have tried to use local variables as class attributes. Try to do the following changes:\nclass D(object):\n def create(self):\n self.foo = 100\n self.bar = 'squirrels'\n baz = 'I have %d insane %s in my head.' % (self.foo, self.bar)\n return baz\n\nclass C(D):\n def create(sel...
[ 3, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0008077806_oop_python.txt
Q: editing List content in Python I have a variable data: data = [b'script', b'-compiler', b'123cds', b'-algo', b'timing'] I need to convert it to remove all occurrence of "b" in the list. How can i do that? A: Not sure whether it would help - but it works with your sample: initList = [b'script', b'-compiler', b'...
editing List content in Python
I have a variable data: data = [b'script', b'-compiler', b'123cds', b'-algo', b'timing'] I need to convert it to remove all occurrence of "b" in the list. How can i do that?
[ "Not sure whether it would help - but it works with your sample:\ninitList = [b'script', b'-compiler', b'123cds', b'-algo', b'timing']\nresultList = [str(x) for x in initList ]\n\nOr in P3:\nresultList = [x.decode(\"utf-8\") for x in initList ] # where utf-8 is encoding used\n\nCheck more on decode function.\nAlso ...
[ 4, 3, 1 ]
[]
[]
[ "edit", "list", "python", "string" ]
stackoverflow_0008077810_edit_list_python_string.txt
Q: Replace recursively from a replacement map I have a dictionary in the form {'from.x': 'from.changed.x',...} possibly quite big, and I have to substitute in text files accordingly to that dictionary in a quite big directory structure. I didn't find anything which might any nice solution and I end up: using os.wal...
Replace recursively from a replacement map
I have a dictionary in the form {'from.x': 'from.changed.x',...} possibly quite big, and I have to substitute in text files accordingly to that dictionary in a quite big directory structure. I didn't find anything which might any nice solution and I end up: using os.walk iterating through the dictionary writing every...
[ "I would write the first function using generators:\ndef fix_imports(top_dir, not_ui_keys):\n \"\"\"Walk through the directory and substitute the wrong imports \"\"\"\n from itertools import imap,ifilter\n gen = ifilter(None,imap(extract_dotted, not_ui_keys))\n repl = dict((dotted,add_model(dotted)) for...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008069320_python_regex.txt
Q: Python Excel (xlrd, xlwt) - How to copy a style from one cell and put it on another Specifically I'm trying to open an existing workbook, and write some data to it. However whenever I write the data it obliterates the borders on those cells. So I'm wondering if there's a way to copy the style of that cell before...
Python Excel (xlrd, xlwt) - How to copy a style from one cell and put it on another
Specifically I'm trying to open an existing workbook, and write some data to it. However whenever I write the data it obliterates the borders on those cells. So I'm wondering if there's a way to copy the style of that cell before writing to it and then reapply it. I think I might be on the right track with this code?...
[ "The problem here is that a xlrd.NamedStyle is very different from xlwt.XFStyle.\nThe question seems to be a duplicate of Preserving styles using python's xlrd,xlwt, and xlutils.copy\n" ]
[ 3 ]
[]
[]
[ "excel", "python", "xlrd", "xlutils", "xlwt" ]
stackoverflow_0007830317_excel_python_xlrd_xlutils_xlwt.txt
Q: csv writing within loop import csv a=[] with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): for j in range(i+1): a.append(i+j*0.2) #print i,j,a #want to write into same csv file??? '''like ...
csv writing within loop
import csv a=[] with open('large.csv','w') as f1: writer=csv.writer(f1, delimiter='\t',lineterminator='\n',) for i in range(1000000): for j in range(i+1): a.append(i+j*0.2) #print i,j,a #want to write into same csv file??? '''like 0 ...
[ "Do you want to do something like this?\nimport csv\nwith open('large.csv','w') as f1:\n writer=csv.writer(f1, delimiter='\\t',lineterminator='\\n',)\n for i in range(1000000):\n row = [i + j*0.2 for j in range(i+1)]\n writer.writerow(row)\n\nor also with the row/column headers:\nimport csv\nwit...
[ 21 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0008078330_csv_python.txt
Q: How do I replace a HTML element with some new format in Python What is a good way to replace an HTML tag like: Old : <div id=pgbrk" ....../>....Page Break....</div> New : <!--page break --> div id might have many other values hence regex is not a good idea. I need some LXML kind of thing. Basically, my problem i...
How do I replace a HTML element with some new format in Python
What is a good way to replace an HTML tag like: Old : <div id=pgbrk" ....../>....Page Break....</div> New : <!--page break --> div id might have many other values hence regex is not a good idea. I need some LXML kind of thing. Basically, my problem is to replace an HTML tag with a string!
[ "As long as your div has a parent tag, you could do this:\nimport lxml.html as LH\nimport lxml.etree as ET\n\ncontent='<root><div id=\"pgbrk\" ......>....Page Break....</div></root>'\ndoc=LH.fromstring(content)\n# print(LH.tostring(doc)) \nfor div in doc.xpath('//div[@id=\"pgbrk\"]'):\n parent=div.getparent()...
[ 3, 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0008078208_html_python.txt
Q: hot reloading / swapping with Python I want code changes to take effect immediately during development. How can I detect changed files and reload them in the running Python (2.7) application? Edit: After reading the pages linked by 'Ivo van der Wijk', I think it would be best to restart the web application when co...
hot reloading / swapping with Python
I want code changes to take effect immediately during development. How can I detect changed files and reload them in the running Python (2.7) application? Edit: After reading the pages linked by 'Ivo van der Wijk', I think it would be best to restart the web application when code changes - like Django does. So the actu...
[ "I wanted the same effect for some of my Python scripts, so I went on and made the script SourceChangeMonitor.py. You can find it with instructions here. If you just want the script, here is a direct link\n", "This question has been asked a number of times\nYou can use reload(module) for this, but beware of nasty...
[ 9, 6, 2 ]
[]
[]
[ "hotdeploy", "hotswap", "python", "reload" ]
stackoverflow_0003862871_hotdeploy_hotswap_python_reload.txt
Q: Django post_syncdb signal handler not getting called? I have a myapp/management/__init__.py that is registering a post_syncdb handler like so: from django.db.models import signals from features import models as features def create_features(app, created_models, verbosity, **kwargs): print "Creating features!" ...
Django post_syncdb signal handler not getting called?
I have a myapp/management/__init__.py that is registering a post_syncdb handler like so: from django.db.models import signals from features import models as features def create_features(app, created_models, verbosity, **kwargs): print "Creating features!" # Do stuff... signals.post_syncdb.connect(create_featu...
[ "try putting it in your models.py \n", "Just came across the same issue, and the way I solved it was to remove the sender from function arguments and check for it inside the callback function.\nfrom django.db.models import signals\nfrom features import models as features\n\ndef create_features(app, created_models...
[ 3, 1, 0 ]
[]
[]
[ "django", "django_syncdb", "python", "signals" ]
stackoverflow_0004391358_django_django_syncdb_python_signals.txt
Q: Why is Clojure 10 times slower than Python for the equivalent solution of Euler 50? I recently started to learn Clojure and decided to practice on Euler problems to get a hang of the available data structures and practice recursion and looping. I tried various approaches to Problem 50, but no matter what I did, f...
Why is Clojure 10 times slower than Python for the equivalent solution of Euler 50?
I recently started to learn Clojure and decided to practice on Euler problems to get a hang of the available data structures and practice recursion and looping. I tried various approaches to Problem 50, but no matter what I did, finding the solution for 1000000 never finished. After I looked up what others did, I gues...
[ "I think the slowdown comes from the number of times you iterate through the sequences in longest-seq-under; each of those iterations takes its toll. Here's a smoking fast version, based on a combination of your code and the answer posted here. Note that primes is lazy, so we can bind it with def vs defn:\n(defn pr...
[ 15, 4 ]
[]
[]
[ "clojure", "comparison", "performance", "python" ]
stackoverflow_0008064336_clojure_comparison_performance_python.txt
Q: Use Python bottle server to receive FileEntity of a POST request from Android On Android phone, I used setEntity() to put the FileEntity to the POST request. HttpPost post = new HttpPost(uri); FileEntity reqEntity = new FileEntity(f, "application/x-gzip"); reqEntity.setContentType("binary/octet-stream"); reqEntity...
Use Python bottle server to receive FileEntity of a POST request from Android
On Android phone, I used setEntity() to put the FileEntity to the POST request. HttpPost post = new HttpPost(uri); FileEntity reqEntity = new FileEntity(f, "application/x-gzip"); reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); post.addHeader("X-AethersNotebook-Custom", configuration.getCust...
[ "Using that code, the phone send file using chunked encoding. Because py-bottle does not support chunked enconding, the solution here is rewrite the android to send file as body of POST request.\n" ]
[ 1 ]
[]
[]
[ "android", "bottle", "python" ]
stackoverflow_0007527413_android_bottle_python.txt
Q: Python Web Proxy that Supports PKCS#11 Does anyone know of a web proxy written in Python that will support SSL connections and will also support PKCS#11 tokens? I am in need of a proxy that will send SSL web requests using a PKCS#11 smartcard. I have been looking for projects that are using something like Twisted ...
Python Web Proxy that Supports PKCS#11
Does anyone know of a web proxy written in Python that will support SSL connections and will also support PKCS#11 tokens? I am in need of a proxy that will send SSL web requests using a PKCS#11 smartcard. I have been looking for projects that are using something like Twisted but have not seen any.
[ "If Twisted has a proxy, then you can use it with M2Crypto+engine_pkcs11. I had the code, I can see if it is still existing somewhere.\n" ]
[ 0 ]
[]
[]
[ "pkcs#11", "proxy", "python", "smartcard" ]
stackoverflow_0008073753_pkcs#11_proxy_python_smartcard.txt
Q: Introspection on pygtk3 possible? One of the great things of python is the ability to have introspection on methods and functions. As an example, to get the function signature of math.log you can (in ipython) run this: In [1]: math.log? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_...
Introspection on pygtk3 possible?
One of the great things of python is the ability to have introspection on methods and functions. As an example, to get the function signature of math.log you can (in ipython) run this: In [1]: math.log? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form: <built-in func...
[ "Right now, I think this isn't yet ready. However, you can still do manual introspection looking at Gtk-3.0.gir file (in my system located in /usr/share/gir-1.0/Gtk-3.0.gir).\nThe gir file is just an xml file that is supposed to be used exactly to explore the exposed interface regardless of the programming language...
[ 4, 0, 0 ]
[]
[]
[ "gtk3", "pygobject", "pygtk", "python" ]
stackoverflow_0007859490_gtk3_pygobject_pygtk_python.txt
Q: python how to overload maybe?? the constructor i have this code : class random_walk: #ns: number of steps1d #np: number of particles #dimension : choose between 1D or 2D def __init__(self,ns,np,dimension=None): self.ns=ns self.np=np self.dimension=dimension def steps1d(...
python how to overload maybe?? the constructor
i have this code : class random_walk: #ns: number of steps1d #np: number of particles #dimension : choose between 1D or 2D def __init__(self,ns,np,dimension=None): self.ns=ns self.np=np self.dimension=dimension def steps1d(self,ns): return 2*sc.random.random_inte...
[ "def steps1d(self, ns): \n return 2*sc.random.random_integers(0, 1, size=ns)-1\n\ndef Walk1d(self, ns=None):\n if ns is None:\n ns = self.ns\n return sc.cumsum(self.steps1d(ns))\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008079430_python.txt
Q: Referencing Python "import" assemblies when calling from IronPython in C# I'm a complete noob when it comes to IronPython. I need to call a py script from an ASP.NET website, and have the following code: var ipy = IronPython.Hosting.Python.CreateRuntime(); dynamic test = ipy.UseFile(Server.MapPath(@"~\python\test....
Referencing Python "import" assemblies when calling from IronPython in C#
I'm a complete noob when it comes to IronPython. I need to call a py script from an ASP.NET website, and have the following code: var ipy = IronPython.Hosting.Python.CreateRuntime(); dynamic test = ipy.UseFile(Server.MapPath(@"~\python\test.py")); test.DoWork(); The version of IronPython I'm using is 2.7. The 3rd part...
[ "An alternate way of doing this:\ndynamic sys = scriptEngine.ImportModule(\"sys\"); \nsys.path.append(somePath);\n\n" ]
[ 2 ]
[]
[]
[ "asp.net", "ironpython", "python" ]
stackoverflow_0006557494_asp.net_ironpython_python.txt
Q: Python urllib2.urlopen freezes script infinitely even though timeout is set The function urllib2.urlopen freezes. So my question is simple: Why does urlopen freeze my script for ever even though timeout is set? How can I access data at an URL (in this case: http://api.own3d.tv/live?channel=FnaticTV) without the p...
Python urllib2.urlopen freezes script infinitely even though timeout is set
The function urllib2.urlopen freezes. So my question is simple: Why does urlopen freeze my script for ever even though timeout is set? How can I access data at an URL (in this case: http://api.own3d.tv/live?channel=FnaticTV) without the possibility of my Python process freezing up for all eternity? This is the part w...
[ "This script doesn't freeze at all, but it's a brilliant example of why you shouldn't code while tired. The loop that's supposed to try to connect to the API three times will continue for ever, because I forgot to put a break in there.\nThis question was so stupid I wouldn't blame you for removing it.\nFixed code:\...
[ 5, 4 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0008071254_python_urllib2.txt
Q: How to determine if elevated priveleges are required to start a process without checking-by-failure How do I go about checking whether privelege elevation is required to start a subprocess without trying first then failing? I need to start a subprocess command from within python code. In some cases it works fine, ...
How to determine if elevated priveleges are required to start a process without checking-by-failure
How do I go about checking whether privelege elevation is required to start a subprocess without trying first then failing? I need to start a subprocess command from within python code. In some cases it works fine, in other cases it turns out that elevated priveleges are required; and on some windows systems this condi...
[ "\nWith pywin32, something like the following should work...:\nimport pythoncom\nimport pywintypes\nimport win32api\nfrom win32com.shell import shell\n\nif shell.IsUserAnAdmin():\n ...\n\nAnd yes, it seems pywin32 does support Python 3.\n\nWritten by Alex Martelli\nAlso this for people without pywin32.\nimport ct...
[ 4 ]
[]
[]
[ "escalation", "python", "windows" ]
stackoverflow_0008078708_escalation_python_windows.txt
Q: How to make a copy of the list? I have a function: def mutate(self, index): ing1, ing2 = random.randrange(8), random.randrange(8) while ing1 == ing2: ing2 = random.randrange(8) ptr = self.drinkList[index].ing[:] ing1thr = ptr[ing1].max - ptr[ing1].perc ing2thr = ptr[ing2].perc - ptr[ing...
How to make a copy of the list?
I have a function: def mutate(self, index): ing1, ing2 = random.randrange(8), random.randrange(8) while ing1 == ing2: ing2 = random.randrange(8) ptr = self.drinkList[index].ing[:] ing1thr = ptr[ing1].max - ptr[ing1].perc ing2thr = ptr[ing2].perc - ptr[ing2].min mutatedFitness = 0 if ...
[ "Slicing creates a view object afaik. Use copy module.\n", "Expanding on what skrat said\nimport copy\nnew_list = copy.deepcopy(old_list)\n\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008078764_python.txt
Q: Is it possible to open a file in shared mode without changing the file handler? In Python I open a temporary file for write by using tempfile.mkstemp in order to be sure that the file is destroyed when released (even if application crashes). Now I need to pass this file to another application but this application ...
Is it possible to open a file in shared mode without changing the file handler?
In Python I open a temporary file for write by using tempfile.mkstemp in order to be sure that the file is destroyed when released (even if application crashes). Now I need to pass this file to another application but this application is not going to be able to open the file as long the file is opened for write. Can I ...
[ "There is no documented way to switch the file modes (r, w, a) for an open file.\nInstead of TempFile, consider using mmap to share data between programs.\n" ]
[ 1 ]
[ "Why not open it in 'a' mode? That way you can read and append?\nAlso why not open the TempFile manually then at an atexit event to delete when your program is done.\n" ]
[ -1 ]
[ "fopen", "python", "windows" ]
stackoverflow_0008079775_fopen_python_windows.txt
Q: python:running command in the background I have a fairly complex report generating work, which needs to be generated spaning through multiple tables. Final report is created in an excel sheet.The process takes anything between 10-20 minutes. We have provided a Django web app for the client. Only issue if the clie...
python:running command in the background
I have a fairly complex report generating work, which needs to be generated spaning through multiple tables. Final report is created in an excel sheet.The process takes anything between 10-20 minutes. We have provided a Django web app for the client. Only issue if the client requests for a report, we are generating a ...
[ "You can use http://celeryproject.org/, it works like a charm, it has nice Django integration, it's very well documented and used by many.\n", "May be the below program helps you. \nbackground.py\nimport subprocess\n\ndef background_execute(command):\n # launching the command\n p1 = subprocess.Popen(command...
[ 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008078806_django_python.txt
Q: Is there anything like Python's pty.fork for Ruby? I'm trying to port some Python code like the following to Ruby: import pty pid, fd = pty.fork if pid == 0: # figure out what to launch cmd = get_command_based_on_user_input() # now replace the forked process with the command os.exec(cmd) else: # read a...
Is there anything like Python's pty.fork for Ruby?
I'm trying to port some Python code like the following to Ruby: import pty pid, fd = pty.fork if pid == 0: # figure out what to launch cmd = get_command_based_on_user_input() # now replace the forked process with the command os.exec(cmd) else: # read and write to fd like a terminal Since I need to read and...
[ "You're probably looking for http://ruby-doc.org/stdlib-1.9.2/libdoc/pty/rdoc/PTY.html, http://www.ruby-doc.org/core-1.9.3/Process.html#method-c-fork and Create a daemon with double-fork in Ruby.\nI'd open a PTY with master process, fork and reattach child to said PTY with STDIN.reopen.\n" ]
[ 1 ]
[]
[]
[ "fork", "linux", "pty", "python", "ruby" ]
stackoverflow_0007393461_fork_linux_pty_python_ruby.txt
Q: Python: subprocess.Popen and subprocess.call hang I have a problem using the subprocess.Popen or subprocess.call when I use them to execute a command lines that generates a lot of output, the python scripts hangs, but what is weird that after waiting for a while, while the script is in its hanging state, I find t...
Python: subprocess.Popen and subprocess.call hang
I have a problem using the subprocess.Popen or subprocess.call when I use them to execute a command lines that generates a lot of output, the python scripts hangs, but what is weird that after waiting for a while, while the script is in its hanging state, I find that the job commanded by the cmd line has been done, an...
[ "According to the python documentation, subprocess.call runs the command and waits for it to complete, so it's equivalent to subprocess.Popen followed by Popen.wait.\nHowever, the Popen.wait method documentation explicitly warns about the problem of buffer overflow and recommends to use Popen.communicate instead. H...
[ 17, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008077868_python.txt
Q: In Python, how do I split a string to a number of integers? This works ! >>> from datetime import date >>> today=date(2011,10,11) But how do I do this ? >>> day = '2011/10/11' >>> today=date(day.split('/')) note: >>> day.split('/') ['2011', '10', '11'] I have seen this link.But i need integers for the dat...
In Python, how do I split a string to a number of integers?
This works ! >>> from datetime import date >>> today=date(2011,10,11) But how do I do this ? >>> day = '2011/10/11' >>> today=date(day.split('/')) note: >>> day.split('/') ['2011', '10', '11'] I have seen this link.But i need integers for the date() not a list
[ "Use datetime.datetime.strptime(), which is designed specifically for parsing dates:\nIn [5]: datetime.datetime.strptime('2011/12/03', '%Y/%m/%d').date()\nOut[5]: datetime.date(2011, 12, 3)\n\n", "This should work:\ndate(*map(int, day.split('/')))\n\n>>> map(int, day.split('/'))\n[2011, 10, 11]\n>>> date(*map(int...
[ 9, 3, 2, 2, 0 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0008080794_integer_python_string.txt
Q: How to setup a program in python? I wrote a python program which I call with arguments from console. As the functionality grew, so did the amount of code that is now all nested in one single file. I know that there are python modules and packages which I could create in order to outsource the functions I wrote. Bu...
How to setup a program in python?
I wrote a python program which I call with arguments from console. As the functionality grew, so did the amount of code that is now all nested in one single file. I know that there are python modules and packages which I could create in order to outsource the functions I wrote. But is this really the python way of doin...
[ "That's a good solution, thought your modules should be stored in a package not called like your main module. This would be prone to conflict between module and package name.\nThis could be resources, lib or anything, but please, not prog, as you already have a module named prog.py; otherwise, how would you know th...
[ 1, 1 ]
[]
[]
[ "directory", "installation", "package", "program_entry_point", "python" ]
stackoverflow_0008079566_directory_installation_package_program_entry_point_python.txt
Q: wx.Media volume reset problems Am working on a media player application using wx.Media but the big challenge that i am having is that the SetVolume(new_volume) of the media ctrl method is not working properly but it mutes the sound when the new_volume reaches to 0.. The new_volume is from a volume slider control. ...
wx.Media volume reset problems
Am working on a media player application using wx.Media but the big challenge that i am having is that the SetVolume(new_volume) of the media ctrl method is not working properly but it mutes the sound when the new_volume reaches to 0.. The new_volume is from a volume slider control. so what is the best strategy to hand...
[ "I created a really simple MP3 player using wx.media that I blogged about a while ago. It might help you figure this out: http://www.blog.pythonlibrary.org/2010/04/20/wxpython-creating-a-simple-mp3-player/\nThere's also a cool 3rd party widget that wraps mplayer that I used too: http://www.blog.pythonlibrary.org/20...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008076065_python_wxpython.txt
Q: Error compiling python.h with C program I am using eclipse and cygwin gcc compiler. Trying to use the Python.h for my C program but encounter these errors when compiling. Any ideas? In file included from C:/Python27/include/python.h:86, from ../src/EmbeddedPython.c:13: C:/Python27/include/intobjec...
Error compiling python.h with C program
I am using eclipse and cygwin gcc compiler. Trying to use the Python.h for my C program but encounter these errors when compiling. Any ideas? In file included from C:/Python27/include/python.h:86, from ../src/EmbeddedPython.c:13: C:/Python27/include/intobject.h:45: error: parse error before "PyInt_AsUn...
[ "I don't know if this would help you out or not, but using gcc on OS X to compile a C program with embedded Python I had to link to the Python library. For instance from the command line I compiled:\ngcc python_test.c -lpython2.7 -o python_test\n\nwhere -l is the flag and python2.7 is my Python library folder. \n" ...
[ 2 ]
[]
[]
[ "c", "python" ]
stackoverflow_0008066407_c_python.txt
Q: Why are python strings left aligned in format with specified width? While thinking of a way to pretty print table header i found that integers are right aligned by default, but strings are left aligned. For example: >>> for i in (1,'x',0.0): ... print("{0:5}".format(i)) ... 1 x 0.0 This is easily f...
Why are python strings left aligned in format with specified width?
While thinking of a way to pretty print table header i found that integers are right aligned by default, but strings are left aligned. For example: >>> for i in (1,'x',0.0): ... print("{0:5}".format(i)) ... 1 x 0.0 This is easily fixed by setting alignment explicitly, but i wonder why is this so? EDIT: ...
[ "Probably you are looking for something like this\nprint ( \"%5s\" % ('x',) )\nprint ( \"%5d\" % (245,) )\n\nwhich outputs \n x\n 245\n\nFor the question 'why' I think an answer is that when you read some data in column you actually expect string to be left aligned\na\nab\nabc\n\nand not\n a\n ab\n abc\n\nAl...
[ 1, 0, 0 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0008019367_formatting_python_string.txt
Q: django python script - why is my loop not finishing? Django/Python rookie. Have a function that isn't finishing when called. No error, it just stops and goes back to the python command prompt. It does the first while loop but stops before it gets to the next 'print' command, and takes me back to the prompt. Ev...
django python script - why is my loop not finishing?
Django/Python rookie. Have a function that isn't finishing when called. No error, it just stops and goes back to the python command prompt. It does the first while loop but stops before it gets to the next 'print' command, and takes me back to the prompt. Everything that executed is correct. I'm sure it's something...
[ "I think you may need to .save() your carpool object after adding legs to it - otherwise the leg count might be zero because there wont have been another database hit on the carpool object. That would explain your loop skipping.\nAm I right in thinking the leg count is zero before the loop? Print it, then try .save...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008081205_django_python.txt
Q: Trying to understand Python's Concurrent.Futures module I’m trying to understand how to use the concurrent.futures module in Python 3.2.2, and have been playing with examples from the documentation. When I try to apply my understanding, my own examples fail. I hope somebody can help me get on track! I want to be...
Trying to understand Python's Concurrent.Futures module
I’m trying to understand how to use the concurrent.futures module in Python 3.2.2, and have been playing with examples from the documentation. When I try to apply my understanding, my own examples fail. I hope somebody can help me get on track! I want to be able to set a number of processes running concurrently but a...
[ "I don't quite understand why you don't want to use executor.map...I tried it with a function that didn't return anything (with your f function, actually) and it worked fine...\nnow, when you run it with map, it won't actually print the values, but here is a version of your f function that does print the values:\ni...
[ 2 ]
[]
[]
[ "concurrency", "multithreading", "python" ]
stackoverflow_0008081149_concurrency_multithreading_python.txt
Q: How to use AWS S3 policies to enforce ownership of resources for federated users? I'm writing an app where I have a set of users, and each user will have a number of files associated with them in a 'directory' within an S3 bucket. Users will be authenticating using Amazon's STS, getting temporary security credent...
How to use AWS S3 policies to enforce ownership of resources for federated users?
I'm writing an app where I have a set of users, and each user will have a number of files associated with them in a 'directory' within an S3 bucket. Users will be authenticating using Amazon's STS, getting temporary security credentials that should allow them to access resources they own while not allowing them to acc...
[ "Someone asked a question like this - it turned out that the bucket had a global public read set on it using a bucket policy. Double check that there are no other ACLs, etc that allow access. Also it looks like there is no 'listing' access - is that what you want? Can you call get on a bucket and get a listing of a...
[ 3 ]
[]
[]
[ "amazon_s3", "amazon_web_services", "boto", "python" ]
stackoverflow_0008074720_amazon_s3_amazon_web_services_boto_python.txt
Q: which Micro-Frameworks can I try online? I see that we can try Flask (the python micro framework from the browser, well... kind of), is there any other microframework that can be tested online before using it in a project? It is ok for me, if the micro framework is in any of the following languages (php, ruby, pyt...
which Micro-Frameworks can I try online?
I see that we can try Flask (the python micro framework from the browser, well... kind of), is there any other microframework that can be tested online before using it in a project? It is ok for me, if the micro framework is in any of the following languages (php, ruby, python, javascript, clojure, erlang or haskell)
[ "What do you mean try online? Like write code to some page and test it? I really don't see a point in that. You often need at least two files for meaningful testing. If you want to just see results of the framework I'd guess that its project page is written in it.\nIf the first one is the case, use bundled testing ...
[ 2 ]
[]
[]
[ "php", "python", "web_frameworks" ]
stackoverflow_0008081467_php_python_web_frameworks.txt
Q: Split string with multiple-character delimiter say I have the following string: "Hello there. My name is Fred. I am 25.5 years old." I want to split this into sentences, so that I have the following list: ["Hello there", "My name is Fred", "I am 25.5 years old"] As you can see, I want to split the string on all ...
Split string with multiple-character delimiter
say I have the following string: "Hello there. My name is Fred. I am 25.5 years old." I want to split this into sentences, so that I have the following list: ["Hello there", "My name is Fred", "I am 25.5 years old"] As you can see, I want to split the string on all occurrences of the string ". ", not any occurrence o...
[ "Works for me\n>>> \"Hello there. My name is Fr.ed. I am 25.5 years old.\".split(\". \")\n['Hello there', 'My name is Fr.ed', 'I am 25.5 years old.']\n\n", ">>> \"Hello there. My name is Fred. I am 25.5 years old.\".rstrip(\".\").split(\". \")\n['Hello there', 'My name is Fred', 'I am 25.5 years old']\n\n", "Yo...
[ 38, 4, 3 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0008081569_python_split_string.txt
Q: How to override default "logfile" in python cli module? I'm trying to use: http://packages.python.org/pyCLI/#cli-log-logging-applications specifically the cli.log.LoggingApp which automatically gives you the -l --logfile option. What is the best way to override the default logfile attribute? If no -l is provided, ...
How to override default "logfile" in python cli module?
I'm trying to use: http://packages.python.org/pyCLI/#cli-log-logging-applications specifically the cli.log.LoggingApp which automatically gives you the -l --logfile option. What is the best way to override the default logfile attribute? If no -l is provided, it defaults to None and output goes to stdout. I would like t...
[ "You can default this file name by supplying a logfile kwarg to the decorator:\nimport cli.log\n\n\n@cli.log.LoggingApp(logfile='default.log')\ndef foo(app):\n print \"I'm in the app!\"\n app.log.error(\"Things are seriously wrong!\")\n\n\nif __name__ == \"__main__\":\n foo.run()\n\nThe only issue (I could...
[ 1, 0 ]
[]
[]
[ "command_line_interface", "python" ]
stackoverflow_0008073488_command_line_interface_python.txt
Q: File based caching with expiration in python To generate stats I'm doing a few 100 XMLRPC requests to a 3rd party API. As I want to have the stats computed fast to be able to play with it, I want to cache the responses from the API. An excerpt of the APIs HTTP headers: Content-Type: application/xml; charset=utf-8 ...
File based caching with expiration in python
To generate stats I'm doing a few 100 XMLRPC requests to a 3rd party API. As I want to have the stats computed fast to be able to play with it, I want to cache the responses from the API. An excerpt of the APIs HTTP headers: Content-Type: application/xml; charset=utf-8 Connection: keep-alive ETag: "c539d317b07c640c123e...
[ "Well, since nobody came up with a good existing module, I have written one myself.\nNot particularly pretty but it does the job I think. Feedback very much welcome\nhttp://pastie.org/2842063\n" ]
[ 0 ]
[]
[]
[ "caching", "python" ]
stackoverflow_0008047400_caching_python.txt
Q: initialize dict with keys,values from two list I have read this link But how do I initialize the dictionary as well ? say two list keys = ['a','b','c','d'] values = [1,2,3,4] dict = {} I want initialize dict with keys & values A: d = dict(zip(keys, values)) (Please don't call your dict dict, that's a buil...
initialize dict with keys,values from two list
I have read this link But how do I initialize the dictionary as well ? say two list keys = ['a','b','c','d'] values = [1,2,3,4] dict = {} I want initialize dict with keys & values
[ "d = dict(zip(keys, values))\n\n(Please don't call your dict dict, that's a built-in name.)\n", "In Python 2.7 and python 3, you can also make a dictionary comprehension\nd = {key:value for key, value in zip(keys, values)}\n\nAlthough a little verbose, I found it more clear, as you clearly see the relationship.\n...
[ 95, 20 ]
[]
[]
[ "dictionary", "key", "list", "python" ]
stackoverflow_0008080890_dictionary_key_list_python.txt
Q: item or member, is there a rule how to refer to a container's contents? Let's take a random container in Python (list, dict...), do you say a container has items or do you refer to it as members? Documentation seems to suggest that only sets have members. A: "Items" in Python usually are the things that can be r...
item or member, is there a rule how to refer to a container's contents?
Let's take a random container in Python (list, dict...), do you say a container has items or do you refer to it as members? Documentation seems to suggest that only sets have members.
[ "\"Items\" in Python usually are the things that can be retrieved or modified using the __getitem__() and __setitem__() functions, so lists and dictionaries have items. Sets in contrast don't implement __getitem__() and __setitem__(), so the documentation uses one of the usual terms to refer to the members of a se...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008082243_python.txt
Q: Real Security in Python I've been looking for a way to use a password in an if statement. Obviously, if theRawInput == theCorrectPassword: is extremely non-secure. Any ideas? I've seen other questions with this topic, but they all suggest base64, which is also very non-secure (I cracked my own compiled script's...
Real Security in Python
I've been looking for a way to use a password in an if statement. Obviously, if theRawInput == theCorrectPassword: is extremely non-secure. Any ideas? I've seen other questions with this topic, but they all suggest base64, which is also very non-secure (I cracked my own compiled script's password without using the p...
[ "If the attacker has access to your password database, the only way to still hide the password is hashing it. Include a salt to prevent the attacker from relying on generic hash tables:\nimport hashlib\nsalt = 'uphi8eiV'\nhash = 'a7a2a98cc06f5b2935db5d2866670cc8b48116022e5bc30095b6167ddc2f3f96'\nif hashlib.md5.hexd...
[ 6 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0008082334_encryption_python.txt
Q: Iterating through a list of numbers and adding them to tags So I have this table, and I want to go through in Python, and find all of the <tr> tags, and turn them into <tr id="NUMBER HERE"> where the number will be a number from a list which is in this format: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '...
Iterating through a list of numbers and adding them to tags
So I have this table, and I want to go through in Python, and find all of the <tr> tags, and turn them into <tr id="NUMBER HERE"> where the number will be a number from a list which is in this format: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '47'] ...
[ "Using lxml:\nimport lxml.html as LH\n\nhtml_table='''\n<table>\n<tr>\n<tr>\n<tr>\n<tr>\n<tr>\n</table>\n'''\n\nnums=['1','2','20','47','50']\ndoc=LH.fromstring(html_table)\nfor tr,n in zip(doc.xpath('//tr'),nums):\n tr.attrib['id']=n\nprint(LH.tostring(doc,pretty_print=True))\n\nyields\n<table>\n<tr id=\"1\"></...
[ 7, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0008066184_html_python.txt
Q: Cython: for i from 1 <= i < N I'm learning Cython and came across this snippit of code: import numpy as np cimport numpy as np def mean(np.ndarray[np.double_t] input): cdef np.double_t cur # Py_ssize_t is numpy's index type cdef Py_ssize_t i cdef Py_ssize_t N = len(input) for i from 0 <= i <...
Cython: for i from 1 <= i < N
I'm learning Cython and came across this snippit of code: import numpy as np cimport numpy as np def mean(np.ndarray[np.double_t] input): cdef np.double_t cur # Py_ssize_t is numpy's index type cdef Py_ssize_t i cdef Py_ssize_t N = len(input) for i from 0 <= i < N: cur += input[i] re...
[ "Compile it and see: the C code that Cython produces is nicely annotated.\n /* \"cyexample.pyx\":11\n * cdef Py_ssize_t N = len(input)\n * \n * for i from 0 <= i < N: # <<<<<<<<<<<<<<\n * cur += input[i]\n * \n */\n __pyx_t_1 = __pyx_v_N;\n for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; _...
[ 5, 5 ]
[]
[]
[ "cython", "for_loop", "python" ]
stackoverflow_0008083451_cython_for_loop_python.txt
Q: Larger CSS font sizes in QTextEdit-based editor We are making a QTextEdit-based editor. We are using QtGui.QComboBox in QtGui.QTextEdit for selecting font sizes. The CSS sizes we are using are: small, normal, large, x-large and xx-large. The largest size winds up being about 24 points. Is there any way to make it ...
Larger CSS font sizes in QTextEdit-based editor
We are making a QTextEdit-based editor. We are using QtGui.QComboBox in QtGui.QTextEdit for selecting font sizes. The CSS sizes we are using are: small, normal, large, x-large and xx-large. The largest size winds up being about 24 points. Is there any way to make it 48 points? (While keeping the ability to zoom with Ct...
[ "The CSS font-size property supports either an absolute size (specified in points or pixels), or a named relative size (\"small\", \"medium\", \"large\", \"x-large\", or \"xx-large\"). \nThe relative sizes are relative to the document font size - which means the font size set on the body tag for rich-text documents...
[ 3 ]
[]
[]
[ "css", "pyqt4", "pyside", "python", "rich_text_editor" ]
stackoverflow_0008074850_css_pyqt4_pyside_python_rich_text_editor.txt
Q: Python - shortening an if / for loop I've got a few lines of code for iterating over a dict within a list and I'm looking to shorten it. It works perfectly as is, but seems like too much code and I'm trying to get a feel for how to keep code efficient in Python (or in general really). for d in dev['devices']: ...
Python - shortening an if / for loop
I've got a few lines of code for iterating over a dict within a list and I'm looking to shorten it. It works perfectly as is, but seems like too much code and I'm trying to get a feel for how to keep code efficient in Python (or in general really). for d in dev['devices']: if d['name'] == devName: devFound ...
[ "Basically the same, only rewritten with some built-in function and a generator:\ndevFound = any(d['name'] == devName for d in dev['devices'])\n\n", "you could try with the any() function:\nany(d for d in dev[\"devices\"] if d['name'] == devName)\n\n", "Here is a variation on Cédric Julien's answer, because it ...
[ 7, 4, 1 ]
[]
[]
[ "coding_style", "for_loop", "if_statement", "iterator", "python" ]
stackoverflow_0008041276_coding_style_for_loop_if_statement_iterator_python.txt
Q: Targetting Mac OS 10.4+ GUI Application I need to develop a GUI based application for Mac OS 10.4 and newer (including PowerPC) and I am having a hard time decides on what language/framework to go with. If I decide to go with straight Cocoa, I will have to run an older version of Xcode to compile for 10.4 ppc. The...
Targetting Mac OS 10.4+ GUI Application
I need to develop a GUI based application for Mac OS 10.4 and newer (including PowerPC) and I am having a hard time decides on what language/framework to go with. If I decide to go with straight Cocoa, I will have to run an older version of Xcode to compile for 10.4 ppc. Then run the newer version of Xcode on a differe...
[ "There are plenty of applications that run on 10.4 through 10.7. One way is to build using the 10.4u SDK and with the deployment target set for 10.4; that means using Xcode 3 or earlier and it will likely be easier if you have an older system, 10.5 or 10.4, to build on. In general, you can stick to a lowest-common...
[ 0 ]
[]
[]
[ "cocoa", "java", "macos", "python", "user_interface" ]
stackoverflow_0008082432_cocoa_java_macos_python_user_interface.txt
Q: UnicodeDecodeError: 'ascii' codec can't decode error when using render_to_response and dajax.assign I am new at using django and dajax and I'm having a problem using dajax.assign to load a html file into a div in another html when using non-English characters, when I set the site language to English it works fine,...
UnicodeDecodeError: 'ascii' codec can't decode error when using render_to_response and dajax.assign
I am new at using django and dajax and I'm having a problem using dajax.assign to load a html file into a div in another html when using non-English characters, when I set the site language to English it works fine, but when I switch to Spanish it does not. Here is what I am doing: I tried : dajax.assign('#setttabs-1',...
[ "I changed:\ndajax.assign('#setttabs-1','innerHTML',render_to_response('./settings/_change_language.html'), context_instance=RequestContext(request)))\n\nto:\ndajax.assign('#setttabs-1','innerHTML',render_to_string('./settings/_change_language.html'.decode('utf-8'), context_instance=RequestContext(request)))\n\nand...
[ 0 ]
[]
[]
[ "django", "encoding", "python", "render_to_response" ]
stackoverflow_0008071758_django_encoding_python_render_to_response.txt
Q: Analyse python project imports In general I would like to understand what exactly code the code in my projects is actually using from a big framework. First I want to know what are all the imports (possibly with static analysis), and then if possible which of these imports are actually used. For the first problem ...
Analyse python project imports
In general I would like to understand what exactly code the code in my projects is actually using from a big framework. First I want to know what are all the imports (possibly with static analysis), and then if possible which of these imports are actually used. For the first problem I could use a regexp of course, but ...
[ "I'm pleased to say that listing out the imports is actually quite simple.\nI need a minimal implementation of the Importer protocol (defined by PEP 302), where if find_module returns None it will just fallback to the next one.\nThis simple script can actually show the imports done by the program passed in:\nimport...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008063309_python.txt
Q: Python: order in a set of numbers With this code: print set(a**b for a in range(2, 5) for b in range(2, 5)) I get this answer: set([64, 256, 4, 8, 9, 16, 81, 27]) Why it isn't sorted? A: Sets are not ordered collections in python or any other language for that matter. Sets are usually implemented using hash k...
Python: order in a set of numbers
With this code: print set(a**b for a in range(2, 5) for b in range(2, 5)) I get this answer: set([64, 256, 4, 8, 9, 16, 81, 27]) Why it isn't sorted?
[ "Sets are not ordered collections in python or any other language for that matter.\nSets are usually implemented using hash keys (hash codes). So order is probably related to how hash functions are used instead of natural order of its elements.\nIf you need order, please do consider using a list.\n", "Sets are by...
[ 10, 3 ]
[]
[]
[ "python", "set" ]
stackoverflow_0008084825_python_set.txt
Q: Clean URL with BeautifulSoup My script import BeautifulSoup as bs from BeautifulSoup import BeautifulSoup url_list = sys.argv[1] urls = [tag['href'] for tag in BeautifulSoup(open(url_list)).findAll('a')] returns [u'http://www.youtube.com/watch?v=Gg81zi0pheg', u'http://www.youtube.com/watch?v=pP9VjGmmhfo', ...
Clean URL with BeautifulSoup
My script import BeautifulSoup as bs from BeautifulSoup import BeautifulSoup url_list = sys.argv[1] urls = [tag['href'] for tag in BeautifulSoup(open(url_list)).findAll('a')] returns [u'http://www.youtube.com/watch?v=Gg81zi0pheg', u'http://www.youtube.com/watch?v=pP9VjGmmhfo', u'http://www.youtube.com/watch?v=y...
[ "But this is completely basic Python. You're getting a list, and you want to output it one URL per line.\nfor url in urls:\n print url\n\n", "It pretty much is returning that. What you see is simply a list of url strings, encoded as unicode strings (that's why there's a u in front of them).\nIf you simply want...
[ 4, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0008084935_beautifulsoup_python.txt
Q: How to use TextTestRunner class from Python unittest module in failfast mode? All I found in documentation of unittest module is description of TextTestRunner's constructor and the following sample code using its run() method: unittest.TextTestRunner(verbosity=2).run(suite) I would like to know how I can use TextT...
How to use TextTestRunner class from Python unittest module in failfast mode?
All I found in documentation of unittest module is description of TextTestRunner's constructor and the following sample code using its run() method: unittest.TextTestRunner(verbosity=2).run(suite) I would like to know how I can use TextTestRunner in failfast mode.
[ "Constructor of TextTestRunner class has failfast parameter which is not shown in the constructor's documentation.\nUPDATE\nI raised bug 17871 and it's fixed now what you can verify at http://docs.python.org/3.3/library/unittest.html#unittest.TextTestRunner\n" ]
[ 6 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0008068216_python_unit_testing.txt
Q: django customize self._errors I'm overriding the clean method for my variables and want to specify a custom error message on error. myErrorMsg = "This is my error Message" myErrorMsg += "\nThis is my error Message I would like on the next line" self._errors["mytag"] = myErrorMsg However it seems to ignore all lin...
django customize self._errors
I'm overriding the clean method for my variables and want to specify a custom error message on error. myErrorMsg = "This is my error Message" myErrorMsg += "\nThis is my error Message I would like on the next line" self._errors["mytag"] = myErrorMsg However it seems to ignore all line breaks I tried both html <br /> a...
[ "When you tried inserting a <br /> tag, did it literally show up in the output as \"<br />\"? If so, then Django is automatically escaping the error message.\nSee https://docs.djangoproject.com/en/dev/topics/templates/#automatic-html-escaping for more details.\n", "self._errors[\"mytag\"] = self._errors.get(\"my...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008084908_django_python.txt
Q: django convert query set to array of list How can I convert a QuerySet returned to an array of string? myWords = MyGroup.objects.get(name = "bla").allkeyword # to myWords = ["meltemi", "bla"] class MyGroup(models.Model): name = models.CharField(max_length=32, unique=True) allkeyword = models.ManyToManyFie...
django convert query set to array of list
How can I convert a QuerySet returned to an array of string? myWords = MyGroup.objects.get(name = "bla").allkeyword # to myWords = ["meltemi", "bla"] class MyGroup(models.Model): name = models.CharField(max_length=32, unique=True) allkeyword = models.ManyToManyField('KeywordTag') def __unicode__(self): ...
[ "You can use values_list(): \nmyWords = MyGroup.objects.get(name = \"bla\").allkeyword.values_list('name', flat=True)\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008085173_django_python.txt
Q: YouTube video_id from Firefox bookmark.html source code [almost there] bookmarks.html looks like this: <DT><A HREF="http://www.youtube.com/watch?v=Gg81zi0pheg" ADD_DATE="1320876124" LAST_MODIFIED="1320878745" ICON_URI="http://s.ytimg.com/yt/favicon-vflZlzSbU.ico" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...
YouTube video_id from Firefox bookmark.html source code [almost there]
bookmarks.html looks like this: <DT><A HREF="http://www.youtube.com/watch?v=Gg81zi0pheg" ADD_DATE="1320876124" LAST_MODIFIED="1320878745" ICON_URI="http://s.ytimg.com/yt/favicon-vflZlzSbU.ico" ICON="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABEElEQVQ4jaWSPU7DQBCF3wGo7DZp4qtEQqJJlSu4jLgBNS0dRDR...
[ "You should provide a string to BeautifulSoup:\n# parse bookmarks.html\nwith open(sys.argv[1]) as bookmark_file:\n soup = BeautifulSoup(bookmark_file.read())\n\n# extract youtube video urls\nvideo_url_regex = re.compile('http://www.youtube.com/watch')\nurls = [link['href'] for link in soup('a', href=video_url_re...
[ 2, 0 ]
[]
[]
[ "gdata", "python", "youtube" ]
stackoverflow_0008083268_gdata_python_youtube.txt
Q: Python - Setting an attribute to the value of a method - cleanest way? I want a nice convenient attribute to do the following: from django.contrib.auth.models import User user = User.objects.get(id=2) user.company <Company: Big Company L.L.C> I am currently solving this using lambda. In searching for an answer i...
Python - Setting an attribute to the value of a method - cleanest way?
I want a nice convenient attribute to do the following: from django.contrib.auth.models import User user = User.objects.get(id=2) user.company <Company: Big Company L.L.C> I am currently solving this using lambda. In searching for an answer it looks like perhaps the "right" way to solve this would be to use types.Met...
[ "I'm not quite sure I understand correctly what your goal is, but from what I think I understand, it doesn't seem necessary to do any crazy stuff with descriptors here, let alone types.MethodType. A simple property is fine, and if you don't like the lambda, you can use an ordinary function decorated with @property...
[ 1 ]
[ "Building on @SvenMarnach's answer, you can still accomplish the same thing without using lambda. Though you still have to monkey-patch:\ndef _get_user_company(user):\n return UserProfile.objects.get_or_create(user=user)[0].get_company()\nUser.company = property(_get_user_company)\n\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0008084199_django_python.txt
Q: Python dict() and the variable as an argument please take a look >>> var = "name" >>> dict(var=12) {'var': 12} but I need {'name': 12} How to do this ? I use dict() not dict[element] because in such a way that append element to my dict(graph is also Dictionary): graph[v1] = dict(graph[v1], v2=weight) Please help...
Python dict() and the variable as an argument
please take a look >>> var = "name" >>> dict(var=12) {'var': 12} but I need {'name': 12} How to do this ? I use dict() not dict[element] because in such a way that append element to my dict(graph is also Dictionary): graph[v1] = dict(graph[v1], v2=weight) Please help, how to do it or modify my append method
[ "I think you need\ngraph[v1][v2] = weight\n\nNo need to recreate the whole dictionary just to add a new item.\n", ">>> var = \"name\"\n>>> {var : 12}\n{'name': 12}\n\n", "You could just do it the simple way:\nvar = 'name'\nd = dict()\nd[var] = 12\ngraph[v1] = d\n\nOr:\nvar = 'name'\ngraph[v1] = {var:12}\n\nOr y...
[ 4, 2, 1 ]
[]
[]
[ "append", "dictionary", "python" ]
stackoverflow_0008085565_append_dictionary_python.txt
Q: executable made with py2exe doesn't run on windows xp 32bit I created an executable with py2exe on a 64bit windows 7 machine, and distributed the program. On a windows xp 32bit machine the program refuses to run exhibiting the following behavior: a popup window says: program.exe is not a valid win32 application...
executable made with py2exe doesn't run on windows xp 32bit
I created an executable with py2exe on a 64bit windows 7 machine, and distributed the program. On a windows xp 32bit machine the program refuses to run exhibiting the following behavior: a popup window says: program.exe is not a valid win32 application. The command prompt window says "access denied" I checked ...
[ "I think you just need to install 32-bit python and 32-bit py2exe on your machine.... see Can 64-bit python create 32-bit Windows executables\n", "A common problem when you generate executable on Windows 7 and deploy on Windows XP.\nAccording with the py2exe tutorial, you need include the MVC DLL. But the tutori...
[ 7, 4 ]
[]
[]
[ "architecture", "py2exe", "python", "windows" ]
stackoverflow_0006378673_architecture_py2exe_python_windows.txt
Q: Python array caching vs C array caching Pretty inexperienced in Python and I realize this is awfully basic, but how well does Python cache blocks compared to C? For example, in C: gridWidth = 100000 gridHeight = 100000 for (i=0; i<gridHeight; i++){ for (j=0; j<gridWidth; j++){ massiveNum += arr[i*gri...
Python array caching vs C array caching
Pretty inexperienced in Python and I realize this is awfully basic, but how well does Python cache blocks compared to C? For example, in C: gridWidth = 100000 gridHeight = 100000 for (i=0; i<gridHeight; i++){ for (j=0; j<gridWidth; j++){ massiveNum += arr[i*gridWidth + j] } } is way faster than ma...
[ "You question is moot. When you got a whole interpreter, boxed number types, heap allocations of said types, etc. between your code and the machine, cache efficency is the least of your worries. Since Python's built-in sequence types use (dynamic and over-allocating) C arrays under the hood, the same rules should a...
[ 2, 0, 0, 0 ]
[]
[]
[ "caching", "python" ]
stackoverflow_0008085237_caching_python.txt
Q: Python error message: builtins.IndexError: string index out of range I am creating a game where the program will read from a file that contains 5 multiple choice questions and the user can answer this questions and receive a score. However I am getting stuck as I get the same error message: builtins.IndexError: st...
Python error message: builtins.IndexError: string index out of range
I am creating a game where the program will read from a file that contains 5 multiple choice questions and the user can answer this questions and receive a score. However I am getting stuck as I get the same error message: builtins.IndexError: string index out of range here is my code so far: def main(): playagain...
[ "Since there's only one index operation in your code, at anskey[4], my guess is that your inFile has a line that has less than 5 characters on it. \n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008074537_python.txt
Q: django form add css to ModelMultipleChoiceFIeld How exactly do I add css to a forms.ModelMultipleChoiceField I tried to pass in attrs={'class' : 'foo'} But it's failing saying "__init__() got an unexpected keyword argument 'attrs'" my_list = forms.ModelMultipleChoiceField(label='List', required=False, queryset=[])...
django form add css to ModelMultipleChoiceFIeld
How exactly do I add css to a forms.ModelMultipleChoiceField I tried to pass in attrs={'class' : 'foo'} But it's failing saying "__init__() got an unexpected keyword argument 'attrs'" my_list = forms.ModelMultipleChoiceField(label='List', required=False, queryset=[])
[ "It's the widget that needs the attrs, not the form field. \nmy_list = forms.ModelMultipleChoiceField(\n label='List',\n required=False,\n queryset=[],\n widget=SelectMultiple(attrs={'class': 'foobar'}))\n\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008085934_django_python.txt
Q: Python, regex and html: match final tag on line I'm confused about python greedy/not-greedy characters. "Given multi-line html, return the final tag on each line." I would think this would be correct: re.findall('<.*?>$', html, re.MULTILINE) I'm irked because I expected a list of single tags like: "</html>", "<ul...
Python, regex and html: match final tag on line
I'm confused about python greedy/not-greedy characters. "Given multi-line html, return the final tag on each line." I would think this would be correct: re.findall('<.*?>$', html, re.MULTILINE) I'm irked because I expected a list of single tags like: "</html>", "<ul>", "</td>". My O'Reilly's Pocket Reference says tha...
[ "Your problem stems from the fact that you have an end-of-line anchor ('$'). The way non-greedy matching works is that the engine first searches for the first unconstrained pattern on the line ('<' in your case). It then looks for the first '>' character (which you have constrained, with the $ anchor, to be at the ...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008085872_python_regex.txt
Q: Replacing HTML representation to ascii using Python Possible Duplicate: Decode HTML entities in Python string? I have parsed some HTML text. But some punctuations like apostrophe are replaced by &#8217;. How to revert them back to ` P.S: I am using Python/Feedparser Thanks A: The PSF Wiki has some ways of doi...
Replacing HTML representation to ascii using Python
Possible Duplicate: Decode HTML entities in Python string? I have parsed some HTML text. But some punctuations like apostrophe are replaced by &#8217;. How to revert them back to ` P.S: I am using Python/Feedparser Thanks
[ "The PSF Wiki has some ways of doing it. Here is one way:\nimport htmllib\n\ndef unescape(s):\n p = htmllib.HTMLParser(None)\n p.save_bgn()\n p.feed(s)\n return p.save_end()\n\nSee http://wiki.python.org/moin/EscapingHtml\n", "This helped me\nimport HTMLParser\n\nhparser=HTMLParser.HTMLParser()\nnew_...
[ 1, 0 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0008057486_encoding_python.txt
Q: Adding date labels to a reportlab LinePlot chart I am using reportlab to generate a LinePlot chart. I can't seem to get non numeric labels for the X axis. Does anyone have any ideas? This is my Lineplot chart class (note: im donig some calculations and setup outside this class, but you get the gist import reportl...
Adding date labels to a reportlab LinePlot chart
I am using reportlab to generate a LinePlot chart. I can't seem to get non numeric labels for the X axis. Does anyone have any ideas? This is my Lineplot chart class (note: im donig some calculations and setup outside this class, but you get the gist import reportlab from advisor.charting.Font import Font from report...
[ "I produced a simple example that you could test. The result could look like this:\n\n#!/usr/bin/python\nfrom reportlab.graphics.charts.lineplots import LinePlot\nfrom reportlab.graphics.shapes import Drawing\nfrom reportlab.lib import colors\nfrom random import randint\nfrom datetime import date, timedelta\n\n# Ge...
[ 6 ]
[]
[]
[ "charts", "django", "python", "reportlab" ]
stackoverflow_0008082803_charts_django_python_reportlab.txt
Q: XPath: get only elements with a certain subelement I have a filesyste that is represented in an xml document in the following format: <xml xmlns="namespace1" xmlns:ns2="namespace2"> <entry> <id>123</id> <ns2:content name="type">directory</ns2:content> <ns2:content name="numErrors">3</ns2:content> <...
XPath: get only elements with a certain subelement
I have a filesyste that is represented in an xml document in the following format: <xml xmlns="namespace1" xmlns:ns2="namespace2"> <entry> <id>123</id> <ns2:content name="type">directory</ns2:content> <ns2:content name="numErrors">3</ns2:content> </entry> ... <entry> <id>456</id> <ns2:conten...
[ "Use the following XPath expression:\n//ns1:entry[ns2:content[@name='type' and .='directory']]\n\n" ]
[ 5 ]
[]
[]
[ "lxml", "python", "xml", "xpath" ]
stackoverflow_0008085708_lxml_python_xml_xpath.txt
Q: Bash: Variable in single quote First take a look at this question: Bash or GoogleCL: new line in a string parameter I want to add a variable ${date} into the "summary" now: google youtube post ~/videos/cat-falls-down-stairs.avi Comedy \ --tags 'currency of the internet' \ --summary $'Today is ${date}. Poor...
Bash: Variable in single quote
First take a look at this question: Bash or GoogleCL: new line in a string parameter I want to add a variable ${date} into the "summary" now: google youtube post ~/videos/cat-falls-down-stairs.avi Comedy \ --tags 'currency of the internet' \ --summary $'Today is ${date}. Poor whiskers takes a tumble.\nShe'\''s ...
[ "Rather than attempting to expand a variable inside a single quoted string, the typical solution is to concatenate single and double quoted strings. In other words:\n\n'Today is'\"${date}\"'. Poor' ...\n\n", "I'll add yet another option to the list: define a variable as newline, then use that inside double-quote...
[ 15, 4, 1 ]
[]
[]
[ "bash", "command_line", "googlecl", "linux", "python" ]
stackoverflow_0008084389_bash_command_line_googlecl_linux_python.txt
Q: How to open a New window in Python PAMIE I am using PAMIE to auto log in to websites and I have a couple to do. I got the scripts down to do this but I can't get PAMIE to open a new IE window so when I run the script it just opens one logs in and then when the next one is open it closes the first and opens the sec...
How to open a New window in Python PAMIE
I am using PAMIE to auto log in to websites and I have a couple to do. I got the scripts down to do this but I can't get PAMIE to open a new IE window so when I run the script it just opens one logs in and then when the next one is open it closes the first and opens the second and so on. So how do I get PAMIE to open n...
[ "The web page is being re-opened in a single IE instance, because you're only using one PAMIE instance. If you really want multiple IE windows open, you can use multiple PAMIE instances.\nHere is one very simple and crude example. Note that your import line may be slightly different than mine.\nfrom pamie30 impor...
[ 1 ]
[]
[]
[ "pamie", "python" ]
stackoverflow_0008076338_pamie_python.txt
Q: Where should custom query functions be placed? In Django application, several views may contain similar db queries. For instance, a query for all entities where is_active = True and is_online = True. During refactoring, such duplicate calls need to be moved into a function and the question is where this filter/que...
Where should custom query functions be placed?
In Django application, several views may contain similar db queries. For instance, a query for all entities where is_active = True and is_online = True. During refactoring, such duplicate calls need to be moved into a function and the question is where this filter/query function should better be placed. 1) Into definit...
[ "This is exactly what model Managers are for. \nclass MyActiveManager(models.Manager):\n def active(self):\n return self.filter(is_active=True)\n\n def online(self):\n return self.filter(is_online=True)\n\n\nclass MyModel:\n ...\n objects = MyActiveManager()\n\n...\n\nactive_objects = MyMo...
[ 3 ]
[]
[]
[ "django", "oop", "orm", "python" ]
stackoverflow_0008086707_django_oop_orm_python.txt
Q: find a list of keywords from a text string and find inexact matches I have a list of keywords I'm trying to find in a text string. The exact matches works fine but is anyone aware of library that could help with approximate matches so for instance if the list of words I provide are ["hello", "bye"] I'd like it to ...
find a list of keywords from a text string and find inexact matches
I have a list of keywords I'm trying to find in a text string. The exact matches works fine but is anyone aware of library that could help with approximate matches so for instance if the list of words I provide are ["hello", "bye"] I'd like it to watch if the text string has hlelo to a certain degree of "closeness" Any...
[ "Here's what I would do. First, define a string to search in and remove extraneous characters:\n>>> tosearch = \"This is a text string where I typed hlelo but I meant to type hello.\"\n>>> import string\n>>> exclude = set(string.punctuation)\n>>> tosearch = ''.join(ch for ch in tosearch if ch not in exclude)\n>>> t...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008086779_django_python.txt
Q: Python: do r = random_stuff() while not meets_condition(r) I often have to randomly generate stuff with certain constraints. In many cases, it's quicker to ignore the constraints in generation, check if they are met afterwards and redo the process otherwise. Lacking a do keyword, I usually write r = random_stuff()...
Python: do r = random_stuff() while not meets_condition(r)
I often have to randomly generate stuff with certain constraints. In many cases, it's quicker to ignore the constraints in generation, check if they are met afterwards and redo the process otherwise. Lacking a do keyword, I usually write r = random_stuff() while not meets_condition(r): r = random_stuff() That's a ...
[ "while True:\n r = random_stuff()\n if meets_condition(r):\n break\n\nor\ncondition = True\nwhile condition:\n r = random_stuff()\n condition = not meets_condition(r)\n\n", "Your idea is not bad - but not with the new keyword until, but rather like\na = (<expression> while <condition>)\n\nexten...
[ 8, 1, 0, 0, 0 ]
[]
[]
[ "design_patterns", "do_while", "python" ]
stackoverflow_0008080072_design_patterns_do_while_python.txt
Q: python, sqlite3 and two values How to take two values into sqlite3 ? v1 = '2011.11.10' v2 = 10 vv1=(v1,) vv2=(v2,) conn = sqlite3.connect('date.db') c = conn.cursor() c.execute(" UPDATE archive SET date=? WHERE Id=? ", (vv1,vv2) ) # (vv1,vv2) this is not work, how? conn.commit() I know, that probably a simple ,...
python, sqlite3 and two values
How to take two values into sqlite3 ? v1 = '2011.11.10' v2 = 10 vv1=(v1,) vv2=(v2,) conn = sqlite3.connect('date.db') c = conn.cursor() c.execute(" UPDATE archive SET date=? WHERE Id=? ", (vv1,vv2) ) # (vv1,vv2) this is not work, how? conn.commit() I know, that probably a simple , but can't find anything on net. Tn...
[ "v1 = '2011.11.10'\nv2 = 10\n...\nc.execute(\" UPDATE archive SET date=? WHERE Id=? \", (v1,v2) ) \n\nFor cursor.execute, pass a sequence of values, not a sequence of sequence of values.\nFor cursor.executemany, in contrast, you would want to pass a sequence of sequences.\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0008087248_python_sql_sqlite.txt
Q: Why is creating a set from a filter so much faster than creating a list or a tuple? I’m running filter on an interable and want to store the result in a sequence (I need a sequence so that I can use random.choice on it). I noticed that creating a set from a filter object is a lot faster than creating a list or a t...
Why is creating a set from a filter so much faster than creating a list or a tuple?
I’m running filter on an interable and want to store the result in a sequence (I need a sequence so that I can use random.choice on it). I noticed that creating a set from a filter object is a lot faster than creating a list or a tuple. Why is that? I first though that the filter type is a subtype of set, which would e...
[ "filter() returns an iterator in Python 3, and this iterator will be consumed on the first run of the inner for-loop. After that, you are only measuring the speed of the contructor -- that's why you have to repeat it so often to make it consume at least a bit of time.\nSo it seems that the constructor of set() is ...
[ 11, 4 ]
[]
[]
[ "python", "python_3.x", "python_internals" ]
stackoverflow_0008087761_python_python_3.x_python_internals.txt
Q: ipython 0.11 exception visible only after exit of pdb both in ipython 0.10 and 0.11 I set the automatic launch of pdb on exceptions. In ipython 0.10 it works fine: In [1]: 1/0. --------------------------------------------------------------------------- ZeroDivisionError Traceback (most rece...
ipython 0.11 exception visible only after exit of pdb
both in ipython 0.10 and 0.11 I set the automatic launch of pdb on exceptions. In ipython 0.10 it works fine: In [1]: 1/0. --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) /home/zonca/<ipython console> in <module>() ...
[ "It's a known issue with IPython 0.11. It will be fixed in 0.12 (which will hopefully be out before Christmas).\n" ]
[ 1 ]
[]
[]
[ "exception", "ipython", "pdb", "python" ]
stackoverflow_0008084200_exception_ipython_pdb_python.txt
Q: Constructing a QIcon through a QPainter in PyQT I know this is possible, but I cannot for the life of me get the proper code to work. What I want is very simple: a monochromatic rectangle, size, say 20x20 constructed (presumably) through a QPainter. From that I wish to use the painted rectangle as a QIcon for use ...
Constructing a QIcon through a QPainter in PyQT
I know this is possible, but I cannot for the life of me get the proper code to work. What I want is very simple: a monochromatic rectangle, size, say 20x20 constructed (presumably) through a QPainter. From that I wish to use the painted rectangle as a QIcon for use in a QComboBox. Any ideas? Thanks in advance.
[ "Looks like you just need QPixmap.fill for this:\nfrom PyQt4 import QtGui\n\nclass Window(QtGui.QComboBox):\n def __init__(self):\n QtGui.QComboBox.__init__(self)\n self.resize(200, 25)\n pixmap = QtGui.QPixmap(20, 20)\n for color in 'red orange yellow green blue grey violet'.split():...
[ 3 ]
[]
[]
[ "icons", "pyqt", "pyqt4", "python" ]
stackoverflow_0008087521_icons_pyqt_pyqt4_python.txt
Q: How to get the upload progress in using Django? I would like to create an upload progress bar on a website, but I'm not sure how to retrieve the upload progress of the file or image that is uploading. How can I achieve this with Django? A: This is something you'll have to handle on the client-side to provide the...
How to get the upload progress in using Django?
I would like to create an upload progress bar on a website, but I'm not sure how to retrieve the upload progress of the file or image that is uploading. How can I achieve this with Django?
[ "This is something you'll have to handle on the client-side to provide the actual progress bar, so using something like jQuery is probably ideal here.\nAs it turns out, someone had the same problem and wrote up a blog post with how they solved it using jQuery. It uses this snippet and the jQuery timers plugin.\n",...
[ 5, 0 ]
[]
[]
[ "ajax", "django", "javascript", "progress_bar", "python" ]
stackoverflow_0003018041_ajax_django_javascript_progress_bar_python.txt
Q: Python encoding UnicodeDecodeError I have been plugging away at this for hours and I just can't seem to get to the bottom of it. I have been through this website in detail and although others seem to have a similar problem but their solutions given just don't work for me. I have a python script which reads the HTM...
Python encoding UnicodeDecodeError
I have been plugging away at this for hours and I just can't seem to get to the bottom of it. I have been through this website in detail and although others seem to have a similar problem but their solutions given just don't work for me. I have a python script which reads the HTML of a website and uses beautiful soup t...
[ "Note that you're getting a decode error from a call to encode. This is the ugliest part of Python 2: it lets you try to encode a string that is already encoded, by first decoding it as ascii. What you're doing is equivalent to this:\ns.decode('ascii', 'strict').encode('ascii', 'ignore')\n\nI think this should do w...
[ 6, 2 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0008087255_character_encoding_python.txt
Q: Is there anyway I can ask python to explicitly treat all floats as 32bits even on a 64bit machine? Is there anyway I can ask python to explicitly treat all floats as 32bits even on a 64bit machine? I don't want to change the codes... A: Python's float is built-in and set in stone. You can't change that. You coul...
Is there anyway I can ask python to explicitly treat all floats as 32bits even on a 64bit machine?
Is there anyway I can ask python to explicitly treat all floats as 32bits even on a 64bit machine? I don't want to change the codes...
[ "Python's float is built-in and set in stone. You can't change that. You could use float32 from numpy.\n", "This size of the float is baked in at compilation time. You can pass in a compile option to treat a C double as a float in a fresh python executable file.\n", "http://docs.python.org/tutorial/floatingpoi...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008087753_python.txt
Q: minute average csv files I have a big csv file with datetime and value recorded every 10 seconds. The csv file looks like this: Datetime Data 2008-10-01 12:00:10, 34 2008-10-01 12:00:20, 55 2008-10-01 12:00:30, 46 2008-10-01 12:00:40, 33 2008-10-01 12:00:50, 55 2008-10-01 12:01:00, 21 2...
minute average csv files
I have a big csv file with datetime and value recorded every 10 seconds. The csv file looks like this: Datetime Data 2008-10-01 12:00:10, 34 2008-10-01 12:00:20, 55 2008-10-01 12:00:30, 46 2008-10-01 12:00:40, 33 2008-10-01 12:00:50, 55 2008-10-01 12:01:00, 21 2008-10-01 12:01:10, 2 2008-1...
[ "It seems to me the easiest way is just to treat the time as a string, rather than a time, and use itertools.groupby:\nfrom csv import reader\nfrom itertools import groupby\n\nlines = \"\"\"Datetime Data\n2008-10-01 12:00:10, 34\n2008-10-01 12:00:20, 55\n2008-10-01 12:00:30, 46\n2008-10-01 12:00:40, 33\...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008087957_python.txt
Q: Python generators and coroutines I am studying coroutines and generators in various programming languages. I was wondering if there is a cleaner way to combine together two coroutines implemented via generators than yielding back at the caller whatever the callee yields? Let's say that we are using the following c...
Python generators and coroutines
I am studying coroutines and generators in various programming languages. I was wondering if there is a cleaner way to combine together two coroutines implemented via generators than yielding back at the caller whatever the callee yields? Let's say that we are using the following convention: all yields apart from the l...
[ "Edit: I recommend using Greenlet. But if you're interested in a pure Python approach, read on.\nThis is addressed in PEP 342, but it's somewhat tough to understand at first. I'll try to explain simply how it works.\nFirst, let me sum up what I think is the problem you're really trying to solve.\nProblem\nYou have ...
[ 18, 2 ]
[]
[]
[ "coroutine", "generator", "python" ]
stackoverflow_0005948643_coroutine_generator_python.txt
Q: Managing logs/warnings in Python extensions TL;DR version: What do you use for configurable (and preferably captured) logging inside your C++ bits in a Python project? Details follow. Say you have a a few compiled .so modules that may need to do some error checking and warn user of (partially) incorrect data. Curr...
Managing logs/warnings in Python extensions
TL;DR version: What do you use for configurable (and preferably captured) logging inside your C++ bits in a Python project? Details follow. Say you have a a few compiled .so modules that may need to do some error checking and warn user of (partially) incorrect data. Currently I'm having a pretty simplistic setup where ...
[ "I'm a big believer in having as much work happen in Python as possible, leaving only the work that has to happen in C in C. So I like #2 better than #1, but you are right, it clutters up all your function signatures.\nI'd create a module-level object to handle the logging, sort of like a callback. The Python cod...
[ 2, 0 ]
[]
[]
[ "log4cxx", "logging", "python", "unit_testing" ]
stackoverflow_0002995027_log4cxx_logging_python_unit_testing.txt
Q: If len(list) is not divisible by 3, then exclude last item in a function . Python 2.7.1 if you have a string string='abcdefg' and you wanted to check if the length of the string is divisible by 3 len(string) what command would you use? A: You can use the modulo (division remainder) operator %: if len(s) % 3 ==...
If len(list) is not divisible by 3, then exclude last item in a function . Python 2.7.1
if you have a string string='abcdefg' and you wanted to check if the length of the string is divisible by 3 len(string) what command would you use?
[ "You can use the modulo (division remainder) operator %:\nif len(s) % 3 == 0:\n ...\n\nIf you want to strip the string to a length divisible by 3, use\ns[:len(s) // 3 * 3]\n\nor\ns[:-(len(s) % 3)]\n\n" ]
[ 9 ]
[]
[]
[ "division", "function", "python", "string", "string_length" ]
stackoverflow_0008088340_division_function_python_string_string_length.txt
Q: PyQt4 names showing as undefined in eclipse, but it runs fine I am using Eclipse 3.7.1 with the latest PyDev add-in for Python coding. I am using PyQt4. At the top of my file I have: from PyQt4.QtCore import * from PyQt4.QtGui import * In addition, I have the PyQt4 tree included in the Project Explorer listing. H...
PyQt4 names showing as undefined in eclipse, but it runs fine
I am using Eclipse 3.7.1 with the latest PyDev add-in for Python coding. I am using PyQt4. At the top of my file I have: from PyQt4.QtCore import * from PyQt4.QtGui import * In addition, I have the PyQt4 tree included in the Project Explorer listing. However, eclipse still thinks the names like QMainWindow are undefin...
[ "PyQt is actually a wrapping of C++ Qt libraries. So they are not .py files and PyDev can't analyze them to get what is in them. You need to add PyQt4 in the Forced Builtins tab, so that PyDev can use a Python shell to \"look into\" those libraries and know what is in them. That will also give you code-completion f...
[ 16, 0 ]
[]
[]
[ "eclipse", "pydev", "pyqt4", "python", "python_2.7" ]
stackoverflow_0008082230_eclipse_pydev_pyqt4_python_python_2.7.txt
Q: Python 2.7 socket htons I am currently looking into socket programming in python and I am experiencing some strange behavior with socket.htons() ... it appears to be flipping the bytes on every call. I am implementing a simple ping script, as far as I am aware network byte order is big endian and my systems byte o...
Python 2.7 socket htons
I am currently looking into socket programming in python and I am experiencing some strange behavior with socket.htons() ... it appears to be flipping the bytes on every call. I am implementing a simple ping script, as far as I am aware network byte order is big endian and my systems byte order is little endian . If I...
[ "Everything looks to be working like it should. Even in your example, the 2 bytes are being swapped, then back again. If the system byte order is the same as the network, then its a no-op, but your question states that the network bytes order is Big, and the host is Little, so the swapping is what it should be do...
[ 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008088278_python_sockets.txt
Q: How can I serve a WSGI Python app using Mongrel2? This is an attempt to discover a canonical answer for something that seems to be hard to Google for right now. I am writing a web app in Pyramid, and I have the luxury of deciding what my server stack will look like. I've heard very good things about Mongrel2, and ...
How can I serve a WSGI Python app using Mongrel2?
This is an attempt to discover a canonical answer for something that seems to be hard to Google for right now. I am writing a web app in Pyramid, and I have the luxury of deciding what my server stack will look like. I've heard very good things about Mongrel2, and would like to try using it to serve my app. However, I...
[ "In pursuit of a canonical answer, here are the WSGI handlers that I've found while looking for a way to get Mongrel2 to serve a WSGI app. Right now, it looks like wsgid is the best bet for Django users, but terminally flawed for others, and the alternatives are flawed. \n\n\nThe wsgid project is not yet at 1.0, bu...
[ 6, 3, 2, 2 ]
[]
[]
[ "mongrel2", "pyramid", "python", "wsgi" ]
stackoverflow_0007774307_mongrel2_pyramid_python_wsgi.txt
Q: Trying to get Mongrel2 + m2wsgi to work I'm trying to get mongrel2 to work with m2wsgi. What I need to do so I can see "Hello World!" in my browser? Mongrel2 is installed but any site configurations are not done yet. def app(environ, start_response): start_response("200 OK", [('Content-Type', 'text/plain')]) r...
Trying to get Mongrel2 + m2wsgi to work
I'm trying to get mongrel2 to work with m2wsgi. What I need to do so I can see "Hello World!" in my browser? Mongrel2 is installed but any site configurations are not done yet. def app(environ, start_response): start_response("200 OK", [('Content-Type', 'text/plain')]) return ['Hello World!', ] Trying to run it: m...
[ "If Mongrel2 is not fully configured, as your \"Mongrel2 is installed but any site configurations are not done yet\" statement suggests, then it won't be able to find your app (the m2wsgi documentation is perhaps not as clear about this as it might be). Here's a tutorial on getting Mongrel2 set up and ready to conn...
[ 0, 0 ]
[]
[]
[ "mongrel2", "python", "wsgi" ]
stackoverflow_0006645498_mongrel2_python_wsgi.txt
Q: How can I loop through a list of dicts, backwards, until a particular key value is found? I have a dict of dicts: for i in results[2]: print i Recurring: {'p_pnref': 'E78P2DFEA7E3', 'p_result': '12'} Recurring: {'p_pnref': 'E78P2E93B933', 'p_result': '0'} Recurring: {'p_pnref': 'E35P0A5578D3', 'p_result': '12...
How can I loop through a list of dicts, backwards, until a particular key value is found?
I have a dict of dicts: for i in results[2]: print i Recurring: {'p_pnref': 'E78P2DFEA7E3', 'p_result': '12'} Recurring: {'p_pnref': 'E78P2E93B933', 'p_result': '0'} Recurring: {'p_pnref': 'E35P0A5578D3', 'p_result': '12'} Recurring: {'p_pnref': 'E24P0AA506C3', 'p_result': '24'} Recurring: {'p_pnref': 'E25P0AFF2C4...
[ "I think reversed is what you are looking for:\nrecords = [\n {'p_pnref': 'E78P2DFEA7E3', 'p_result': '12'},\n {'p_pnref': 'E78P2E93B933', 'p_result': '0'},\n {'p_pnref': 'E35P0A5578D3', 'p_result': '12'},\n {'p_pnref': 'E24P0AA506C3', 'p_result': '24'},\n {'p_pnref': 'E25P0AFF2C43', 'p_result': '24'...
[ 4, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008088527_dictionary_python.txt
Q: Descramble a message string using a permutation as a key Help i'm trying to descramble a file using a permutation as a key,i know how to scramble it but i need to create a function to descramble it back to what it was using the same permutation key, here's the code: def stringtoarray(S): A = [] i = 0 w...
Descramble a message string using a permutation as a key
Help i'm trying to descramble a file using a permutation as a key,i know how to scramble it but i need to create a function to descramble it back to what it was using the same permutation key, here's the code: def stringtoarray(S): A = [] i = 0 while i<len(S): A.append(S[i]) i += 1 retur...
[ "You have, in a sense, already written the de-scrambler. All you have to do is feed scrambler the inverse permutation. Below, the inverse permutation is given by argsort(P) where P is the permutation. \n\ndef scramble(S, P): #Scramble string S with permutation P\n pn = len(P) # length of permutation array\n ...
[ 3, 0, 0 ]
[]
[]
[ "permutation", "python", "string" ]
stackoverflow_0008088535_permutation_python_string.txt