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:
Windows 7 and python with rsync
I want to develop with a Python module that's using rsync for file transfers over SFTP and webdav.
I found one lib called pysync (and others eventually). But I'm on Windows 7. I use VisualStudio 2010, but the build fails... due to "problems".
So I wonder whether someone knows a wor... | Windows 7 and python with rsync | I want to develop with a Python module that's using rsync for file transfers over SFTP and webdav.
I found one lib called pysync (and others eventually). But I'm on Windows 7. I use VisualStudio 2010, but the build fails... due to "problems".
So I wonder whether someone knows a working librsync or something for Window... | [
"Are you really tied to rsync? You're using SFTP to transfer the files, so paramiko may work for you. If you really need a working librsync, you have a couple of options.\n\nSearch for a pre compiled version and install (hope your google fu is strong...)\nInstall cygwin, download the source, run the make install, a... | [
1
] | [] | [] | [
"cross_platform",
"python",
"rsync"
] | stackoverflow_0006455809_cross_platform_python_rsync.txt |
Q:
remote backup with appcfg.py/bulkloader.py with script. how to handle the email/password fields?
I'm trying to write a script in python or bash which executes bulkloader.py to backup my entities on appengine but I don't know how to handle the email and password prompts on the bulkloader.
is there a way to insert ... | remote backup with appcfg.py/bulkloader.py with script. how to handle the email/password fields? | I'm trying to write a script in python or bash which executes bulkloader.py to backup my entities on appengine but I don't know how to handle the email and password prompts on the bulkloader.
is there a way to insert those fields in a bash or python script?
| [
"Here document. Available for bash scripts and languages like Perl, PHP, Python, PowerShell and Ruby.\n"
] | [
1
] | [] | [] | [
"bash",
"google_app_engine",
"python"
] | stackoverflow_0006455126_bash_google_app_engine_python.txt |
Q:
Mysterious problem with Fandjango
I've just configured fandjango with my simply django application.
Here's the files:
VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render
from fandjango.decorators import facebook_authorization_required
@facebook_authorization_required()
def home(reque... | Mysterious problem with Fandjango | I've just configured fandjango with my simply django application.
Here's the files:
VIEWS.PY
from django.http import HttpResponse
from django.shortcuts import render
from fandjango.decorators import facebook_authorization_required
@facebook_authorization_required()
def home(request):
return render(request, 'home.h... | [
"Instead of doing \n{% if facebook_user.first_name %} \ncheck for \n{% if facebook.user %} \n\nThat will actually check for the user if he was authorized; the first one may give you random errors -missing first name on some users maybe-.\n",
"Do you have caching turned on in your application? Does the problem occ... | [
1,
0
] | [] | [] | [
"django",
"django_facebook",
"facebook",
"python"
] | stackoverflow_0006433391_django_django_facebook_facebook_python.txt |
Q:
find items in list1 that are also in list2 and delete items not in list1
i want to find items that are in list1:
list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape']
that are also in list2:
list2 = ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']
the problem is that the... | find items in list1 that are also in list2 and delete items not in list1 | i want to find items that are in list1:
list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape']
that are also in list2:
list2 = ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']
the problem is that the items in list2 have numbers after the needed item. how do i find the common i... | [
"# using a set makes the later `x in keep` test faster\nkeep = set(['peach', 'plum', 'apple', 'kiwi', 'grape'])\n\nlist2= ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', \n 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']\n\n# x.split(',',1)[0] = the part before the first `,` \nnew = [x for x in list2 if x.split... | [
9,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006456300_list_python.txt |
Q:
python3.2 ERROR on aix6.1
i compiled python3.2 on aix6.2 server, but it doesnt work. Pop error like this
Fatal Python error: Py_Initialize: Unable to get the locale encoding
UnicodeEncodeError: 'filesystemencoding' codec can't encode character '\uda18' in position 28: Invalid wide character
IOT/Abort trap(coredump... | python3.2 ERROR on aix6.1 | i compiled python3.2 on aix6.2 server, but it doesnt work. Pop error like this
Fatal Python error: Py_Initialize: Unable to get the locale encoding
UnicodeEncodeError: 'filesystemencoding' codec can't encode character '\uda18' in position 28: Invalid wide character
IOT/Abort trap(coredump)
Any help is welcome.
xxxxxxx... | [
"This might need a lot of step by step debugging, since I can't imagine where that surrogate character came from.\nFirst, do the following in your shell:\n$ echo LANG:$LANG LC_CTYPE:$LC_CTYPE\n\nPlease update your question with the output of this command.\nI suggest you use an encoding that is UTF-8 (e.g en_US.UTF-... | [
2
] | [] | [] | [
"aix",
"build",
"compilation",
"python"
] | stackoverflow_0006455371_aix_build_compilation_python.txt |
Q:
Loop over and editing the items in a list after looping over some input data
Why can i only get the [-1.0,0.0,1.0,2.0,3.0], instead of
[0.0,1.0,2.0,3.0,4.0]
[-2.0,-1.0,0.0,1.0,2.0]
[-1.0,0.0,1.0,2.0,3.0], thank you
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1
for line in iter(f): ... | Loop over and editing the items in a list after looping over some input data | Why can i only get the [-1.0,0.0,1.0,2.0,3.0], instead of
[0.0,1.0,2.0,3.0,4.0]
[-2.0,-1.0,0.0,1.0,2.0]
[-1.0,0.0,1.0,2.0,3.0], thank you
V = [1,2,3,4,5]
f = open('Qin.txt') # values in Qin.txt: 1
for line in iter(f): 3
Z = float(line) 2
... | [
"Something was messed up while you were posting.\nI guess you have this:\nV = [1,2,3,4,5]\nf = open('Qin.txt') # values in Qin.txt: 1\nfor line in iter(f): 3\n Z = float(line) 2\n\n c = []\n for i in range(len(V)):\n c.appe... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006456536_python.txt |
Q:
Python: List operations
I am 100% new to python, I know I need to read more but I need to do this task right now that's why I am using python for it. Here is my code:
outputList = []
for line in open('cron.log', 'r'):
m = line[45:47]
outputList.append(m)
So I opened the file, read through lines, and append... | Python: List operations | I am 100% new to python, I know I need to read more but I need to do this task right now that's why I am using python for it. Here is my code:
outputList = []
for line in open('cron.log', 'r'):
m = line[45:47]
outputList.append(m)
So I opened the file, read through lines, and append the 2 chars I need into a li... | [
"#This is from the beginning\nfor i in range(1, len(outputList)):\n # == could be what ever comparison you want. Any one in particular?\n if outputList[i] == outputList[i-1]:\n #do whatever you need to do\n\n",
"Also you can use something like this:\na = [1, 2, 3, 4, 5, 6, 7, 8]\n# proceed backward\... | [
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006456716_list_python.txt |
Q:
jQuery parseJSON object question/issue
I've been playing around with jQuery's parseJSON and simplejson and I can't seem to figure out why I'm unable to get my variables to print or compare.
I know my Python return statement is correct, because if it wasn't the jQuery.ajax would return false and the "error" code wo... | jQuery parseJSON object question/issue | I've been playing around with jQuery's parseJSON and simplejson and I can't seem to figure out why I'm unable to get my variables to print or compare.
I know my Python return statement is correct, because if it wasn't the jQuery.ajax would return false and the "error" code would run. So I'm not sure what I'm doing wro... | [
"I had this problem recently and it was because I was using single quotes in my JSON, which parseJSON considers invalid.\n$.parseJSON(\"{'key':'value'}\")\nInvalid JSON: {'key':'value'}\n$.parseJSON('{\"key\":\"value\"}')\nObject\n\nThe way I figured this out was to call parseJSON from the JS console window in chro... | [
1,
1
] | [] | [] | [
"jquery",
"json",
"python"
] | stackoverflow_0006457145_jquery_json_python.txt |
Q:
Is it possible to make an accordion style check list in wxPython?
I want to make a checklist with a accordion style in a wxPython widget. I know about checklistbox, but I couldn't find anything in the official docs concerning it. Has anyone done this?
A:
You can use a wx.combo.ComboCtrl which allows any custom p... | Is it possible to make an accordion style check list in wxPython? | I want to make a checklist with a accordion style in a wxPython widget. I know about checklistbox, but I couldn't find anything in the official docs concerning it. Has anyone done this?
| [
"You can use a wx.combo.ComboCtrl which allows any custom popup, and combine this with a wx.CheckListBox.\nHere's what is could look like, folded:\n\n\nand unfolded:\n\n\nTo get this, I started with the ComboCtrl example in the demo, and in the ListCtrlComboPopup list class I replaced ListCtrl with CheckListBox eve... | [
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002906110_python_wxpython.txt |
Q:
How do you make python recognize read a precompiled shared file?
I have a package I've created in C++ and, have already compiled it into a shared library.
When I link against it with my own main function, I can initialize the package by calling the initialization function directly, initfoo, and everything works fi... | How do you make python recognize read a precompiled shared file? | I have a package I've created in C++ and, have already compiled it into a shared library.
When I link against it with my own main function, I can initialize the package by calling the initialization function directly, initfoo, and everything works fine.
How do I get python to recognize my shared library as a package, s... | [
"If you have a shared library with initfoo symbol exported (note: since you've tagged the question c++ — make sure it's an extern \"C\" symbol, otherwise name mangling will prevent the interpreter from finding it), then it's already a Python module, and can be loaded directly, with no further work. You only need to... | [
2
] | [] | [] | [
"c++",
"cmake",
"distutils",
"python",
"python_c_api"
] | stackoverflow_0006457418_c++_cmake_distutils_python_python_c_api.txt |
Q:
AppEngine - Weird ID assignment in AppEngine HR DataStore
Possible Duplicate:
How to implement “autoincrement” on Google AppEngine
I've got a Python App in AppEngine. I'm using High Replication Datastore.
This is my problem:
I have an entity (call it Person for simplicity) that is saved without parents, it's a r... | AppEngine - Weird ID assignment in AppEngine HR DataStore |
Possible Duplicate:
How to implement “autoincrement” on Google AppEngine
I've got a Python App in AppEngine. I'm using High Replication Datastore.
This is my problem:
I have an entity (call it Person for simplicity) that is saved without parents, it's a root entity in the AppEngine terms.
I don't set a key_name befo... | [
"Why do you need them to be consecutive?\nApp Engine datastore doesn't assign IDs to be consecutive.\nIf you want consecutive IDs, you must assign IDs yourself. Don't forget to use allocate_id_range (http://code.google.com/appengine/docs/python/datastore/functions.html) so that app engine doesn't automatically assi... | [
3
] | [] | [] | [
"flask",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0006457019_flask_google_app_engine_google_cloud_datastore_python.txt |
Q:
django templates performance
Which is more efficient in Django: to render an object using the template language? or to push the code to render the object via a templatetag function using the python language?
A:
The question is sort-of nonsensical. Templates are always going to be slower than a hand-tuned render... | django templates performance | Which is more efficient in Django: to render an object using the template language? or to push the code to render the object via a templatetag function using the python language?
| [
"The question is sort-of nonsensical. Templates are always going to be slower than a hand-tuned rendering solution, but template tags still need to run through the Template machinery, so you lose out any advantage there. If you want ultra-high efficiency, consider writing all of the HTML as an array of Python str... | [
3,
3,
1
] | [] | [] | [
"django",
"django_templates",
"performance",
"python"
] | stackoverflow_0006456627_django_django_templates_performance_python.txt |
Q:
Modifying a single line in a file
Is there a way, in Python, to modify a single line in a file without a for loop looping through all the lines?
The exact positions within the file that need to be modified are unknown.
A:
Unless we're talking about a fairly contrived situation in which you already know a lot abo... | Modifying a single line in a file | Is there a way, in Python, to modify a single line in a file without a for loop looping through all the lines?
The exact positions within the file that need to be modified are unknown.
| [
"Unless we're talking about a fairly contrived situation in which you already know a lot about the file, the answer is no. You have to iterate over the file to determine where the newline characters are; there's nothing special about a \"line\" when it comes to file storage -- it all looks the same. \n",
"This sh... | [
5,
5,
3
] | [] | [] | [
"file_io",
"for_loop",
"python"
] | stackoverflow_0006457253_file_io_for_loop_python.txt |
Q:
How to filter out warning info
My code imports a function(import_function) from the other module(written by other guys).
ret = import_function(arg1,arg2)
The function will PRINT some warning info when it runs(the function uses print() to display the warning messages).
The question is: how can I filter out all the... | How to filter out warning info | My code imports a function(import_function) from the other module(written by other guys).
ret = import_function(arg1,arg2)
The function will PRINT some warning info when it runs(the function uses print() to display the warning messages).
The question is: how can I filter out all these warning info?
I have tried the f... | [
"I think the issue with with sample code you provided is that os.devnull is a string; not a file object. You need to wrap it in an open(). Like this:\nsys.stderr = open(os.devnull, 'w')\nret = import_function(arg1,arg2)\nsys.stderr = sys.__stderr__\n\nthere is no need to backup the original stdios, they are retain... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006457593_python.txt |
Q:
Converting an open curve to a list of ordered pixels: a Python test code with numpy
I have the image of an open curve in a numpy array and I need to build a list of points coordinates ordered according to their position on the curve.
I wrote a draft script using numpy and mahotas. It may not be optimal.
I know th... | Converting an open curve to a list of ordered pixels: a Python test code with numpy | I have the image of an open curve in a numpy array and I need to build a list of points coordinates ordered according to their position on the curve.
I wrote a draft script using numpy and mahotas. It may not be optimal.
I know that OpenCV can do this for a closed curve. Can OpenCV do the same (faster) with an open cu... | [
"Assuming that only one curve is present in the matrix/image and that each point on the curve has between 1 and 2 neighbours, the following function will provide the results you need.\nIt works by taking the point closest to the top left hand corner, and forming a chain of points by iteratively finding the closest ... | [
3
] | [] | [] | [
"curve",
"numpy",
"python",
"shapes"
] | stackoverflow_0006282462_curve_numpy_python_shapes.txt |
Q:
What is a good open source pastebin in Python or Perl?
I'm looking for an open-source pastebin web-application written in either Python or Perl.
I need it in order to implement a web-based specialized editor for my own needs, and I want to borrow code / ideas from the pastebin since I don't have much experience i... | What is a good open source pastebin in Python or Perl? | I'm looking for an open-source pastebin web-application written in either Python or Perl.
I need it in order to implement a web-based specialized editor for my own needs, and I want to borrow code / ideas from the pastebin since I don't have much experience in web programming.
Can you point to one (or a few) ?
Thanks ... | [
"I like pastebot, which powers http://paste.pocoo.org/ (for example). It's Perl and uses POE.\n",
"Lodgeit is written in Python and is a nice pastebin\n",
"Stickum is written using TurboGears and supports syntax highlighting for a large number of languages thanks to its use of Pygments. You can see it in action... | [
12,
11,
3,
3,
1
] | [
"Have you considered Gist from the github?\nhttp://gist.github.com/ \n\nGist is a simple way to share snippets and pastes with others. All gists are git repositories, so they are automatically versioned, forkable and usable as a git repository.\n\n",
"Hpaste is good. comes with pln txt and python highlighting (py... | [
-1,
-2,
-2,
-3,
-3
] | [
"open_source",
"pastebin",
"perl",
"python"
] | stackoverflow_0000218717_open_source_pastebin_perl_python.txt |
Q:
Python list replacement
How to replace each element in a list with an element in the same position from another list? I thought something like this might work:
list1 = ['a', 'b', 'c', 'd']
list2 = ['a_replaced', 'b_replaced', 'c_replaced']
text = open(textfile, 'r')
n = 0
for line in text:
line = line[0:len... | Python list replacement | How to replace each element in a list with an element in the same position from another list? I thought something like this might work:
list1 = ['a', 'b', 'c', 'd']
list2 = ['a_replaced', 'b_replaced', 'c_replaced']
text = open(textfile, 'r')
n = 0
for line in text:
line = line[0:len(line)-1]
line.replace(co... | [
"5 things:\n\nYou reference col and outcol which I assume are actually list1 and list2.\nlist1 and list2 are different sizes, this will crash\nYou're not checking the bounds on n, so if your text file is longer than 4 lines it will crash\nThe line n + 1 doesn't actually do anything, it should be n += 1\nline.replac... | [
3,
0,
0,
0
] | [] | [] | [
"list",
"python",
"replace"
] | stackoverflow_0006457692_list_python_replace.txt |
Q:
Python - from Script to Web App?
I have a Python script that can run in command line/console which works with the Google Calendar Data API to do some tasks like retrieve calendars and modify or update events. I want to turn it into a web application/interface, but was not sure what would be the optimal or simplest... | Python - from Script to Web App? | I have a Python script that can run in command line/console which works with the Google Calendar Data API to do some tasks like retrieve calendars and modify or update events. I want to turn it into a web application/interface, but was not sure what would be the optimal or simplest way going about it.
Some precursor in... | [
"Go check out Google App Engine. There's a Python API. It works well with other Google services, like Calendar. Probably the fastest way to get where you want to go.\n",
"Google Appengine would be much easier for you in terms of getting a web application available and up on the web. You might want to look at the ... | [
3,
0,
0
] | [] | [] | [
"python",
"web_applications",
"web_services"
] | stackoverflow_0006448814_python_web_applications_web_services.txt |
Q:
Out of Core Rules Engine
Are there any implementations of production rule systems that operate out of core?
I've checked out the open source implementations like CLIPS and Jess, but these only operate in memory, so they tend to crash or force heavy disk swapping when operating on large numbers of facts and rules (... | Out of Core Rules Engine | Are there any implementations of production rule systems that operate out of core?
I've checked out the open source implementations like CLIPS and Jess, but these only operate in memory, so they tend to crash or force heavy disk swapping when operating on large numbers of facts and rules (e.g. in the billions/trillions... | [
"you can check JENA and similar RDF rule engines which are designed to work with very large fact databases.\n",
"This isn't a direct answer to your question, but it may give you a line of attack on the problem.\nBack in the 80's and 90's we fielded an information retrieval system that allowed for very large numbe... | [
1,
1
] | [] | [] | [
"machine_learning",
"python",
"rule_engine",
"rules"
] | stackoverflow_0006311829_machine_learning_python_rule_engine_rules.txt |
Q:
python, cleaning a list
Trying to clean up a python list, I am able to remove exact string matches. How do I remove partial matches?
exclude = ['\n','Hits','Sites','blah','blah2','partial string','maybe here']
newlist = []
for item in array:
if item not in exclude:
newlist.append(item)
Problem here ... | python, cleaning a list | Trying to clean up a python list, I am able to remove exact string matches. How do I remove partial matches?
exclude = ['\n','Hits','Sites','blah','blah2','partial string','maybe here']
newlist = []
for item in array:
if item not in exclude:
newlist.append(item)
Problem here is "item not in exclude"... w... | [
"Try the following generator instead:\ndef remove_similar(array, exclude):\n for item in array:\n for fault in exclude:\n if fault in item:\n break\n else:\n yield item\n\n",
"I'm not sure what you're asking here. Do you want to filter out all elements in arr... | [
2,
1,
1,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006458006_python_string.txt |
Q:
Will the function in assertRaises complete before unit test ends?
def test_invalid_host(self):
controller = SSHController("host name")
self.assertRaises(SSHException, controller.login())
#test_invalid_host End
Will controller.login() finish before the test passes or will the test pass as soon as SSHExcept... | Will the function in assertRaises complete before unit test ends? | def test_invalid_host(self):
controller = SSHController("host name")
self.assertRaises(SSHException, controller.login())
#test_invalid_host End
Will controller.login() finish before the test passes or will the test pass as soon as SSHException is raised?
| [
"As soon as the SSHException is raised, the exception is caught by the assertRaises method. So the rest of controller.login is not run.\nPS. Be sure to call \nself.assertRaises(SSHException, controller.login)\n\nwithout the parentheses after controller.login. If you write controller.login() then indeed the login me... | [
3
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0006458568_python_unit_testing.txt |
Q:
Where will Python be logging errors for me (moving from PHP)
I am a PHPer new to Python (2.7 on Win32) and I would like to know where Python is shoving any errors it finds?
Do I need to turn something on, if so where do I do that?
Or, is the idea that you develop using a shell and watch errors spat out via that?
P... | Where will Python be logging errors for me (moving from PHP) | I am a PHPer new to Python (2.7 on Win32) and I would like to know where Python is shoving any errors it finds?
Do I need to turn something on, if so where do I do that?
Or, is the idea that you develop using a shell and watch errors spat out via that?
Please share any other good Python debugging/sanity-saving mechanis... | [
"Python development is normally done in a shell, and you get a full traceback printed out on any uncaught exception.\nIf you want to log errors to file, have a look at the logging module. You can either catch exceptions directly, or override the sys.excepthook function which is called for an uncaught error. If you'... | [
4
] | [] | [] | [
"debugging",
"error_handling",
"python"
] | stackoverflow_0006458447_debugging_error_handling_python.txt |
Q:
getting context for a word
I am dealing with an extremely large text file (around 3.77 GB), and trying to extract all the sentences a specific word occurs in and write out to a text file.
So the large text file is just many lines of text:
line 1 text ....
line 2 text ....
I have also extracted the unique word lis... | getting context for a word | I am dealing with an extremely large text file (around 3.77 GB), and trying to extract all the sentences a specific word occurs in and write out to a text file.
So the large text file is just many lines of text:
line 1 text ....
line 2 text ....
I have also extracted the unique word list from the text file, and want t... | [
"First problem, you never close fin.\nMaybe you should try something like this : \nfout=open('word_context_3000_4000(4).txt','a')\n\nfin=open('corpus2.txt')\nfor x in unique_word[3000:4000]:\n fout.write('\\n'+x+'\\t')\n fin.seek(0) # go to the begining of the file\n for line in fin:\n if x ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006457531_python.txt |
Q:
Create a python class that is treated as a list, but with more features?
I have a class called dataList. It is basically a list with some metadata---myDataList.data contains the (numpy) list itself, myDataList.tag contains a description, etc. I would like to be able to make myDataList[42] return the corresponding ... | Create a python class that is treated as a list, but with more features? | I have a class called dataList. It is basically a list with some metadata---myDataList.data contains the (numpy) list itself, myDataList.tag contains a description, etc. I would like to be able to make myDataList[42] return the corresponding element of myDataList.data, and I would like for Numpy, etc. to recognize it a... | [
"You can subclass list and provide additional methods:\nclass CustomList(list):\n def __init__(self, *args, **kwargs):\n list.__init__(self, args[0])\n\n def foobar(self):\n return 'foobar'\n\nCustomList inherits the methods of Python's ordinary lists and you can easily let it implement further ... | [
8,
3,
2
] | [] | [] | [
"inheritance",
"list",
"numpy",
"python"
] | stackoverflow_0006458461_inheritance_list_numpy_python.txt |
Q:
How can I post more than 64K of data via python's httplib2.Http request method?
If I do this:
h = httplib2.Http(timeout=60)
resp, content = h.request(uri, method=method, body=body, headers=headers,
redirections=redirections,
connection_type=connection_type)
If ... | How can I post more than 64K of data via python's httplib2.Http request method? | If I do this:
h = httplib2.Http(timeout=60)
resp, content = h.request(uri, method=method, body=body, headers=headers,
redirections=redirections,
connection_type=connection_type)
If body is more than 64K the data appears to be truncated.
This is on a 32-bit Python r... | [
"First time I've ever heard of this. Here is a short program to show that this works for me. Note that the full.cgi script I have running just returns the request headers and request body back in the response body. When I run this the full 64K+ of content, including the ' the end' roundtrips.\nimport httplib2\n\nh ... | [
1,
1
] | [] | [] | [
"http",
"httplib2",
"python"
] | stackoverflow_0006393053_http_httplib2_python.txt |
Q:
How to easily publish a new Mercurial repository or subrepository on a shared central server? (Push a clone)
Mercurial's vast publishing options include HgWeb (and formerly HgWebDir), which is almost perfect for my needs. HgWeb 1.6 supports multiple repositories, including collections.
So hgweb.config could conta... | How to easily publish a new Mercurial repository or subrepository on a shared central server? (Push a clone) | Mercurial's vast publishing options include HgWeb (and formerly HgWebDir), which is almost perfect for my needs. HgWeb 1.6 supports multiple repositories, including collections.
So hgweb.config could contain something like this:
[collections]
/home/user/collection1 = /home/user/collection1
/home/user/collection2 = /ho... | [
"The default web interface of Mercurial does not support remote creations of repositories (see Why doesn't Mercurial support remote repository creations over HTTP?). However, if your fellow developers principally are allowed to login to the Mercurial server using SSH and if you have some kind of shared filespace on... | [
2
] | [] | [] | [
"cgi",
"hgweb",
"mercurial",
"python"
] | stackoverflow_0006455729_cgi_hgweb_mercurial_python.txt |
Q:
How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are in the txt files?
Why don´t I get the following result, in this order?
[-2.0, -1.0, 0.0, 1.0, 2.0]
[-1.0, 0.0, 1.0, 2.0, 3.0]
[-2.0, -1.0, 0.0, 1.0, 2.0], instead i get the second list in the wro... | How can I loop through a list changing the list elements at each time step, adding or subtracting input values that are in the txt files? | Why don´t I get the following result, in this order?
[-2.0, -1.0, 0.0, 1.0, 2.0]
[-1.0, 0.0, 1.0, 2.0, 3.0]
[-2.0, -1.0, 0.0, 1.0, 2.0], instead i get the second list in the wrong place.
Can I edit list elements in a more consistent way, considering this form of input data?
My objective is to change a initial list (V) ... | [
"OR:\nV = [1,2,3,4,5]\n\nf = open('Qin.txt') # values in Qin.txt: 1, 3, 2 \nfdata = f.readlines()\nf.close()\n\ng = open('Qout.txt') # values in Qout.txt: 4, 5, 5 \ngdata = g.readlines()\ng.close()\n\noutput = [[v + float(x) - float(y) for v in V] for y in gdata for x in fdata]\n\nprint output \n>>> [[-2.0,... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006459078_python.txt |
Q:
Find keys in multidimensional dict based on value
I have a dict of dicts that looks like the following:
{ 'a':{'foo': True,
'bar': 1,
'baz': 'abc'},
'b':{'foo': True,
'bar': 21,
'baz': 'abc'},
'c':{'foo': True,
'bar': 3,
'baz': 'cba'}}
What is the most efficient way t... | Find keys in multidimensional dict based on value | I have a dict of dicts that looks like the following:
{ 'a':{'foo': True,
'bar': 1,
'baz': 'abc'},
'b':{'foo': True,
'bar': 21,
'baz': 'abc'},
'c':{'foo': True,
'bar': 3,
'baz': 'cba'}}
What is the most efficient way to filter the dict to only include those keys whose sub-... | [
"{k: v for k, v in my_dict.items() if v['baz'] == 'abc'}\n\n"
] | [
7
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006459707_dictionary_python.txt |
Q:
Detect alternating signs
Is there a nice and short way to tell whether a python list (or numpy array) contains numbers with alternating signs? In other words:
is_alternating_signs([1, -1, 1, -1, 1]) == True
is_alternating_signs([-1, 1, -1, 1, -1]) == True
is_alternating_signs([1, -1, 1, -1, -1]) == False
A:
OK, ... | Detect alternating signs | Is there a nice and short way to tell whether a python list (or numpy array) contains numbers with alternating signs? In other words:
is_alternating_signs([1, -1, 1, -1, 1]) == True
is_alternating_signs([-1, 1, -1, 1, -1]) == True
is_alternating_signs([1, -1, 1, -1, -1]) == False
| [
"OK, thanks to SO \"related\" feature. I found this question and adopted the answer by ianalis and the comment by lazyr\ndef is_alternating_signs(a):\n return numpy.all(numpy.abs(numpy.diff(numpy.sign(a))) == 2)\n\n\n\nprint is_alternating_signs([1, -1, 1, -1, 1]) \nprint is_alternating_signs([-1, 1, -1, 1, -1])... | [
7,
3,
1,
0,
0,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006451514_numpy_python.txt |
Q:
Python: How to delete a HTML header from a text string?
Possible Duplicate:
using python, Remove HTML tags/formatting from a string
I read in a HTML file:
fi = open("Tree.html", "r")
text = fi.read()
I want to delete the HTML header from the text:
text = re.sub("<head>.*?</head>", "", text)
Why does this not w... | Python: How to delete a HTML header from a text string? |
Possible Duplicate:
using python, Remove HTML tags/formatting from a string
I read in a HTML file:
fi = open("Tree.html", "r")
text = fi.read()
I want to delete the HTML header from the text:
text = re.sub("<head>.*?</head>", "", text)
Why does this not work?
| [
"It looks like you're not catching newlines. You need to add the DOTALL flag.\ntext = re.sub(\"<head>.*?</head>\", \"\", text, flags=re.DOTALL)\n\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006460107_python_regex.txt |
Q:
Boost.python error in hello world example
I keep getting the error when I try to compile the hello world example with bjam. Everything in Jamroot file ran ok, except the last line (when I commented this line, no error happens):
run-test hello : hello_ext hello.py ;
The error is:
capture-output bin/hello.test/gcc-... | Boost.python error in hello world example | I keep getting the error when I try to compile the hello world example with bjam. Everything in Jamroot file ran ok, except the last line (when I commented this line, no error happens):
run-test hello : hello_ext hello.py ;
The error is:
capture-output bin/hello.test/gcc-4.5.2/debug/hello
export: 3: LD_LIBRARY_PATH: b... | [
"I had encountered similar problem during building adobe asl library. The problem was the version of installed from ubuntu repositories bjam (3.1.16). After installing latest bjam from sourceforge (3.1.18), everything worked as it should.\nPS. OS is Ubuntu 11.04\n"
] | [
0
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0006162258_boost_c++_python.txt |
Q:
Can you migrate backwards to before the first migration in South?
Can you migrate an app backwards to before its first migration in Django South? If not, are there plans to add such functionality, perhaps using an option passed to migrate?
A:
./manage.py migrate myapp zero
See: https://docs.djangoproject.com/en... | Can you migrate backwards to before the first migration in South? | Can you migrate an app backwards to before its first migration in Django South? If not, are there plans to add such functionality, perhaps using an option passed to migrate?
| [
"./manage.py migrate myapp zero\n\nSee: https://docs.djangoproject.com/en/1.9/ref/django-admin/#migrate\nIn Django 1.11: https://docs.djangoproject.com/en/1.11/ref/django-admin/#migrate\n"
] | [
87
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0006460598_django_django_south_python.txt |
Q:
feincms applicationcontent not working with feincms_translatedpage_or_base
I have used the code from the examples in the docs, but I cannot make ApplicationContent show anything on a translated page.
The ApplicationContent is on both the base-language-page and the translated page, but it only shows up on the base-... | feincms applicationcontent not working with feincms_translatedpage_or_base | I have used the code from the examples in the docs, but I cannot make ApplicationContent show anything on a translated page.
The ApplicationContent is on both the base-language-page and the translated page, but it only shows up on the base-language-page.
The regions are being rendered like this:
{% feincms_translatedpa... | [
"Yes, merely rendering the content is not sufficient for ApplicationContent to do and/or show anything.\nThe list of content blocks has to be determined earlier so that process() and finalize() can be called on all content types offering these methods (f.e. ApplicationContent.process).\nIf you want to inherit conte... | [
1
] | [] | [] | [
"content_management_system",
"django",
"feincms",
"python"
] | stackoverflow_0006329695_content_management_system_django_feincms_python.txt |
Q:
convert an isoformat string to python datetime object
Possible Duplicate:
How to parse ISO formatted date in python?
I have an isoformat datetime as a string like the example below -
'2011-05-31T04:35:33.127-05:00'
What is the best way convert it to a python datetime object? I came across some posts that tell h... | convert an isoformat string to python datetime object |
Possible Duplicate:
How to parse ISO formatted date in python?
I have an isoformat datetime as a string like the example below -
'2011-05-31T04:35:33.127-05:00'
What is the best way convert it to a python datetime object? I came across some posts that tell how to get an isoformat string but not the other way round.... | [
"There is an strptime function, just like in C.\nhttp://docs.python.org/library/datetime.html#datetime.datetime.strptime\n"
] | [
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0006460423_datetime_python.txt |
Q:
Python Tkinter continuous line with endpoints that don't match up
Basically I'm trying to create a continuous line (starting when the user clicks, ending when they right click), and I have it working, but for some reason the end points (ovals), don't really line up perfectly with the sides of the line (it becomes ... | Python Tkinter continuous line with endpoints that don't match up | Basically I'm trying to create a continuous line (starting when the user clicks, ending when they right click), and I have it working, but for some reason the end points (ovals), don't really line up perfectly with the sides of the line (it becomes really obvious when you try drawing a straight line with multiple point... | [
"Rather than draw circles at the end of lines, you can use the capstyle and joinstyle options of the line.\nFor example:\nself.Line = self.DrawArea.create_line(self.startx,self.starty, x, y, fill='red',\n width=self.linewidth, capstyle=ROUND, joinstyle=ROUND)\n\n",
"On my screen, and my version of Python (2.5 ... | [
2,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006459937_python_tkinter.txt |
Q:
How to move all .log and .txt files to a new folder
I'm having trouble figuring out how to move all .log and .txt files in a certain folder and it's subdirectories to a new folder. I understand how to move one file with shutil. But, I tried to use a loop, unsuccessfully, to move all. Can someone help me with this?... | How to move all .log and .txt files to a new folder | I'm having trouble figuring out how to move all .log and .txt files in a certain folder and it's subdirectories to a new folder. I understand how to move one file with shutil. But, I tried to use a loop, unsuccessfully, to move all. Can someone help me with this? Thanks ....
import os, os.path
import re
def prin... | [
"According to the traceback, the log-files are already existing. The Python docs to the os.rename say:\n\nOn Windows, if dst already exists, OSError will be raised [...].\n\nNow you can either:\n\ndelete the files manually or\ndelete the files automatically using os.remove(path)\n\nIf you want the files to be autom... | [
1,
1
] | [] | [] | [
"python",
"shutil"
] | stackoverflow_0006459757_python_shutil.txt |
Q:
Why implicitly check for emptiness in Python?
The Zen of Python says that explicit is better than implicit.
Yet the Pythonic way of checking a collection c for emptiness is:
if not c:
# ...
and checking if a collection is not empty is done like:
if c:
# ...
ditto for anything that can have "zeroness" or ... | Why implicitly check for emptiness in Python? | The Zen of Python says that explicit is better than implicit.
Yet the Pythonic way of checking a collection c for emptiness is:
if not c:
# ...
and checking if a collection is not empty is done like:
if c:
# ...
ditto for anything that can have "zeroness" or "emptiness" (tuples, integers, strings, None, etc)
... | [
"This best practice is not without reason.\nWhen testing if object: you are basically calling the objects __bool__ method, which can be overridden and implemented according to object behavior.\nFor example, the __bool__ method on collections (__nonzero__ in Python 2) will return a boolean value based on whether the... | [
21,
7,
7,
5,
4,
4,
2,
1
] | [] | [] | [
"idioms",
"python"
] | stackoverflow_0006459513_idioms_python.txt |
Q:
python downloading data (urllib, urllib2)
I have a link like this, direct to a mp3 file. So when I put it in my browser, basically asks me if I want to download the file, however when I do the same thing with python by the following code :
> data = urllib2.urlopen("http://www23.zippyshare.com/d/44123087/497548/Lil... | python downloading data (urllib, urllib2) | I have a link like this, direct to a mp3 file. So when I put it in my browser, basically asks me if I want to download the file, however when I do the same thing with python by the following code :
> data = urllib2.urlopen("http://www23.zippyshare.com/d/44123087/497548/Lil%20Wayne%20ft.%20Eminem%20-%20Drop%20The%20Worl... | [
"urllib2 handles redirection transparently. You might want to see what the server is actually doing when it is presenting such a redirection as well allowing you to download. You might want to subclass the redirect handler and see which property of the header is giving you the url and use urlretrieve to download th... | [
2,
0
] | [] | [] | [
"html",
"mp3",
"python",
"urllib",
"urllib2"
] | stackoverflow_0006461471_html_mp3_python_urllib_urllib2.txt |
Q:
python interpreter keys are swapped
I am trying to get some kicking in python and decided to run python on my ubuntu natty installation, still I am having a weird problem...
It seems that inside the interpreter my keyboard keys are completely swapped by US keyboard ones, like, when I try to type a ' it gives me a ... | python interpreter keys are swapped | I am trying to get some kicking in python and decided to run python on my ubuntu natty installation, still I am having a weird problem...
It seems that inside the interpreter my keyboard keys are completely swapped by US keyboard ones, like, when I try to type a ' it gives me a ?.
The thing is, how do I change this set... | [
"The issue isn't with python. this might help: http://pubs.opengroup.org/onlinepubs/000095399/utilities/stty.html\n"
] | [
2
] | [] | [] | [
"keyboard",
"linux",
"python",
"tty",
"ubuntu"
] | stackoverflow_0006461524_keyboard_linux_python_tty_ubuntu.txt |
Q:
Where do the variables in template inheritance come from?
So based on what I've read from template inheritance, say you have
base.html
content.html
content_view.py
and there is a function in content_view.py whose template_name="content.html" and content.html extends base.html. So the locals() which is returned b... | Where do the variables in template inheritance come from? | So based on what I've read from template inheritance, say you have
base.html
content.html
content_view.py
and there is a function in content_view.py whose template_name="content.html" and content.html extends base.html. So the locals() which is returned by the funnction in content_view.py is passed into content.html,... | [
"\nFirst of all is this correct?\n\nNo, locals() are not passed to the template from the view. \nThe variables which are passed to the template are specified in the dictionary argument when calling render or render_to_response, adding some more data from context processors. You can also later use a custom built te... | [
0
] | [] | [] | [
"django",
"inheritance",
"python",
"templates",
"view"
] | stackoverflow_0006461406_django_inheritance_python_templates_view.txt |
Q:
Getting two class game to interact
So I know this site gets far too many questions about Zed Shaw's Learn Python the Hard Way, but I'm going through ex42., extra credit #3, has got me hung up.
I am having trouble getting the class Engine to effectively start and transition into the class Map where the game can beg... | Getting two class game to interact | So I know this site gets far too many questions about Zed Shaw's Learn Python the Hard Way, but I'm going through ex42., extra credit #3, has got me hung up.
I am having trouble getting the class Engine to effectively start and transition into the class Map where the game can begin going through the different functions... | [
"There's a lot wrong here. \nYour code as shown is illegally indented; it looks like __init__() and play() should be indented to be members of class Engine, and death() and princess_lives_here() indented into Map.\nThe __init__ of a class needs double underscores, not single, on each end.\nThe line:\ne = \"princess... | [
3,
1
] | [] | [] | [
"class",
"function",
"python"
] | stackoverflow_0006193962_class_function_python.txt |
Q:
Python 3.x call function with sys.argv[]
I have a function that processes file contents, but right now I have the filename hardcoded in the function like this as a keyword argument:
def myFirstFunc(filename=open('myNotes.txt', 'r')):
pass
and I call it like this:
myFirstFunc()
I would like to treat the argu... | Python 3.x call function with sys.argv[] | I have a function that processes file contents, but right now I have the filename hardcoded in the function like this as a keyword argument:
def myFirstFunc(filename=open('myNotes.txt', 'r')):
pass
and I call it like this:
myFirstFunc()
I would like to treat the argument as a filename and process the contents.
... | [
"something like this:\n#!/usr/bin/python3\n\nimport sys\n\n\ndef myFirstFunction():\n return open(sys.argv[1], 'r')\n\nopenFile = myFirstFunction()\n\nfor line in openFile:\n print (line.strip()) #remove '\\n'? if not remove .strip()\n #do other stuff\n\nopenFile.close() #don't forget to close open file\n\... | [
8,
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006460541_python_python_3.x.txt |
Q:
Python interpreter waits for child process to die
Contents of check.py:
from multiprocessing import Process
import time
import sys
def slp():
time.sleep(30)
f=open("yeah.txt","w")
f.close()
if __name__=="__main__" :
x=Process(target=slp)
x.start()
sys.exit()
In windows 7, from cmd, if I call python check.... | Python interpreter waits for child process to die | Contents of check.py:
from multiprocessing import Process
import time
import sys
def slp():
time.sleep(30)
f=open("yeah.txt","w")
f.close()
if __name__=="__main__" :
x=Process(target=slp)
x.start()
sys.exit()
In windows 7, from cmd, if I call python check.py, it doesn't immediately exit, but instead waits for ... | [
"What you seem to want is running your script as a background process. The solution in How to start a background process in Python? should do, you will have to specify some command line parameter that tell your script to go into slp rather than spawning a new process.\n",
"have a look at subprocess module instead... | [
1,
0
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0006461689_multiprocessing_python.txt |
Q:
String to list without using regex
If I have a string as in
mystring = "1212, 1215, 2132, 2312, 3333"
What is the recommended approach to convert it into a list? as in
mylist = [1212, 1215, 2132, 2312, 3333]
Please note that mystring can assume a single value too, as in mystring = "1212"
A:
map(int, mystring.... | String to list without using regex | If I have a string as in
mystring = "1212, 1215, 2132, 2312, 3333"
What is the recommended approach to convert it into a list? as in
mylist = [1212, 1215, 2132, 2312, 3333]
Please note that mystring can assume a single value too, as in mystring = "1212"
| [
"map(int, mystring.split(','))\n\nThat's it.\n",
"List comprehension syntax:\n[int(n) for n in mystring.split(',')]\n\n"
] | [
10,
6
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0006462048_list_python_string.txt |
Q:
how to combine python into wxpython
Hello I am an amateur programmer. I built a simple text twister game and named it as texttwister_compy.py. I also have been able to build a simple GUI. But I need to learn how to integrate my python program into my wxpython GUI.
Here is my wxpython code:
import os
import wx
cla... | how to combine python into wxpython | Hello I am an amateur programmer. I built a simple text twister game and named it as texttwister_compy.py. I also have been able to build a simple GUI. But I need to learn how to integrate my python program into my wxpython GUI.
Here is my wxpython code:
import os
import wx
class MainWindow(wx.Frame):
def __init__... | [
"Simply bind your action events to your button or mouse clicks. So if your game involves changing the number in a box and incrementing it one for every click a simple call to your function in the game to as input and update the GUI. On that click its not only supposed to update the box, but do something in your gam... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006461864_python_wxpython.txt |
Q:
Multi-threaded multi-client server in python
I'm writing a multi-threaded, multi-client server in python. Multiple users can connect to it with telnet and basically use it as a chat server. I'm able to connect with two clients through telnet, but I run into the two following problems:
The first client to send a... | Multi-threaded multi-client server in python | I'm writing a multi-threaded, multi-client server in python. Multiple users can connect to it with telnet and basically use it as a chat server. I'm able to connect with two clients through telnet, but I run into the two following problems:
The first client to send a message is immediately disconnected.
The other cl... | [
"It's much simpler and better to implement this sort of thing using Twisted, which lets you handle multiple clients concurrently in a single thread, as well as providing a nicer API.\nHere's how you write a chat server using Twisted (full example in chatserver.py):\nclass MyChat(basic.LineReceiver):\n def connec... | [
2,
0,
0
] | [] | [] | [
"echo",
"multithreading",
"python",
"sockets"
] | stackoverflow_0005544013_echo_multithreading_python_sockets.txt |
Q:
can you make an image transparent over another image in pygame?
I'm able to set an image to be transparent using the both the set_colorkey method and the convert_alpha method over a surface background. However, when I try to overlap two images the transparency is lost for some reason.
So to reiterate, is there ... | can you make an image transparent over another image in pygame? | I'm able to set an image to be transparent using the both the set_colorkey method and the convert_alpha method over a surface background. However, when I try to overlap two images the transparency is lost for some reason.
So to reiterate, is there a way to make part of an image transparent over another image (e.g. t... | [
"I'm not sure if you're running into \"buggy\" behavior or not. It is possible color-key alpha doesn't support what you are trying to do, and it is possible that you are either defining your pixel data wrong, or that there is some sort of bug (video driver or pygame) that you're experiencing.\nBut I do have a work... | [
0
] | [] | [] | [
"png",
"pygame",
"python",
"transparency"
] | stackoverflow_0006462338_png_pygame_python_transparency.txt |
Q:
Django simplejson error
I'm attempting to use simplejson to parse a JSON string. For some reason, when I use simplejson.loads I recieve the following error:
ERROR:root:Exception in request:
Traceback (most recent call last):
File "C:\django\lokus_web_new\django\core\handlers\base.py", line 111, in get_
response
re... | Django simplejson error | I'm attempting to use simplejson to parse a JSON string. For some reason, when I use simplejson.loads I recieve the following error:
ERROR:root:Exception in request:
Traceback (most recent call last):
File "C:\django\lokus_web_new\django\core\handlers\base.py", line 111, in get_
response
response = callback(request, *c... | [
"This is not a valid JSON string. Use double quotes:\n{\"type\":\"basic\",\"id\":\"156\",\"payload\":{\"text\":\"asd\"}}\n\n"
] | [
2
] | [] | [] | [
"django",
"python",
"simplejson"
] | stackoverflow_0006462404_django_python_simplejson.txt |
Q:
Python loop that always executes at least once?
Possible Duplicate:
do-while loop in Python?
How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through googl... | Python loop that always executes at least once? |
Possible Duplicate:
do-while loop in Python?
How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through google and python docs)
| [
"while True:\n #loop body\n if (!condition): break\n\n",
"You could try:\ndef loop_body():\n # implicitly return None, which is false-ish, at the end\n\n\nwhile loop_body() or condition: pass\n\nBut realistically I think I would do it the other way. In practice, you don't really need it that often anyway... | [
15,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0006461648_loops_python.txt |
Q:
Choosing when to execute in Python
I'm a student writing a Python script to achieve the following:
Given a .py file(that includes drawing logic from pygame), show the code as it is being executed, along with a frame that displays the drawings. I am writing this as a tool for a professor to more easily teach algori... | Choosing when to execute in Python | I'm a student writing a Python script to achieve the following:
Given a .py file(that includes drawing logic from pygame), show the code as it is being executed, along with a frame that displays the drawings. I am writing this as a tool for a professor to more easily teach algorithms, by being able to demonstrate the c... | [
"Why don't you wrap the python debugger itself into your program, and have it execute within it - and use its hooks to graphically track the current line being executed?\nI've also seen someone embed an ironPython interpreter into their program - and you can probably track the current code being executed within it ... | [
0
] | [] | [] | [
"debugging",
"eval",
"exec",
"pygame",
"python"
] | stackoverflow_0006460596_debugging_eval_exec_pygame_python.txt |
Q:
Executing commands from windows batch file using Python, without creating batch file
I need to execute below command (and couple of other similar) to collect Windows OS event logs:
' wmic nteventlog where filename="appevent" call BackupEventLog C:\appevent.evt '
The command executes successfully through cmd promp... | Executing commands from windows batch file using Python, without creating batch file | I need to execute below command (and couple of other similar) to collect Windows OS event logs:
' wmic nteventlog where filename="appevent" call BackupEventLog C:\appevent.evt '
The command executes successfully through cmd prompt. and collects file C:\appevent.evt
But when i use Python os.system or os.popen to exec... | [
"Its due to the \\a in the string. Escape the \\ in the string by replacing it with \\\\:\n' wmic nteventlog where filename=\"appevent\" call BackupEventLog C:\\\\appevent.evt '\n\nor use a raw string:\nr' wmic nteventlog where filename=\"appevent\" call BackupEventLog C:\\appevent.evt '\n\n"
] | [
2
] | [] | [] | [
"batch_file",
"python",
"windows",
"wmic"
] | stackoverflow_0006462684_batch_file_python_windows_wmic.txt |
Q:
why is __init__ module in django project loaded twice In the same process?
I'm trying to wrap a c library in a high-level python interface with Boost.Python. One of the client contracts of the c library is that one of the handles can only be allocated once per-process. I was hoping I could enforce this contract on... | why is __init__ module in django project loaded twice In the same process? | I'm trying to wrap a c library in a high-level python interface with Boost.Python. One of the client contracts of the c library is that one of the handles can only be allocated once per-process. I was hoping I could enforce this contract on the python side by using a module global.
Here is my django component module's... | [
"Because it's being loaded via two different entries in sys.path. Be consistent about your imports; I recommend importing the module without going through the project, e.g. import <app>.<module>. Configuring a WSGI container so that you're not dependent on manage.py's mangling of sys.path will help.\n"
] | [
2
] | [] | [] | [
"boost_python",
"django",
"python"
] | stackoverflow_0006461674_boost_python_django_python.txt |
Q:
Print y-axis on histogram and use dict function as input
How can I use a dict from another function as input argument to histo below, and label the y axis with dict values (in addition to the x-axis)? Or is there a simpler alternative to this code at all?
def histo(his_dict = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, ... | Print y-axis on histogram and use dict function as input | How can I use a dict from another function as input argument to histo below, and label the y axis with dict values (in addition to the x-axis)? Or is there a simpler alternative to this code at all?
def histo(his_dict = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1} ):
x_max = max(his_dict.keys()) + 2 #get maximum va... | [
"If I were you, I would just draw the histogram with pylab.\nimport pylab\n\npylab.hist([1,1,1,2,2,3])\npylab.show()\n\nAnd instead of passing a dict, just pass a raw list of values.\nThe y-axis will be computed automatically.\n"
] | [
1
] | [] | [] | [
"label",
"python"
] | stackoverflow_0006462754_label_python.txt |
Q:
Project Euler question 36
I'm up to question 36 and I thought this would be simple. As usual, I am apparently wrong. I'm trying to do this in Python (because I don't know Python). My code is below. I'm getting 19 as the output, which is apparently incorrect. I don't see what I'm missing. Any suggestions (without c... | Project Euler question 36 | I'm up to question 36 and I thought this would be simple. As usual, I am apparently wrong. I'm trying to do this in Python (because I don't know Python). My code is below. I'm getting 19 as the output, which is apparently incorrect. I don't see what I'm missing. Any suggestions (without correcting the code) would be ap... | [
"It looks like your code is correct, but you need to read carefully what it asks you to submit as the answer. I can't be any more specific without giving it away!\n",
"From http://projecteuler.net/index.php?section=problems&id=36\nFind the sum of all numbers, less than one million, which are palindromic in base... | [
6,
1,
1
] | [
"\n\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: neo\n\"\"\"\ndef bin(x):\n result = ''\n x = int(x)\n while x > 0:\n mod = x % 2\n x /= 2\n result = str(mod) + result\n return result\nprint sum(i for i in xrange(1,1000001)\\\n if str(i)==str(i)[::-1] and str(bin(i))==str(bin(i))[:... | [
-1
] | [
"python"
] | stackoverflow_0006458060_python.txt |
Q:
Tell windows which monitor to display dialogs on
I've got a program which is using multiple monitors. The program is showing special visualizations on the second monitor. At one point, the program uses windows shell functions to send files to the recycle bin. However, when it does this, the delete confirmation dia... | Tell windows which monitor to display dialogs on | I've got a program which is using multiple monitors. The program is showing special visualizations on the second monitor. At one point, the program uses windows shell functions to send files to the recycle bin. However, when it does this, the delete confirmation dialog comes on top of my visualization. This is particul... | [
"which function are you using to send the files to the recycle bin? if you use SHFileOperation you can pass a parent HWND. perhaps make that an invisible WS_EX_TOOLWINDOW window on the other monitor.\ni would expect the API, treating that window as a parent, would center relative to that window, but i haven't trie... | [
2
] | [] | [] | [
"multiple_monitors",
"python",
"pywin32",
"winapi",
"windows"
] | stackoverflow_0006460062_multiple_monitors_python_pywin32_winapi_windows.txt |
Q:
Django Socail-Auth and My Auth
i tried to install django social auth,
which is located on
https://github.com/omab/django-social-auth
how can i associate a regular registration and social auth
for example a user doesn't have any account in twitter or facebook etc ..
how can i associate django.contrib.auth with soc... | Django Socail-Auth and My Auth | i tried to install django social auth,
which is located on
https://github.com/omab/django-social-auth
how can i associate a regular registration and social auth
for example a user doesn't have any account in twitter or facebook etc ..
how can i associate django.contrib.auth with social auth
by giving him the choice of... | [
"django-social-auth provides views for authenticated with a particular backend (such as Google, Facebook, or Twitter). Take a look at the code defined in social_auth's URLconf: https://github.com/omab/django-social-auth/blob/master/social_auth/urls.py\nOnce you've got social_auth installed, if you want to log in w... | [
0
] | [] | [] | [
"django",
"django_socialauth",
"python",
"socialauth"
] | stackoverflow_0005226650_django_django_socialauth_python_socialauth.txt |
Q:
Using python (urllib) to download a file, how to get the real filename?
So I finally managed to get my script to login to a website and download a file... however, in some instances I will have a url like "http://www.test.com/index.php?act=Attach&type=post&id=3345". Firefox finds the filename ok... so I should be... | Using python (urllib) to download a file, how to get the real filename? | So I finally managed to get my script to login to a website and download a file... however, in some instances I will have a url like "http://www.test.com/index.php?act=Attach&type=post&id=3345". Firefox finds the filename ok... so I should be able to.
I am unable to find the "Content-Disposition" header via something ... | [
"It is the task of the remote server/Service to provide the content-disposition header.\nThere is nothing you can do unless the remote server/service is under your own control..\n"
] | [
2
] | [] | [] | [
"authentication",
"download",
"python",
"url",
"urllib2"
] | stackoverflow_0006463179_authentication_download_python_url_urllib2.txt |
Q:
My Python items aren't adding to the list, len isn't changing after recalling
Alright, I'm making a game of sorts... I've done it with append as well -_-
When I call back and add the next item(i.e. #2 after doing #1) I get just that item in the print out...
such as this:
> 1
You put your Hatchet into the bag
Pre... | My Python items aren't adding to the list, len isn't changing after recalling | Alright, I'm making a game of sorts... I've done it with append as well -_-
When I call back and add the next item(i.e. #2 after doing #1) I get just that item in the print out...
such as this:
> 1
You put your Hatchet into the bag
Press enter to add more items
['Hatchet']
>
> 2
You put your Toothbrush into the ba... | [
"Your problem is that you're adding something to bag, but then you're recursing into the start of func again, where it has a different scope. It then assigns [] to bag, leaving it empty. Something you could do is make func take an optional argument:\ndef func(bag=None):\n if bag is None:\n bag = []\n #... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006463236_python.txt |
Q:
Subtract Overlaps Between Two Ranges Without Sets
NO SETS!
I can't use Sets because:
The ranges will be too long.
They will take up too much memory
The creation of the sets themselves will take too long.
Using only the endpoints of the of the ranges, is there an optimal way to subtract two lists of ranges?
Examp... | Subtract Overlaps Between Two Ranges Without Sets | NO SETS!
I can't use Sets because:
The ranges will be too long.
They will take up too much memory
The creation of the sets themselves will take too long.
Using only the endpoints of the of the ranges, is there an optimal way to subtract two lists of ranges?
Example:
r1 = (1, 1000), (1100, 1200)
r2 = (30, 50), (60,... | [
"The interval package may provide all that you need.\nfrom interval import Interval, IntervalSet\nr1 = IntervalSet([Interval(1, 1000), Interval(1100, 1200)])\nr2 = IntervalSet([Interval(30, 50), Interval(60, 200), Interval(1150, 1300)])\nprint(r1 - r2)\n\n>>> [1..30),(50..60),(200..1000],[1100..1150)\n\n",
"This ... | [
13,
8,
5,
3,
1,
1,
0
] | [] | [] | [
"overlap",
"python",
"range"
] | stackoverflow_0006462272_overlap_python_range.txt |
Q:
MySQLdb - Error with simple statement
db = MySQLdb.connect("XXXXXXXX","root", "XXXXXX", database)
cursor = db.cursor()
cursor.execute('INSERT INTO media_files (ID, DATA) VALUES ("test", "test")')
cursor.execute("commit")
This statement errors and I cannot seem to figure out why. Any thoughts? The table media_fil... | MySQLdb - Error with simple statement | db = MySQLdb.connect("XXXXXXXX","root", "XXXXXX", database)
cursor = db.cursor()
cursor.execute('INSERT INTO media_files (ID, DATA) VALUES ("test", "test")')
cursor.execute("commit")
This statement errors and I cannot seem to figure out why. Any thoughts? The table media_files btw only has the two columns, ID and DAT... | [
"'INSERT INTO media_files (ID, DATA) VALUES (\"test\", \"test\")'\n\nUsing the parentheses will fix the problem. You were inserting one piece of data but provided 2 fields.\n"
] | [
2
] | [] | [] | [
"insert",
"mysql",
"mysql_python",
"python"
] | stackoverflow_0006463951_insert_mysql_mysql_python_python.txt |
Q:
python easy_install.pth for sys.path
I looked at my easy_install.pth file in /usr/local/lib/python2.6/dist-packages, which I think is the default directory when I download packages via easy_install. Inside easy_install.pth, one of the entry is the directory itself, i.e /usr/local/lib/python2.6/dist-packages. Howev... | python easy_install.pth for sys.path | I looked at my easy_install.pth file in /usr/local/lib/python2.6/dist-packages, which I think is the default directory when I download packages via easy_install. Inside easy_install.pth, one of the entry is the directory itself, i.e /usr/local/lib/python2.6/dist-packages. However, when I check sys.path, /usr/local/lib/... | [
"The easy_install tool installs it in the right place for you. If you don't or can't run it as root then you can place new packages in your private locate.\neasy_install-2.6 --user \n\nWill install in your home directory. \n"
] | [
0
] | [] | [] | [
"easy_install",
"python"
] | stackoverflow_0006464272_easy_install_python.txt |
Q:
Translate Exif DMS to DD Geolocation with Python
I am using the following code to extract the geolocation of an image taken with an iPhone:
from PIL import Image
from PIL.ExifTags import TAGS
def get_exif(fn):
ret = {}
i = Image.open(fn)
info = i._getexif()
for tag, value in info.items():
... | Translate Exif DMS to DD Geolocation with Python | I am using the following code to extract the geolocation of an image taken with an iPhone:
from PIL import Image
from PIL.ExifTags import TAGS
def get_exif(fn):
ret = {}
i = Image.open(fn)
info = i._getexif()
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
ret[decoded] = va... | [
"Here's a way to do it, adapted for a script I wrote some months ago using pyexiv2:\na = get_exif('photo2.jpg')\nlat = [float(x)/float(y) for x, y in a['GPSInfo'][2]]\nlatref = a['GPSInfo'][1]\nlon = [float(x)/float(y) for x, y in a['GPSInfo'][4]]\nlonref = a['GPSInfo'][3]\n\nlat = lat[0] + lat[1]/60 + lat[2]/3600\... | [
10,
1
] | [] | [] | [
"exif",
"geo",
"python",
"python_imaging_library"
] | stackoverflow_0006460381_exif_geo_python_python_imaging_library.txt |
Q:
what's the best way to modify django form at runtime?
The code I use is:
class VoteForm(forms.ModelForm):
other_choice1 = forms.BooleanField(required=False)
other_choice2 = forms.BooleanField(required=False)
other_choice3 = forms.BooleanField(required=False)
other_choice4 = forms.BooleanField(requi... | what's the best way to modify django form at runtime? | The code I use is:
class VoteForm(forms.ModelForm):
other_choice1 = forms.BooleanField(required=False)
other_choice2 = forms.BooleanField(required=False)
other_choice3 = forms.BooleanField(required=False)
other_choice4 = forms.BooleanField(required=False)
class Meta:
model = Vote
ex... | [
"Use base_fields as explained in Monkey patching a Django form class? :\nContactForm.another_field = forms.CharField(...)\nContactForm.base_fields['another_field'] = ContactForm.another_field\n\n(Or BaseForm as explained here http://snipt.net/danfreak/how-to-generate-a-dynamic-at-runtime-form-in-django/ :\ndef make... | [
4,
1
] | [] | [] | [
"django",
"django_forms",
"dynamic",
"python"
] | stackoverflow_0006459007_django_django_forms_dynamic_python.txt |
Q:
Delete numbers from a file
I have a file of the form
00040 void FormExample::setLanguage(const std::string lang)
00041 {
00042 bool haveLang = false;
00043
I want to remove the numbers from the file so that it can compile.
I tried using
sed -e 's/^(\d)*//g' test.cpp but was not successful. Please tell me ... | Delete numbers from a file | I have a file of the form
00040 void FormExample::setLanguage(const std::string lang)
00041 {
00042 bool haveLang = false;
00043
I want to remove the numbers from the file so that it can compile.
I tried using
sed -e 's/^(\d)*//g' test.cpp but was not successful. Please tell me what was I doing wrong.
It can ... | [
"This works: \nsed -e 's/^[0-9]*//' test.cpp\n\nsed's regex flavor is a bit different than Perl's. You don't have this \"shorthand\" character classes ( e.g. \\d or \\w) and grouping is done by \\( \\). The parenthesis in your expression match literally.\n",
"sed -r 's/^[[:digit:]]*//g'\n\nshould do it\n",
"In... | [
4,
1,
0
] | [] | [] | [
"awk",
"python",
"regex",
"scripting",
"sed"
] | stackoverflow_0006464850_awk_python_regex_scripting_sed.txt |
Q:
What is an easy way to create a trivial one-off Python object?
I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:
options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERB... | What is an easy way to create a trivial one-off Python object? | I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:
options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
Of course I could use a dictionary, but options.VERBOS... | [
"The collections module has grown a namedtuple function in 2.6:\nimport collections\nopt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')\nmyoptions=opt(True, False)\n\n>>> myoptions\noptions(VERBOSE=True, IGNORE_WARNINGS=False)\n>>> myoptions.VERBOSE\nTrue\n\nA namedtuple is immutable, so you can only a... | [
15,
9,
8,
7,
5,
4,
3,
2,
1,
1
] | [
"simple object and named tuples are the way to go\n"
] | [
-2
] | [
"python"
] | stackoverflow_0000211695_python.txt |
Q:
Where does Python look for library binaries?
I'm trying to bundle a Python library (fontforge) together so that my script runs on a machine without that library installed (but with Python installed). So far I tried copying ".so" files corresponding to "Missing library" errors to current directory, and while it wor... | Where does Python look for library binaries? | I'm trying to bundle a Python library (fontforge) together so that my script runs on a machine without that library installed (but with Python installed). So far I tried copying ".so" files corresponding to "Missing library" errors to current directory, and while it worked for some, it didn't work for others, I'm getti... | [
"Assuming you're on Linux, the OS looks for shared objects in the directories listed in /etc/ld.so.conf, /etc/ld.so.conf.d/* and $LD_LIBRARY_PATH.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0006465053_python.txt |
Q:
Compare two glob expressions
Does anyone know an algorithm to check which of two wild card expression is more general than the other?
For example I'd like to compare
*/foo/foo.bar
with
*.bar
Clearly the first expression is contained in the second. I know that is not possible for regex (at least not if you do... | Compare two glob expressions | Does anyone know an algorithm to check which of two wild card expression is more general than the other?
For example I'd like to compare
*/foo/foo.bar
with
*.bar
Clearly the first expression is contained in the second. I know that is not possible for regex (at least not if you don't have a looooot of time, as far... | [
"You basically need to find a string somehow that matches the more general glob but not the more specific one. Just being captain obvious...\nProbably by replacing * character with 0 or more random symbols.\n"
] | [
0
] | [] | [] | [
"compare",
"expression",
"glob",
"python",
"wildcard"
] | stackoverflow_0006465322_compare_expression_glob_python_wildcard.txt |
Q:
Read integer from binary file in Python
I have the following snippet of C code:
#include <stdio.h>
void main(){
int a = 1308901095;
FILE *fp;
fp = fopen("file", "wb");
fwrite(&a, sizeof(int), 1, fp);
fclose(fp);
printf("Done\n");
}
This will write the "a" integer in file "file", in binary form.
How I... | Read integer from binary file in Python | I have the following snippet of C code:
#include <stdio.h>
void main(){
int a = 1308901095;
FILE *fp;
fp = fopen("file", "wb");
fwrite(&a, sizeof(int), 1, fp);
fclose(fp);
printf("Done\n");
}
This will write the "a" integer in file "file", in binary form.
How I can read this number in Python?
| [
"Try following.\nfrom struct import *\nf = open('file', 'rb')\nprint unpack('<i', f.read(4))[0]\nf.close()\n\nnote that using '<' about your machine is little endian or not.\n"
] | [
3
] | [] | [] | [
"binaryfiles",
"c",
"python"
] | stackoverflow_0006465425_binaryfiles_c_python.txt |
Q:
Paster daemon won't shut down because can't read own pid file
TL;DR version: When I ask Paster to stop-daemon, it fails to read its own file that it uses to track its process id.
Longer version:
I am running Paster (pastescript 1.7.3) on Python 2.7.1 on Windows Vista.
My first surprise comes from running a simple ... | Paster daemon won't shut down because can't read own pid file | TL;DR version: When I ask Paster to stop-daemon, it fails to read its own file that it uses to track its process id.
Longer version:
I am running Paster (pastescript 1.7.3) on Python 2.7.1 on Windows Vista.
My first surprise comes from running a simple web-site:
>paster serve development.ini
Starting server in PID 1518... | [
"From paste script's source code(serve.py), in the PID reading method:\npid = read_pidfile(pidfile)\nif pid:\n try:\n os.kill(int(pid), 0)\n return pid\n except OSError, e:\n if e.errno == errno.EPERM:\n return pid\nreturn None\n\nOn POSIX-compatible platforms, specifying 0 as ... | [
2
] | [] | [] | [
"daemon",
"paster",
"python",
"windows"
] | stackoverflow_0006463388_daemon_paster_python_windows.txt |
Q:
What's the standard way of doing this sort in Python?
Imagine I have a list of tuples in this format:
(1, 2, 3)
(1, 0, 2)
(3, 9 , 11)
(0, 2, 8)
(2, 3, 4)
(2, 4, 5)
(2, 7, 8)
....
How could I sort the list by the first element of the tuples, and then by the second? I'd like to get to this list:
(0, 2, 8)
(1, 0, 2)... | What's the standard way of doing this sort in Python? | Imagine I have a list of tuples in this format:
(1, 2, 3)
(1, 0, 2)
(3, 9 , 11)
(0, 2, 8)
(2, 3, 4)
(2, 4, 5)
(2, 7, 8)
....
How could I sort the list by the first element of the tuples, and then by the second? I'd like to get to this list:
(0, 2, 8)
(1, 0, 2)
(1, 2, 3)
(2, 3, 4)
(2, 4, 5)
(2, 7, 8)
(3, 9 , 11)
I was... | [
"Why not simply let python sort the list for you ?\nmy_list = [\n(1, 2, 3),\n(1, 0, 2),\n(3, 9 , 11),\n(0, 2, 8),\n(2, 3, 4),\n(2, 4, 5),\n(2, 7, 8),\n]\n\nprint sorted(my_list)\n>>>[(0, 2, 8), (1, 0, 2), (1, 2, 3), (2, 3, 4), (2, 4, 5), (2, 7, 8), (3, 9, 11)]\n\n",
"Python automagically does the right thing:\n>>... | [
8,
3,
1,
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0006464524_python_sorting.txt |
Q:
Migrate Python Dict to Java and JSON
I was a decent programmer in Python. Now i am forced to do a Wowza Module for my chat application. An application which will login by facebook account and the status of each user is saved on a Wowza Server, which use java for app development, connected via flash client & RTMP. ... | Migrate Python Dict to Java and JSON | I was a decent programmer in Python. Now i am forced to do a Wowza Module for my chat application. An application which will login by facebook account and the status of each user is saved on a Wowza Server, which use java for app development, connected via flash client & RTMP. The online status datastructure will be li... | [
"I assume that by store and retrieve, you mean cache it in memory, so:\n(1) Create javabean classes to encapsulate the data. A java HashMap is very similar to a python dictionary. Why don't you try to write the classes in java as if they were python, update your question with the result, and then people can help yo... | [
1,
0,
0
] | [] | [] | [
"java",
"json",
"migration",
"python"
] | stackoverflow_0006439458_java_json_migration_python.txt |
Q:
piston-django how many methods should a single handler contain
I've been building a handler class for each method I want to map to the url file. Is my approach correct or wrong? because I don't seem to find a way to map a resource to a method they all map to an entire class.
Regards,
A:
The documentations seem... | piston-django how many methods should a single handler contain | I've been building a handler class for each method I want to map to the url file. Is my approach correct or wrong? because I don't seem to find a way to map a resource to a method they all map to an entire class.
Regards,
| [
"The documentations seems very clear https://bitbucket.org/jespern/django-piston/wiki/Documentation#!resources\nfrom piston.handler import BaseHandler\nfrom myapp.models import Blogpost\n\nclass BlogpostHandler(BaseHandler):\n allowed_methods = ('GET',)\n model = Blogpost \n\n def read(self, request, post_s... | [
0
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0006465900_django_django_piston_python.txt |
Q:
Validating a slug in Django
I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to £$(*£$(£@$&£($ in the title field, which is converted into a slug using Django slugify.
Because none of these characters can be c... | Validating a slug in Django | I'm guessing this is going to involve regexp or something, but I'll give it a shot. At the minute, a user can break a website by typing something similar to £$(*£$(£@$&£($ in the title field, which is converted into a slug using Django slugify.
Because none of these characters can be converted, Django returns an error... | [
"This question is half a decade old so in updating my question I should explain that I'm at least nodding to the past where some features might not have existed.\nThe easiest way to handle slugs in forms these days is to just use django.models.SlugField. It will validate itself for you and imply that this field is ... | [
19,
12
] | [] | [] | [
"django",
"python",
"slug",
"validation"
] | stackoverflow_0000941270_django_python_slug_validation.txt |
Q:
How to implement a Required Property in Python
If I have a class such as below (only with many more properties), is there are clean way to note which fields are required before calling a particular method?
class Example():
def __init__(self):
pass
@property
"""Have to use property methods to ... | How to implement a Required Property in Python | If I have a class such as below (only with many more properties), is there are clean way to note which fields are required before calling a particular method?
class Example():
def __init__(self):
pass
@property
"""Have to use property methods to have docstrings..."""
def prop1(self):
r... | [
"Would it not be best to make sure that all the attributes are supplied when an object is initialised? Then all your properties will be defined when you try to acces them.\nFor example,\nclass Example(object):\n def __init__(self, prop1, prop2):\n self.prop1 = prop1\n self.prop2 = prop2\n\nAlso, no... | [
8,
7,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006465686_python.txt |
Q:
Assigning random value to a parameter in a python program
I need to assign a default random value in __init__(). For example:
import math
import random
class Test:
def __init__(self, r = random.randrange(0, math.pow(2,128)-1)):
self.r = r
print self.r
If I create 10 instances of Test, they all... | Assigning random value to a parameter in a python program | I need to assign a default random value in __init__(). For example:
import math
import random
class Test:
def __init__(self, r = random.randrange(0, math.pow(2,128)-1)):
self.r = r
print self.r
If I create 10 instances of Test, they all get the exact same random value. I don't understand why this i... | [
"The value of the default parameter is being set at the time the function is created, not when it is called - that's why it's the same every time.\nThe typical way to deal with this is to set the default parameter to None and test it with an if statement.\nimport math\nimport random\nclass Test:\n def __init__(... | [
19,
5,
1,
1
] | [] | [] | [
"init",
"parameters",
"python",
"random"
] | stackoverflow_0006462784_init_parameters_python_random.txt |
Q:
How to write to a file in a particular position using python?
i want to replace a dictionary value by mapping the key in the python file.how can it be done,someone help me,i am new in this field.sorry my english..
A:
I'm not quite sure I understand your question, but I'll try to help.
To save an object to file ... | How to write to a file in a particular position using python? | i want to replace a dictionary value by mapping the key in the python file.how can it be done,someone help me,i am new in this field.sorry my english..
| [
"I'm not quite sure I understand your question, but I'll try to help.\nTo save an object to file from Python you can use a process called Pickle.\nWhat you would do is write your object to the file and then if you would like to change it, you can unpickle, change the value, and repickle.\nimport pickle\n\n# Write o... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006466828_python.txt |
Q:
Image lists in (Py)Qt
I wanna implement some king of Image List (like this one) with drag-n-drop option (when element is dragged out of list and dropped somewhere, it is not removed from the list and when item is dropped into the list, it is added to the bottom of the list). This list should not have its images 'i... | Image lists in (Py)Qt | I wanna implement some king of Image List (like this one) with drag-n-drop option (when element is dragged out of list and dropped somewhere, it is not removed from the list and when item is dropped into the list, it is added to the bottom of the list). This list should not have its images 'iconified' (like QListWidget... | [
"Use the constructor of QListWidgetItem that takes an icon to insert items with icon into your list. i.e\nQListWidget list = new QListWidget ();\nQListWidgetItem item =new QListWidgetItem(QIcon(\"C:\\\\My.PNG\"),\"Winter\",list);\n\nThen use these methos with your lists\nlist1->setDragEnabled(true);\nlist2->setAcc... | [
1
] | [] | [] | [
"listview",
"pyqt",
"python",
"qt",
"user_interface"
] | stackoverflow_0006466989_listview_pyqt_python_qt_user_interface.txt |
Q:
Java main-class in python-syntax
this is an example Java Class with a main method.
public class MyMainClass{
public static void main(){
doThings();
}
}
To start it i have to do a "javac" on it and then a "java" on its output.
I've been experimenting quite a bit with python lately, but i couldn't f... | Java main-class in python-syntax | this is an example Java Class with a main method.
public class MyMainClass{
public static void main(){
doThings();
}
}
To start it i have to do a "javac" on it and then a "java" on its output.
I've been experimenting quite a bit with python lately, but i couldn't figure out how to structure my py-docum... | [
"Why not...\nclass MyClass:\n def method(self):\n print(\"in main\")\n\nif __name__ == \"__main__\":\n MyClass().method()\n\nThat's the closest thing to Java that you'll get here.\n",
"It seems OK to me:\nPython 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) \n[GCC 4.5.2] on linux2\nType \"help\", \"copy... | [
3,
2,
0
] | [] | [] | [
"class_design",
"comparison",
"java",
"python"
] | stackoverflow_0006467148_class_design_comparison_java_python.txt |
Q:
Handle server error python
I m workin on an api where the user enters a domain and i need to redirect to the login page of that domain.
So this works for only google domains and i need to handle the error created when user enters non google domain . I m workin on google app engine.
I m new to dis error handling.So... | Handle server error python | I m workin on an api where the user enters a domain and i need to redirect to the login page of that domain.
So this works for only google domains and i need to handle the error created when user enters non google domain . I m workin on google app engine.
I m new to dis error handling.So kindly explain how it works alo... | [
"The easiest solution will be probably to try to validate the user input before you use it. A simple regular expression which checks the last parts of the domain the user has entered might be enough.\nIf you want to support arbitrary domains without a google\\.[a-z]+ or appspot.com suffix you will need another way ... | [
1,
0
] | [] | [] | [
"api",
"error_handling",
"python"
] | stackoverflow_0006466790_api_error_handling_python.txt |
Q:
Generic methods in python
Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
A:
The... | Generic methods in python | Is it possible to implement generic method handlers in python which allow for calling of non-existent functions? Something like this:
class FooBar:
def __generic__method__handler__(.., methodName, ..):
print methodName
fb = FooBar()
fb.helloThere()
-- output --
helloThere
| [
"The first thing to remember is that methods are attributes which happen to be callable.\n>>> s = \" hello \"\n>>> s.strip()\n'hello'\n>>> s.strip\n<built-in method strip of str object at 0x000000000223B9E0>\n\nSo you can handle non-existent methods in the same way you would handle non-existent attributes.\nThis is... | [
15,
6,
4
] | [] | [] | [
"python"
] | stackoverflow_0006467461_python.txt |
Q:
Getting values from the database as list
I have the Model:
class TreeComment(models.Model):
parent = models.ForeignKey('self', null=True, blank=True, verbose_name='Parent')
title = models.TextField(_('Title'), blank=True)
I want to call TreeComment.objects.all() and put result values into some list:
for e ... | Getting values from the database as list | I have the Model:
class TreeComment(models.Model):
parent = models.ForeignKey('self', null=True, blank=True, verbose_name='Parent')
title = models.TextField(_('Title'), blank=True)
I want to call TreeComment.objects.all() and put result values into some list:
for e in TreeComment.objects.all():
some_list +=... | [
"If you are looking to pull the query back as a list try\nTreeComment.objects.values_list()\n\nwhich would return [(1, u'some title'), ...] 1 being parent id and u'some title' being title's value\nvalues_list docs\n",
"I'm thinking 2 solutions\n1) You create a method get_parent(self) inside TreeComment class. The... | [
2,
0
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0006467663_django_orm_python.txt |
Q:
How to calculate the average of only one column in a series of file with python?
I have a series of file( with format shown in below) with different names such as:
100107_902988_6188DAAXX_s_6.sorted
100107_902988_6188DAAXX_s_7.sorted
(if you notice only the part 6 and 7 are different in the file name)
I would lik... | How to calculate the average of only one column in a series of file with python? | I have a series of file( with format shown in below) with different names such as:
100107_902988_6188DAAXX_s_6.sorted
100107_902988_6188DAAXX_s_7.sorted
(if you notice only the part 6 and 7 are different in the file name)
I would like to have the average of the last column with numbers (column number 8 the one which s... | [
"Not tested, but something like this should do the trick:\nimport glob\n\ndef avg(lst):\n return float(sum(lst))/len(lst)\n\nall_numbers = []\nfor filename in glob.glob(\"100107_902988_6188DAAXX_s_*.sorted\"):\n numbers = []\n with open(filename, \"r\") as file:\n for line in file:\n numb... | [
1
] | [] | [] | [
"average",
"python",
"series"
] | stackoverflow_0006468104_average_python_series.txt |
Q:
Numpy array from cStringIO object and avoiding copies
This to understand things better. It is not an actual problem that I need to fix. A cstringIO object is supposed to emulate a string, file and also an iterator over the lines. Does it also emulate a buffer ? In anycase ideally one should be able to construct a ... | Numpy array from cStringIO object and avoiding copies | This to understand things better. It is not an actual problem that I need to fix. A cstringIO object is supposed to emulate a string, file and also an iterator over the lines. Does it also emulate a buffer ? In anycase ideally one should be able to construct a numpy array as follows
import numpy as np
import cstringIO
... | [
"The problem seems to be that numpy doesn't like being given characters instead of numbers. Remember, in Python, single characters and strings have the same type — numpy must have some type detection going on under the hood, and takes '\\x01' to be a nested sequence.\nThe other problem is that a cStringIO iterates ... | [
3,
2
] | [] | [] | [
"numpy",
"python",
"stringio"
] | stackoverflow_0006464353_numpy_python_stringio.txt |
Q:
Python: Adding dictionary values to form new tuple-keyed dictionary
If I have a dictionary as follows (with some lists):
units = ['a','b']
nums = ['1','2']
ratios = ['alpha', 'beta']
d = {'a_1_alpha':4, 'a_1_beta' :1, 'a_2_alpha' :2, 'a_2_beta': 3, 'b_1_alpha':2}
How do i from a new dictionary which:
forms a ke... | Python: Adding dictionary values to form new tuple-keyed dictionary | If I have a dictionary as follows (with some lists):
units = ['a','b']
nums = ['1','2']
ratios = ['alpha', 'beta']
d = {'a_1_alpha':4, 'a_1_beta' :1, 'a_2_alpha' :2, 'a_2_beta': 3, 'b_1_alpha':2}
How do i from a new dictionary which:
forms a key comprising of tuple (num,ratio) #items from list nums & ratios
the valu... | [
"The two outer loops are redundant, simply iterate over the key-value pairs of d. You can easily extract the three components of a key using split(). Here's the code:\nnew_d = {}\nfor k, v in d.items():\n u, n, r = k.split('_')\n new_d[(n, r)] = v + new_d.get((n, r), 0)\n\n",
"This should solve your problem... | [
6,
2,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006468249_dictionary_python.txt |
Q:
how to trim file - for rows which with the same value in two columns, conserve only the row with max in another columns
I am now facing a file trimming problem. I would like to trim rows in a tab-delimited file.
The rule is: for rows which with the same value in two columns, preserve only the row with the largest... | how to trim file - for rows which with the same value in two columns, conserve only the row with max in another columns | I am now facing a file trimming problem. I would like to trim rows in a tab-delimited file.
The rule is: for rows which with the same value in two columns, preserve only the row with the largest value in the third column. There may be different numbers of such redundant rows defined by two columns. If there is a tie f... | [
"Here's a solution that will rely on the input file already being sorted appropriately. It will scan line-by-line for lines with similar start (e.g. two first columns identical), check the third column value and preserve the line with the highest value - or the line that came first in the file. When a new start is ... | [
2,
1,
1,
1
] | [] | [] | [
"awk",
"perl",
"python",
"unix"
] | stackoverflow_0006466315_awk_perl_python_unix.txt |
Q:
Sort a pandas DataMatrix in ascending order
The pandas DataFrame object has a sort method but pandas DataMatrix object does not.
What is the best way to sort this DataMatrix object by index (the date column) in ascending order?
>>> dm
compound_ret
2/16/2011 0:00 0.006275682
2/15/2011 0:00 0.003098... | Sort a pandas DataMatrix in ascending order | The pandas DataFrame object has a sort method but pandas DataMatrix object does not.
What is the best way to sort this DataMatrix object by index (the date column) in ascending order?
>>> dm
compound_ret
2/16/2011 0:00 0.006275682
2/15/2011 0:00 0.003098208
2/14/2011 0:00 0.0055039
2/13/2011 0:00 0.0... | [
"Indeed between 0.2 and 0.3 I renamed sortUp/sortDown to the single sort methods. Sorry about that.\nI definitely recommend keeping up on the bleeding edge of pandas if you can ( https://github.com/wesm/pandas )! Also, consider using IPython for all your interactive work ( http://ipython.scipy.org )-- I find that h... | [
8,
0
] | [] | [] | [
"numpy",
"pandas",
"python",
"sorting"
] | stackoverflow_0005558607_numpy_pandas_python_sorting.txt |
Q:
Convert a unicode input to string for comparison
i am writing code which parses a word document table and compares to a keyword which is an ascii string
tyring = unicode((ListTables[0].Rows[x])).encode('utf-8')
tryingstring = tyring.encode('ascii')
print 'trying string' ,tryingstring
ERROR BELOW:
tyring = unicode... | Convert a unicode input to string for comparison | i am writing code which parses a word document table and compares to a keyword which is an ascii string
tyring = unicode((ListTables[0].Rows[x])).encode('utf-8')
tryingstring = tyring.encode('ascii')
print 'trying string' ,tryingstring
ERROR BELOW:
tyring = unicode((ListTables[0].Rows[x])).encode('utf-8','ignore')
Fil... | [
"Going back to your original posting:\nif tr1_find.search(str(ListTables[0].Cell(x,y))):\n print 'Found'\n value = ListTables[0].Cell(x,y+1)\n\nListTables[0].Cell(x,y) returns a Cell instance from the Word document. Calling str() on it retrieves its Unicode value and tries to encode it to a byte string usin... | [
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006458367_python.txt |
Q:
WxPython changing the shape of bitmap button
Hi I'm sort new to wxPython and still in the process of learning. I'm trying to make a bitmap button using a particular image like this for example: http://i.min.us/idk3Uy.png
The catch is I want to retain the original shape of the image in the button, like a circular b... | WxPython changing the shape of bitmap button | Hi I'm sort new to wxPython and still in the process of learning. I'm trying to make a bitmap button using a particular image like this for example: http://i.min.us/idk3Uy.png
The catch is I want to retain the original shape of the image in the button, like a circular button for example instead of a rectangular one (wh... | [
"You're probably going to have to implement a custom control for this. I've done my fair share of custom wxPython controls, so I went ahead and wrote a ShapedButton class for you. =)\nTo run this demo, you just need three images:\n\nbutton-normal.png\nbutton-pressed.png\nbutton-disabled.png\n\nThe three images are ... | [
15
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0006449709_python_wxpython.txt |
Q:
Debugging sample Pygame code?
A simple question: Why does this the first code work but the seemingly identical second code freezes up when the pygame window comes?
# Moving Pan
# Demonstrates mouse input
from livewires import games
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Pan(games.Sp... | Debugging sample Pygame code? | A simple question: Why does this the first code work but the seemingly identical second code freezes up when the pygame window comes?
# Moving Pan
# Demonstrates mouse input
from livewires import games
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Pan(games.Sprite):
""" A pan controlled by ... | [
"I have never worked with livewires, but in games you usually need a - more or less - endless game-loop.\nThe sense behind a game-loop is, that you always want to know where the mouse is or what keys are pressed, not only once! So you have to ask Where is the mouse? over and over. And to achieve that, you use a loo... | [
2
] | [] | [] | [
"debugging",
"livewires",
"pygame",
"python",
"sample"
] | stackoverflow_0006468605_debugging_livewires_pygame_python_sample.txt |
Q:
passing list of strings to map_async()
I'm having a funny issue with map_async that i can't figure out.
I'm using python's multiprocessing library with process pools. I'm trying to pass a list of strings to compare against and a list of strings to be compared to a function using map_async()
right now i have:
from ... | passing list of strings to map_async() | I'm having a funny issue with map_async that i can't figure out.
I'm using python's multiprocessing library with process pools. I'm trying to pass a list of strings to compare against and a list of strings to be compared to a function using map_async()
right now i have:
from multiprocessing import Pool, cpu_count
impor... | [
"Ok, i actually figured this one out myself. I'm only going to post the answer here for anyone else who might come along and have the same issue. The reason i was having problems was because map_async takes one item from the list (in this case a string), and feeds it into the function, which was expecting a list of... | [
3
] | [] | [] | [
"multiprocessing",
"python",
"python_3.x"
] | stackoverflow_0006446568_multiprocessing_python_python_3.x.txt |
Q:
Check if the user is typing in numeric numbers. Don't want letters
I would like to know the easiest way to check it the user typing in a letter versus a number. If the user types in a letter it would give them an error message and give them the question back. Right now I have it so when the user enters a 'q' it wi... | Check if the user is typing in numeric numbers. Don't want letters | I would like to know the easiest way to check it the user typing in a letter versus a number. If the user types in a letter it would give them an error message and give them the question back. Right now I have it so when the user enters a 'q' it will exit the script.
if station == "q":
break
else:
#curs... | [
"Just using python built-in method \nstr.isdigit()\n\nSEE http://docs.python.org/library/stdtypes.html \ne.g.\nif station.isdigit():\n print 'Thank you for checking into station: ', station\nelse:\n # show your error information here\n pass\n\n",
"Try this (using YeJiabin's answer)\ndef answer():\n statio... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006469114_python.txt |
Q:
Tkinter Checkbutton doesn't change my variable
I'm trying to use a Checkbutton with a function, my_var never changes but it always call my function.
here the code:
my_var = False
def controllo_carta():
global my_var
print str(my_var)
[...]
c = tk.Checkbutton(toolbar, text="press me",onvalue=True,offvalue... | Tkinter Checkbutton doesn't change my variable | I'm trying to use a Checkbutton with a function, my_var never changes but it always call my function.
here the code:
my_var = False
def controllo_carta():
global my_var
print str(my_var)
[...]
c = tk.Checkbutton(toolbar, text="press me",onvalue=True,offvalue=False,variable=my_var,command=controllo_carta)
c.se... | [
"To make your code work I would use BooleanVar() and the associated get() method to retrieve its value (http://effbot.org/tkinterbook/variable.htm)\nFor example: (from: http://effbot.org/tkinterbook/checkbutton.htm)\nfrom Tkinter import *\n\nmaster = Tk()\n\nvar = BooleanVar()\n\ndef cb():\n print \"variable is ... | [
9
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006469254_python_tkinter.txt |
Q:
Python multithreading
I have this scenario:
A web page created with Zope/Plone and some mine python API. There's a web page, call it "a", that by a python method calls a database (Postgres) and returns some information. On page "a" you can modify database data "offline" (I intend that the changes aren't written in... | Python multithreading | I have this scenario:
A web page created with Zope/Plone and some mine python API. There's a web page, call it "a", that by a python method calls a database (Postgres) and returns some information. On page "a" you can modify database data "offline" (I intend that the changes aren't written in the database instantly but... | [
"The realm of problem you're discussing is generally called, \"Concurrency\". Since your method would warn or block the user from updating when any field in the target item changes, the approach is usually called \"Pessimistic Concurrency\". One way to do this is to keep track of what the item looked like when it w... | [
3
] | [] | [] | [
"ajax",
"multithreading",
"python",
"zope"
] | stackoverflow_0006469462_ajax_multithreading_python_zope.txt |
Q:
Python kill hanging function
I'm sure this has been asked before, but I can't find a similar example. I need to be able to call a function with an execution time-limit. If the function takes over this time, then the whole script exits.
This can't be done by timing the whole script! And I only want one, small fun... | Python kill hanging function | I'm sure this has been asked before, but I can't find a similar example. I need to be able to call a function with an execution time-limit. If the function takes over this time, then the whole script exits.
This can't be done by timing the whole script! And I only want one, small function to be timed. Is it possible... | [
"Here's a recipe (unix only) http://code.activestate.com/recipes/534115-function-timeout/\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006468904_python.txt |
Q:
mounting fuse gives invalid argument error in python
I have written python code to a mount fuse on a point mount. It always gives invalid argument error. I have tried the same program in C and it works fine. Can any of python Guru's help me out in finding what the problem is, I have pasted the code here.
#!/usr/bi... | mounting fuse gives invalid argument error in python | I have written python code to a mount fuse on a point mount. It always gives invalid argument error. I have tried the same program in C and it works fine. Can any of python Guru's help me out in finding what the problem is, I have pasted the code here.
#!/usr/bin/python
import stat
import os
import ctypes
from ctypes.... | [
"ctypes.c_void_p cannot be initialized with a string. Instead, just use a string without c_void_p.\nYou can then compare the output of\nstrace -v -e mount python mymount.py\n\nand\nstrace -v -e mount ./mymount-c\n\nuntil they match.\nAlso, make sure the file handle fd is still open when you call mount. file(\"/dev/... | [
2
] | [] | [] | [
"fuse",
"python"
] | stackoverflow_0006469557_fuse_python.txt |
Q:
Introduction on implementations of CPython types
I'm interested in a high level introduction on the implementations of CPython types, e.g., list, str, dict, etc., and their computational complexity. I only found this article which gives an intro on the list type.
http://www.laurentluce.com/?p=271
A:
There's a ni... | Introduction on implementations of CPython types | I'm interested in a high level introduction on the implementations of CPython types, e.g., list, str, dict, etc., and their computational complexity. I only found this article which gives an intro on the list type.
http://www.laurentluce.com/?p=271
| [
"There's a nice table on the python wiki listing the time complexity for a bunch of python types. Furthermore, Laurent Luce blog also describes the implementation of python's list and dict types.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006470105_python.txt |
Q:
QThread/Signal Logic
I'm trying to write a notifier for a forum. I'm trying to use a QThread with a QTimer for checking for new replies periodically. But, my check() function in my thread don't run in thread, it blocks the GUI. Can you say what is wrong with that?
I am suspecting of signals, I'm using the QTimer's... | QThread/Signal Logic | I'm trying to write a notifier for a forum. I'm trying to use a QThread with a QTimer for checking for new replies periodically. But, my check() function in my thread don't run in thread, it blocks the GUI. Can you say what is wrong with that?
I am suspecting of signals, I'm using the QTimer's timeout signal for runnin... | [
"It looks like the main problem is that you're calling time.sleep(). I don't see where time is defined, but if that's the normal time module for python that will make the python interpreter pause which I expect is the cause of the problem.\nSince you don't want to mix python threads and qt threads, I'd recommend th... | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0006468981_pyqt_python.txt |
Q:
Grok and MySQL - how to set a connection?
According to this doc: http://grok.zope.org/documentation/how-to/grok-orm-with-storm when i want connect to database (sqlite) i should set something like thIS: with correct path TO MY DB.
How to set a connection with mysql?
A:
you can add the connection string like thi... | Grok and MySQL - how to set a connection? | According to this doc: http://grok.zope.org/documentation/how-to/grok-orm-with-storm when i want connect to database (sqlite) i should set something like thIS: with correct path TO MY DB.
How to set a connection with mysql?
| [
"you can add the connection string like this:\n\nFor more information take a look here:\nhttps://storm.canonical.com/Tutorial#Creating a database and the store\nHTH Christian\n"
] | [
1
] | [] | [] | [
"grok",
"python"
] | stackoverflow_0006242450_grok_python.txt |
Q:
Python instancemethods & decorators
I've got the following problem:
I need to write a decorator that would be able to detect a situation where it is used around a method and around a regular function.
So let's consider the following code:
def somedecorator(fn):
print "decorating function:", fn
print "funct... | Python instancemethods & decorators | I've got the following problem:
I need to write a decorator that would be able to detect a situation where it is used around a method and around a regular function.
So let's consider the following code:
def somedecorator(fn):
print "decorating function:", fn
print "function class:", fn.__class__
return fn
... | [
"May be looking at the stack?\ndef somedecorator(fn):\n import traceback\n print \"decorating function:\", fn\n print \"function class:\", fn.__class__\n print traceback.extract_stack()[-2][2]\n return fn\n\nIf the decorator has been called from a module outputs 'module' and from the method outputs '... | [
2,
1
] | [] | [] | [
"decorator",
"function",
"metaprogramming",
"methods",
"python"
] | stackoverflow_0006470457_decorator_function_metaprogramming_methods_python.txt |
Q:
Django using i18n in URL patterns
I have a app in django, which I need to implement i18n, should be easy in django. but my problem here is, I cannot use the HttpSession to store the user language! so my solution is, I got add to all URL the language as parameter! is there any easy why to do it?! or some API for dj... | Django using i18n in URL patterns | I have a app in django, which I need to implement i18n, should be easy in django. but my problem here is, I cannot use the HttpSession to store the user language! so my solution is, I got add to all URL the language as parameter! is there any easy why to do it?! or some API for django?!
I saw this however it is just av... | [
"Try using transurlvania, I've just used it in 2 of my websites over past two few weeks and it seems very nice to work with and is quite similar to what docs say is in trunk now, so my guess is it will be easy to move to 1.4 in the future.\nIt supports, quote:\n\nLanguage-in-Path - a replacement for\n Django's lan... | [
2
] | [] | [] | [
"django",
"internationalization",
"python"
] | stackoverflow_0006470722_django_internationalization_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.