content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Why is IronPython faster than the Official Python Interpreter
According to this:
http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think co... | Why is IronPython faster than the Official Python Interpreter | According to this:
http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance
IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI byteco... | [
"Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.\n",
"You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dicti... | [
41,
9,
5,
5,
4
] | [] | [] | [
"ironpython",
"performance",
"python"
] | stackoverflow_0000504716_ironpython_performance_python.txt |
Q:
Quick primer on implementing a COM object that implement some custom IDLs in python?
Does anyone have experience using python to create a COM object that implements some custom IDLs?
Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?
A:
The tu... | Quick primer on implementing a COM object that implement some custom IDLs in python? | Does anyone have experience using python to create a COM object that implements some custom IDLs?
Basically I'd like to know if it's extremely simple to do compared to c++, and if it is do you know of a good tutorial?
| [
"The tutorial you are looking for is in the Python Programming On Win32 book, by Mark Hammond and Andy Robinson. A bit old, and the COM object creation info is distributed across some chapters.\nA more recent example, simple COM server using Python, can give you a quick start.\n",
"There is also comtypes, which a... | [
3,
2,
1
] | [] | [] | [
"com",
"python"
] | stackoverflow_0000550450_com_python.txt |
Q:
Using Beautiful Soup, how do I iterate over all embedded text?
Let's say I wanted to remove vowels from HTML:
<a href="foo">Hello there!</a>Hi!
becomes
<a href="foo">Hll thr!</a>H!
I figure this is a job for Beautiful Soup. How can I select the text in between tags and operate on it like this?
A:
Suppose the v... | Using Beautiful Soup, how do I iterate over all embedded text? | Let's say I wanted to remove vowels from HTML:
<a href="foo">Hello there!</a>Hi!
becomes
<a href="foo">Hll thr!</a>H!
I figure this is a job for Beautiful Soup. How can I select the text in between tags and operate on it like this?
| [
"Suppose the variable test_html has the following html content:\n<html>\n<head><title>Test title</title></head>\n<body>\n<p>Some paragraph</p>\nUseless Text\n<a href=\"http://stackoverflow.com\">Some link</a>not a link\n<a href=\"http://python.org\">Another link</a>\n</body></html>\n\nJust do this:\nfrom BeautifulS... | [
11
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0000830997_beautifulsoup_python.txt |
Q:
A production ready server to serve django on win32
I'd like to serve django application on windows XP/Vista.
The application is an at hoc web interface to a windows program so it won't be put under heavy load (around 100 requests per second).
Do you know any small servers that can be easily deployed on windows to ... | A production ready server to serve django on win32 | I'd like to serve django application on windows XP/Vista.
The application is an at hoc web interface to a windows program so it won't be put under heavy load (around 100 requests per second).
Do you know any small servers that can be easily deployed on windows to serve a django app? (IIS is not an option as the app sho... | [
"cherrypy includes a good server. Here's how you set it up to work with django and some benchmarks.\ntwisted.web has wsgi support and that could be used to run your django application. Here's how you do it.\nIn fact any wsgi server will do. Here's one more example, this time using spawning:\n$ spawn --factory=spawn... | [
5,
1,
0
] | [] | [] | [
"django",
"python",
"windows"
] | stackoverflow_0000831288_django_python_windows.txt |
Q:
How do you create an anonymous Python telnet connection?
I am trying to telnet into a server using Python on Windows XP. I can connect successfully by typing 'telnet HOST PORT' which creates an anonymous connection. But Python's telnetlib.Telnet(HOST, PORT) returns 'Connection refused'. Telnetting in Java also ... | How do you create an anonymous Python telnet connection? | I am trying to telnet into a server using Python on Windows XP. I can connect successfully by typing 'telnet HOST PORT' which creates an anonymous connection. But Python's telnetlib.Telnet(HOST, PORT) returns 'Connection refused'. Telnetting in Java also fails. Spelunking shows that Python tries to create an anonym... | [
"It would be a good idea to trace both connection attempts (a failing case and a successful case) with wireshark or similar packet trace tool to see what the difference is at the protocol level.\n",
"First, eliminate telnetlib as your problem: import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n... | [
1,
1
] | [] | [] | [
"java",
"python",
"telnet",
"windows"
] | stackoverflow_0000831679_java_python_telnet_windows.txt |
Q:
Python imaging, resize Turtle Graphics window
My image is too large for the turtle window. I had to enlarge the image because the text I need at each spot overlaps.
How do I Resize the window in python?
A:
It sounds like you have drawn an image, but it has gone outside the borders of the window, so therefore y... | Python imaging, resize Turtle Graphics window | My image is too large for the turtle window. I had to enlarge the image because the text I need at each spot overlaps.
How do I Resize the window in python?
| [
"It sounds like you have drawn an image, but it has gone outside the borders of the window, so therefore you need to make the window larger to see the entire image. \nTo resize the window:\n\nsetup( width = 200, height = 200, startx = None, starty = None) \n\nThis will make your output window 200X200 (which may be ... | [
6
] | [] | [] | [
"python",
"turtle_graphics"
] | stackoverflow_0000831894_python_turtle_graphics.txt |
Q:
Python: Finding all packages inside a package
Given a package, how can I automatically find all its sub-packages?
A:
You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, ... | Python: Finding all packages inside a package | Given a package, how can I automatically find all its sub-packages?
| [
"You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, zip file, extension module, or loaded from memory.\ndef get_subpackages(module):\n dir = os.path.dirname(module.__fi... | [
10,
0
] | [] | [] | [
"import",
"package",
"python"
] | stackoverflow_0000832004_import_package_python.txt |
Q:
Django template with jquery: Ajax update on existing page
I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I inten... | Django template with jquery: Ajax update on existing page | I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:
<html>
<head>
<titl... | [
"Without being able to test the code, what are your results? Have you checked the results returned by the AJAX call? I would suggest you run Firefox with Firebug and log the AJAX results to the Firebug console to see what you get:\n//...\n success: function( result ) { \n console.log( result );\n ... | [
2,
1
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"jquery",
"python"
] | stackoverflow_0000209023_django_django_templates_google_app_engine_jquery_python.txt |
Q:
How to set up Python in a web server?
Not exactly about programming, but I need help with this.
I'm running a development sever with WampServer. I want to install Python (because I prefer to use Python over PHP), but it seems there isn't an obvious choice. I've read about mod_python and WSGI, and about how the lat... | How to set up Python in a web server? | Not exactly about programming, but I need help with this.
I'm running a development sever with WampServer. I want to install Python (because I prefer to use Python over PHP), but it seems there isn't an obvious choice. I've read about mod_python and WSGI, and about how the latter is better.
However, from what I gathere... | [
"Django is not a web server, but a web application framework.\nIf you want a bare-bones Python webserver capable of some dynamic and some static content, have a look at CherryPy.\n",
"Use mod_wsgi to embed Python in Apache. It works very, very well.\n\"However, from what I gathered (I may be wrong) you have to d... | [
5,
3,
2,
0,
0
] | [] | [] | [
"django",
"python",
"windows"
] | stackoverflow_0000832140_django_python_windows.txt |
Q:
How to run a script without being in the tasktray?
I have a scheduled task which runs a python script every 10 min
so it turns out that a script pops up on my desktop every 10 min
how can i make it invincible so my script will work in the background ?
I've been told that pythonw will do the work, but I cant figure... | How to run a script without being in the tasktray? | I have a scheduled task which runs a python script every 10 min
so it turns out that a script pops up on my desktop every 10 min
how can i make it invincible so my script will work in the background ?
I've been told that pythonw will do the work, but I cant figure out how to use it
any help ?
thanks
| [
"\nI've been told that pythonw will do the work, but I cant figure out how to use it\n\nNormally you just have to rename the file extension to .pyw. Then it will be executed by pythonw.\n",
"Set the scheduled task to start the script as minimized.\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0000833356_python.txt |
Q:
Need help for developing facebook app
I am trying to develop a facebook app using django.
The problem I am facing is how to use facebook api and get user friend list.
view.py
def canvas(request):
# Get the User object
user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)
return... | Need help for developing facebook app | I am trying to develop a facebook app using django.
The problem I am facing is how to use facebook api and get user friend list.
view.py
def canvas(request):
# Get the User object
user, created = FacebookUser.objects.get_or_create(id = request.facebook.uid)
return direct_to_template(request, 'canvas.fbml',... | [
"Try using single quotes when loading up the userID etc. \nFailing that it would appear to be either of the following\n- Output error from python. The HTML / FBML output should be as follows\n\nDouble check the attributes you are adding are correct. Case sensitive. \nAre you loading you the correct authentication ... | [
0
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0000833406_django_facebook_python.txt |
Q:
What i need to install python 2.5 on SCO 5.0.5
I would love to install python2.5 on sco unix, and am wondering anybody who has attempted to do this?
A:
Did you already try the standard source instructions, and fail? If so, I guess it would be useful to mention what failed. This is almost a non-programming questi... | What i need to install python 2.5 on SCO 5.0.5 | I would love to install python2.5 on sco unix, and am wondering anybody who has attempted to do this?
| [
"Did you already try the standard source instructions, and fail? If so, I guess it would be useful to mention what failed. This is almost a non-programming question, as it's phrased now ...\n"
] | [
2
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0000833624_python_unix.txt |
Q:
design for handling exceptions - google app engine
I'm developing a project on google app engine (webapp framework). I need you people to assess how I handle exceptions.
There are 4 types of exceptions I am handling:
Programming exceptions
Bad user input
Incorrect URLs
Incorrect query strings
Here is how I handl... | design for handling exceptions - google app engine | I'm developing a project on google app engine (webapp framework). I need you people to assess how I handle exceptions.
There are 4 types of exceptions I am handling:
Programming exceptions
Bad user input
Incorrect URLs
Incorrect query strings
Here is how I handle them:
I have subclassed the webapp.requesthandler cla... | [
"You seem to have thought things through pretty well. The only thing I would add is that you might want to take a look at Bloog as an example. Bloog is a pretty well written and popular open source blog engine for App Engine written in Python.\nAlso, on Point #2, watch out for these types of Cross Scripting attacks... | [
5,
0
] | [] | [] | [
"exception_handling",
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0000830597_exception_handling_google_app_engine_python_web_applications.txt |
Q:
Scaffold or django-admin without Auth app
I created my own Auth app, and now Admin is not working, what can you suggest?
Exception now is: 'User' object has no attribute 'is_authenticated'
I know my User really have no such method. So I have 2 ways:
- change admin
- adapt my user system
My question was: is th... | Scaffold or django-admin without Auth app | I created my own Auth app, and now Admin is not working, what can you suggest?
Exception now is: 'User' object has no attribute 'is_authenticated'
I know my User really have no such method. So I have 2 ways:
- change admin
- adapt my user system
My question was: is there possibility to easily off admin bound to au... | [
"See the file django/contrib/admin/views/decorators.py:\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login\n\nThese are used in decorator staff_member_required which guards access to admin application.\nAdmin application requires django.contrib.auth - you might try to ... | [
2
] | [] | [] | [
"django",
"django_admin",
"python",
"scaffolding"
] | stackoverflow_0000831934_django_django_admin_python_scaffolding.txt |
Q:
Returning http status codes in Python CGI
Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
A:
via cgi script?
print "Status:301\nLocation: http://www.google.com"
A:
Via wsgi application?
def simple_app(environ, start_response):
status = '301 Moved Permanent... | Returning http status codes in Python CGI | Is it possible to send a status code other than 200 via a python cgi script (such as 301 redirect)
| [
"via cgi script?\nprint \"Status:301\\nLocation: http://www.google.com\"\n\n",
"Via wsgi application?\ndef simple_app(environ, start_response):\n status = '301 Moved Permanently' # HTTP Status\n headers = [('Location','http://example.com')] # HTTP Headers\n start_response(status, headers)\n\n return [... | [
23,
0
] | [] | [] | [
"cgi",
"http",
"python"
] | stackoverflow_0000833715_cgi_http_python.txt |
Q:
Mapping a database table to an attribute of an object
I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems... | Mapping a database table to an attribute of an object | I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems the most flexible solution that I can tailor to my needs. ... | [
"It seems you want something like\nwork_instance.variants = [<some iterable of variants>]\n\nIf not please clarify in your question.\nIdeally you should have 2 mappings to these 2 tables. It doesn't matter if you won't access the second mapping anywhere else. work mapping should have a one-to-many relationship to v... | [
1
] | [] | [] | [
"database",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0000834722_database_orm_python_sqlalchemy.txt |
Q:
How to make Satchmo work in Google App Engine
I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?
Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.
Plus, if t... | How to make Satchmo work in Google App Engine | I understand that there are big differences in data-store, but surely since django is bundled and it abstracts data-store away from Satchmo, something can be done?
Truth is that I am not a Python guy, been mostly Java/PHP thus far, but I am willing to learn.
Plus, if this is not possible today, lets band together and f... | [
"You can't. There are alot of dependencies in Satchmo that you aren't allowed to install on AppEngine.\nSee this thread as well: http://groups.google.com/group/satchmo-users/browse_thread/thread/509265ccd5f5fc1e?pli=1\n",
"Possible if:\n\nSomeone writes a generic ORM to Bigtable mapper. Most probably, Appengine P... | [
3,
3,
2
] | [] | [] | [
"e_commerce",
"google_app_engine",
"python",
"satchmo"
] | stackoverflow_0000600225_e_commerce_google_app_engine_python_satchmo.txt |
Q:
Can I use a List Comprehension to get Line Indexes from a file?
I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which wa... | Can I use a List Comprehension to get Line Indexes from a file? | I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was
count=0
docIndex=[]
for line in open('myfile.txt','r'):
if 'mys... | [
"What about this?\n[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]\n\n"
] | [
8
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0000835572_list_comprehension_python.txt |
Q:
why might my pyglet vertex lists and batches be very slow on Windows?
I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex... | why might my pyglet vertex lists and batches be very slow on Windows? | I'm writing opengl code in python using the library pyglet. When I draw to the screen using pyglet.graphics.vertex_list or pyglet.graphics.batch objects, they are very slow (~0.1 fps) compared to plain old pyglet.graphics.draw() or just glVertex() calls, which are about 40fps for the same geometry.
In Linux the vertex_... | [
"Don't forget to invoke your pyglet scripts with 'python -O myscript.py', the '-O' flag can make a huge performance difference.\nSee pyglet docs here and here.\n",
"I don't know personally, but I noticed that you haven't posted to the pyglet mailing list about this. More Pyglet users, as well as the primary devel... | [
5,
1
] | [] | [] | [
"opengl",
"pyglet",
"python"
] | stackoverflow_0000067223_opengl_pyglet_python.txt |
Q:
Extending Python's builtin Str
I'm trying to subclass str, but having some difficulties due to its immutability.
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ... | Extending Python's builtin Str | I'm trying to subclass str, but having some difficulties due to its immutability.
class DerivedClass(str):
def __new__(cls, string):
ob = super(DerivedClass, cls).__new__(cls, string)
return ob
def upper(self):
#overridden, new functionality. Return ob of type DerivedClass. Great.
... | [
"Good use for a class decorator -- roughly (untested code):\n@do_overrides\nclass Myst(str):\n def upper(self):\n ...&c...\n\nand\ndef do_overrides(cls):\n done = set(dir(cls))\n base = cls.__bases__[0]\n def wrap(f):\n def wrapper(*a, **k):\n r = f(*a, **k)\n if isinstance(r, base):\n r ... | [
7,
5,
5
] | [
"You might be able to do this by overriding __getattribute__.\ndef __getattribute__(self, name):\n # Simple hardcoded check for upper.\n # I'm sure there are better ways to get the list of defined methods in\n # your class and see if name is contained in it.\n if name == 'upper':\n return object.... | [
-2
] | [
"immutability",
"inheritance",
"oop",
"overriding",
"python"
] | stackoverflow_0000835469_immutability_inheritance_oop_overriding_python.txt |
Q:
PDF Tables of Arbitrary (within reason) Width
I know PDF generation has been discussed a lot here; however, I've yet to find what I need.
I'm trying to generate PDF reports (mainly tables) from python. Yes I've tried ReportLab and Pisa. Both had column content "break out" in circumstances I didn't think were unr... | PDF Tables of Arbitrary (within reason) Width | I know PDF generation has been discussed a lot here; however, I've yet to find what I need.
I'm trying to generate PDF reports (mainly tables) from python. Yes I've tried ReportLab and Pisa. Both had column content "break out" in circumstances I didn't think were unreasonable and unrealistic to encounter in productio... | [
"I completely agree with Brandon Craig Rhodes answer.\nTeX, plain or with a macro package like LaTeX or ConTeXt, would be a good solution if \nyou need high quality output. However TeX is a heavy dependency\nIf you are looking for a lighter alternative you can try to\n\ngenerate xsl-fo and render it with apache-fop... | [
3,
2,
1
] | [] | [] | [
"latex",
"pdf",
"python",
"xhtml"
] | stackoverflow_0000832693_latex_pdf_python_xhtml.txt |
Q:
Form Submission in Python Without Name Attribute
Background:
Using urllib and urllib2 in Python, you can do a form submission.
You first create a dictionary.
formdictionary = { 'search' : 'stackoverflow' }
Then you use urlencode method of urllib to transform this dictionary.
params = urllib.urlencode(formdictio... | Form Submission in Python Without Name Attribute | Background:
Using urllib and urllib2 in Python, you can do a form submission.
You first create a dictionary.
formdictionary = { 'search' : 'stackoverflow' }
Then you use urlencode method of urllib to transform this dictionary.
params = urllib.urlencode(formdictionary)
You can now make a url request with urllib2 and... | [
"According to the W3 standard, for an input field to be submitted, it must have a name attribute. A quick test on Firefox 3 and Safari 3.2 shows that an input field that is missing the name attribute but has an id attribute is not submitted.\nWith that said, if you have a form that you want to submit, and some of i... | [
2,
0
] | [] | [] | [
"forms",
"python",
"urllib",
"urllib2"
] | stackoverflow_0000837195_forms_python_urllib_urllib2.txt |
Q:
Python style iterators in C
The "yield" statement in python allows simple iteration from a procedure, and it also means that sequences don't need to be pre-calculated AND stored in a array of "arbitrary" size.
Is there a there a similar way of iterating (with yield) from a C procedure?
A:
Here follows a communit... | Python style iterators in C | The "yield" statement in python allows simple iteration from a procedure, and it also means that sequences don't need to be pre-calculated AND stored in a array of "arbitrary" size.
Is there a there a similar way of iterating (with yield) from a C procedure?
| [
"Here follows a community-wiki copy of the self-answer, which can be chosen as \"the\" answer. Please direct up/downvotes to the actual self-answer\nHere is the method I found:\n /* Example calculates the sum of the prime factors of the first 32 Fibonacci numbers */\n#include <stdio.h>\n\ntypedef enum{false=0, t... | [
6,
3,
0
] | [] | [] | [
"algol68",
"c",
"iterator",
"jit",
"python"
] | stackoverflow_0000833063_algol68_c_iterator_jit_python.txt |
Q:
Python cgi and stdin
I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:
while True:
next = sys.stdin.read(4096)
if not next:
break
#.... write the buffer
This seems to work with text, but not binary f... | Python cgi and stdin | I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:
while True:
next = sys.stdin.read(4096)
if not next:
break
#.... write the buffer
This seems to work with text, but not binary files (I'm on windows).
Wit... | [
"You need to run Python in binary mode. Change your CGI script from:\n#!C:/Python25/python.exe\n\nor whatever it says to:\n#!C:/Python25/python.exe -u\n\nOr you can do it programmatically like this:\nmsvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)\n\nbefore starting to read from stdin.\n",
"Use mod_wsgi instead ... | [
3,
0
] | [] | [] | [
"cgi",
"python",
"stdin"
] | stackoverflow_0000838991_cgi_python_stdin.txt |
Q:
Popen log management question
Problem:
I have a monitor program in Python that uses subprocess' Popen to start new processes. These processes have the potential to run for a very long time (weeks-months). I'm passing a file handle to stdout variable in Popen and I'm worried that this file will get huge easily. ... | Popen log management question | Problem:
I have a monitor program in Python that uses subprocess' Popen to start new processes. These processes have the potential to run for a very long time (weeks-months). I'm passing a file handle to stdout variable in Popen and I'm worried that this file will get huge easily. Is there a way I can safely move or... | [
"Fix the monitor program so that it is responsible for rotating its own logs, or mediate the data coming from the log program yourself and package it out into separate files.\nThose are the two options you have. You can't mess with another process' file descriptors once it's running, so no, you can't \"move or rem... | [
1
] | [] | [] | [
"logging",
"popen",
"python"
] | stackoverflow_0000840531_logging_popen_python.txt |
Q:
authentication method
I am writing a server-client application to receive user message and publish it.
Thinking about authentication method.
Asymmetric encryption, probably RSA.
Hash (salt+password+'msg'+'userid'), SHA256
HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password... | authentication method | I am writing a server-client application to receive user message and publish it.
Thinking about authentication method.
Asymmetric encryption, probably RSA.
Hash (salt+password+'msg'+'userid'), SHA256
HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.
Symmetric En... | [
"Can't you just use standard SSL sockets to secure the connection, validate the user with a password, and then send the message to be published? If there won't be many clients, you can even use a self-signed certificate and put it in a KeyStore in the client app, that way you won't need to buy a certificate from Ve... | [
2,
1,
1,
0
] | [] | [] | [
"authentication",
"encryption",
"hash",
"java",
"python"
] | stackoverflow_0000834932_authentication_encryption_hash_java_python.txt |
Q:
Sort lexicographically?
I am working on integrating with the Photobucket API and I came across this in their api docs:
"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."
... | Sort lexicographically? | I am working on integrating with the Photobucket API and I came across this in their api docs:
"Sort the parameters by name
lexographically [sic] (byte ordering, the
standard sorting, not natural or case
insensitive). If the parameters have
the same name, then sort by the value."
What does that mean? How do I... | [
"I think that here lexicographic is a \"alias\" for ascii sort?\n\nLexicographic Natural \nz1.doc z1.doc \nz10.doc z2.doc \nz100.doc z3.doc \nz101.doc z4.doc \nz102.doc z5.doc \nz11.doc z6.doc \... | [
8,
6,
4,
1
] | [] | [] | [
"api",
"photobucket",
"python",
"sorting"
] | stackoverflow_0000840637_api_photobucket_python_sorting.txt |
Q:
mod_python publisher and pretty URLs
I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:
I have a file /foo.py with functions index() and bar(), so, with the publisher I can access http://domain/foo/bar and http://domain/foo... | mod_python publisher and pretty URLs | I am new to Python (I am getting out of PHP because of how increasingly broken it is), and I am racing through porting my old code. One thing:
I have a file /foo.py with functions index() and bar(), so, with the publisher I can access http://domain/foo/bar and http://domain/foo as the documentation suggests.
How can I ... | [
"You would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the publisher handler replaces the slashes in the URL with dots, and tries to find some Python object with that name.\nYou would have to have an object bar.a1.a2.a3.an defined within your foo.py module. Basically, the pu... | [
1,
1
] | [] | [] | [
"friendly_url",
"mod_python",
"python",
"url"
] | stackoverflow_0000841068_friendly_url_mod_python_python_url.txt |
Q:
wxPython: Drawing inside a ScrolledPanel
I'm using a PaintDC to draw inside a ScrolledPanel. However, when I run the program, the scroll bars have no effect. They're the right size, but the picture doesn't move when you scroll with them.
I figured I may have to convert from logical to device coordinates. I tried x... | wxPython: Drawing inside a ScrolledPanel | I'm using a PaintDC to draw inside a ScrolledPanel. However, when I run the program, the scroll bars have no effect. They're the right size, but the picture doesn't move when you scroll with them.
I figured I may have to convert from logical to device coordinates. I tried x=dc.LogicalToDeviceX(x) and y=dc.LogicalToDevi... | [
"Got it:\n(new_x,new_y)=self.CalcScrolledPosition((old_x,old_y))\n\nWhere self is the ScrolledPanel.\n"
] | [
1
] | [] | [] | [
"python",
"scroll",
"wxpython"
] | stackoverflow_0000841425_python_scroll_wxpython.txt |
Q:
WinXP button-style with wxPython
I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.
How to make buttons look like current Windows buttons style?
A:
Are you packaging the app with py2exe?
If so you may need to spec... | WinXP button-style with wxPython | I noticed that my programs written with wxPython have Win98 button style.
But Boa Constructor (that is written using wxPython too) got pretty buttons.
How to make buttons look like current Windows buttons style?
| [
"Are you packaging the app with py2exe?\nIf so you may need to specify a manifest file to make Python use the WinXP(Vista?) theme/Common Controls:\nhttp://wiki.wxpython.org/DistributingYourApplication\n",
"Expanding on John's answer, you may also be able to create manifest files for python.exe and pythonw.exe to ... | [
3,
1,
0
] | [
"Have you tried running your scripts with pythonw.exe instead of python.exe?\n"
] | [
-2
] | [
"coding_style",
"python",
"wxpython"
] | stackoverflow_0000642853_coding_style_python_wxpython.txt |
Q:
How to use subversion Ctypes Python Bindings?
Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.... | How to use subversion Ctypes Python Bindings? | Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly... | [
"You need the Subversion source distribution, Python (>= 2.5), and ctypesgen.\nInstructions for building the ctypes bindings are here.\nYou will end up with a package called csvn, examples of it's use are here.\n",
"The whole point of ctypes is that you shouldn't need to have to compile anything anywhere. That sa... | [
1,
0
] | [
"I looked into the python binding for subversion, but in the end I found it to be simpler to just invoke svn.exe like this:\n(stdout, stderr, err) = execute('svn export \"%s\" \"%s\"' \\\n % (exportURL, workingCopyFolder))\n\nwhere execute is a function like this:\ndef execute(cmd):\n import subprocess\n pr... | [
-1
] | [
"python",
"svn"
] | stackoverflow_0000815530_python_svn.txt |
Q:
Python: ODBC Exception Handling
I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?
>>>cursor.execute("delete from TABLE")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.inte... | Python: ODBC Exception Handling | I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?
>>>cursor.execute("delete from TABLE")
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
dbi.internal-error: [IBM][CLI Driver][DB2] SQ... | [
"From the Python documentation:\n\nA try statement may have more than one except clause, to specify handlers for different exceptions.\n\nFor example:\ntry:\n do_something_crazy\nexcept AttributeError:\n print 'there was an AttributeError'\nexcept NameError:\n print 'there was a NameError'\nexcept:\nprint ... | [
1
] | [] | [] | [
"odbc",
"python"
] | stackoverflow_0000841968_odbc_python.txt |
Q:
Piping Batch File output to a Python script
I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like... | Piping Batch File output to a Python script | I'm trying to write a python script (in windows) that runs a batch file and will take the command line output of that batch file as input. The batch file runs processes that I don't have access to and gives output based on whether those processes are successful. I'd like to take those messages from the batch file and u... | [
"import subprocess\n\noutput= subprocess.Popen(\n (\"c:\\\\bin\\\\batch.bat\", \"an_argument\", \"another_argument\"),\n stdout=subprocess.PIPE).stdout\n\nfor line in output:\n # do your work here\n\noutput.close()\n\nNote that it's preferable to start your batch file with \"@echo off\".\n",
"Here is a s... | [
9,
2,
1
] | [] | [] | [
"batch_file",
"io",
"python",
"scripting",
"windows"
] | stackoverflow_0000842120_batch_file_io_python_scripting_windows.txt |
Q:
What are some good ways to set a path in a Multi-OS supported Python script
When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the ... | What are some good ways to set a path in a Multi-OS supported Python script | When writing a Python script that can be executed in different operating system environments (Windows/*nix), what are some good ways to set a path? In the example below I would like to have the logfiles stored in the logs folder under the current directory. Is this an acceptable approach (I'm rather new to Python) or a... | [
"Definitely have a look at os.path. It contains many of the \"safe\" cross-OS path manipulation functions you need. For example, I've always done this in the scenario you're outlining:\nos.path.join(os.path.abspath(os.path.dirname(__file__)), 'logs')\n\nAlso note that if you want to get the path separator, you ca... | [
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0000842570_python.txt |
Q:
find in files using ruby or python
A popular text editor has the following "find in files" feature that opens in a dialog box:
Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
I... | find in files using ruby or python | A popular text editor has the following "find in files" feature that opens in a dialog box:
Look For: __searchtext__
File Filter: *.txt; *.htm
Start From: c:/docs/2009
Report: [ ] Filenames [ ]FileCount only
Method: [ ] Regex [ ]Plain Text
In fact, several popular text editors hav... | [
"I know you said you don't feel like writing it yourself, but for what it's worth, it would be very easy using os.walk - you could do something like this:\nresults = []\nif regex_search:\n p = re.compile(__searchtext__)\nfor dir, subdirs, subfiles in os.walk('c:/docs/2009'):\n for name in fnmatch.filter(subfi... | [
5,
3
] | [] | [] | [
"file",
"grep",
"python",
"ruby",
"search"
] | stackoverflow_0000842598_file_grep_python_ruby_search.txt |
Q:
Django equivalent of COUNT with GROUP BY
I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:
SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
A:
If you... | Django equivalent of COUNT with GROUP BY | I know Django 1.1 has some new aggregation methods. However I couldn't figure out equivalent of the following query:
SELECT player_type, COUNT(*) FROM players GROUP BY player_type;
Is it possible with Django 1.1's Model Query API or should I just use plain SQL?
| [
"If you are using Django 1.1 beta (trunk):\nPlayer.objects.values('player_type').order_by().annotate(Count('player_type'))\n\n\nvalues('player_type') - for inclusion only player_type field into GROUP BY clause.\norder_by() - for exclusion possible default ordering that can cause not needed fields inclusion in SELEC... | [
65,
16
] | [] | [] | [
"django",
"django_aggregation",
"django_queryset",
"python",
"sql"
] | stackoverflow_0000842031_django_django_aggregation_django_queryset_python_sql.txt |
Q:
How can I use Django admin list and filterering in my own views?
I’m just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?
I’ve looked in the source for the admin and figured o... | How can I use Django admin list and filterering in my own views? | I’m just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?
I’ve looked in the source for the admin and figured out that I probably want to subclass the “ChangeList”-object in some wa... | [
"You're better off doing the following.\n\nDefine a regular old Django query for your various kinds of filters. These are very easy to write.\nUse the supplied generic view functions. These are very easy to use.\nCreate your own templates with links to your filters. You'll be building a list links based on the r... | [
1
] | [] | [] | [
"django",
"django_queryset",
"django_views",
"filter",
"python"
] | stackoverflow_0000843182_django_django_queryset_django_views_filter_python.txt |
Q:
Pygame cannot find include file "sdl.h"
I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)
This is the me... | Pygame cannot find include file "sdl.h" | I am trying to build a downloaded Python app on Windows that uses Pygame. I have installed Python 2.5 and Pygame 1.7.1. I am new to Python, but I just tried typing the name of the top level .py file on a Windows console command line. (I'm using Win XP Pro.)
This is the message that I get.
C:\Python25\include\pygame\... | [
"I tried compiling and got the same errors on my linux box:\n$ python setup.py build\nDBG> include = ['/usr/include', '/usr/include/python2.6', '/usr/include/SDL']\nrunning build\nrunning build_ext\nbuilding 'surfutils' extension\ncreating build\ncreating build/temp.linux-i686-2.6\ncreating build/temp.linux-i686-2.... | [
5,
2
] | [] | [] | [
"pygame",
"python",
"sdl"
] | stackoverflow_0000841654_pygame_python_sdl.txt |
Q:
How to render contents of a tag in unicode in BeautifulSoup?
This is a soup from a WordPress post detail page:
content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
I want to omit the enc... | How to render contents of a tag in unicode in BeautifulSoup? | This is a soup from a WordPress post detail page:
content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
I want to omit the enclosing div tag when assigning item['content']. Is there any way to... | [
"Have you tried:\nunicode(content)\n\nIt converts content's markup to a single Unicode string.\nEdit: If you don't want the enclosing tag, try:\ncontent.renderContents()\n\n"
] | [
6
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping",
"web_applications",
"xml"
] | stackoverflow_0000843227_beautifulsoup_python_screen_scraping_web_applications_xml.txt |
Q:
Computing the second (mis-match) table in the Boyer-Moore String Search Algorithm
For the Boyer-Moore algorithm to be worst-case linear, the computation of the mis-match table must be O(m). However, a naive implementation would loop through all suffixs O(m) and all positions in that that suffix could go and check ... | Computing the second (mis-match) table in the Boyer-Moore String Search Algorithm | For the Boyer-Moore algorithm to be worst-case linear, the computation of the mis-match table must be O(m). However, a naive implementation would loop through all suffixs O(m) and all positions in that that suffix could go and check for equality... which is O(m3)!
Below is the naive implementation of table building alg... | [
"The code under \"Preprocessing for the good-suffix heuristics\" on this page builds the good-suffix table in O(n) time. It also explains how the code works.\n"
] | [
1
] | [] | [] | [
"algorithm",
"discrete_mathematics",
"python",
"string_search"
] | stackoverflow_0000840974_algorithm_discrete_mathematics_python_string_search.txt |
Q:
How does garbage collection in Python work with class methods?
class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?
A:
The vari... | How does garbage collection in Python work with class methods? | class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?
| [
"The variable is never deallocated.\nThe object (in this case a string, with a value of 'some string' is reused again and again, so that object can never be deallocated.\nObjects are deallocated when no variable refers to the object. Think of this.\na = 'hi mom'\na = 'next value'\n\nIn this case, the first object ... | [
7,
5,
3,
0
] | [] | [] | [
"garbage_collection",
"python"
] | stackoverflow_0000843459_garbage_collection_python.txt |
Q:
call function between time intervals
In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now.
ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_op... | call function between time intervals | In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now.
ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, min... | [
"This is more compact, but not so obvious:\nif '09:55' <= time.strftime(\n '%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':\n check_for_updates()\n\nDepending on how important it is for you to do the calculations absolutely properly, you may want to consider daylight saving time (use pytz fo... | [
1,
0
] | [] | [] | [
"datetime",
"python",
"time",
"timezone"
] | stackoverflow_0000843614_datetime_python_time_timezone.txt |
Q:
python: can I extend the upper bound of the range() method?
What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
A:
range(1, 600851475143) wants to generate a very large list in memory, and you'll get an out of mem... | python: can I extend the upper bound of the range() method? | What is the upper bound of the range() function and how can I extend it, or alternately what's the best way to do this:
for i in range(1,600851475143):
| [
"range(1, 600851475143) wants to generate a very large list in memory, and you'll get an out of memory error. To save memory, use xrange instead of range. Unfortunately, xrange doesn't work with large numbers (it's an implementation restriction) Example (raises OverflowError):\nfor i in xrange(1, 600851475143):\n ... | [
10,
2,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000841584_python.txt |
Q:
FastCgi crashes -- Want to catch all exceptions but how?
I have a django app running on apache with fastcgi (uses Flup's WSGIServer).
This gets setup via dispatch.fcgi, concatenated below:
#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.envir... | FastCgi crashes -- Want to catch all exceptions but how? | I have a django app running on apache with fastcgi (uses Flup's WSGIServer).
This gets setup via dispatch.fcgi, concatenated below:
#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.environ['PROJECT_PATH']
sys.path.insert(0, PROJECT_PATH)
os.chdir... | [
"This is probably a Flup bug. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.\nTrying to catch the exception by a try catch around runfastcgi will not work. Simply because the exception is raised by a thread.\nOK, I'll... | [
3,
0
] | [] | [] | [
"django",
"fastcgi",
"flup",
"python",
"wsgi"
] | stackoverflow_0000843753_django_fastcgi_flup_python_wsgi.txt |
Q:
What's the most efficient way to find one of several substrings in Python?
I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice, the list contains hundreds of entries.
I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substring... | What's the most efficient way to find one of several substrings in Python? | I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice, the list contains hundreds of entries.
I'm processing a string, and what I'm looking for is to find the index of the first appearance of any of these substrings.
To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result ... | [
"I would assume a regex is better than checking for each substring individually because conceptually the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).\nSo, here is an example:\nimport re\n\ndef w... | [
36,
4,
3,
2,
0,
0
] | [] | [] | [
"python",
"regex",
"string",
"substring"
] | stackoverflow_0000842856_python_regex_string_substring.txt |
Q:
Python regex question: stripping multi-line comments but maintaining a line break
I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /..../). However, if the multi-line comment has at least one line-break in it (\n), I want the output to h... | Python regex question: stripping multi-line comments but maintaining a line break | I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /..../). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.
For example, the code:
qwe /* 123
456
789 */ asd
... | [
"comment_re = re.compile(\n r'(^)?[^\\S\\n]*/(?:\\*(.*?)\\*/[^\\S\\n]*|/[^\\n]*)($)?',\n re.DOTALL | re.MULTILINE\n)\n\ndef comment_replacer(match):\n start,mid,end = match.group(1,2,3)\n if mid is None:\n # single line comment\n return ''\n elif start is not None or end is not None:\n ... | [
12,
5,
1,
1,
0
] | [] | [] | [
"comments",
"parsing",
"python",
"regex"
] | stackoverflow_0000844681_comments_parsing_python_regex.txt |
Q:
where to put method that works on a model
I'm working with Django.
I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.
like obj.get_current_side(username)
I've added this to the actual Argument model like th... | where to put method that works on a model | I'm working with Django.
I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.
like obj.get_current_side(username)
I've added this to the actual Argument model like this
def get_current_side(self, user):
r... | [
"It would make more sense to have instance methods on the User model:\ndef get_current_side(self):\n try:\n return self.arguments.latest('pub_date').side\n except User.DoesNotExist, e:\n return None\n\nYou can do this by extending the User model as explained here:\n\nExtending the Django User mo... | [
2,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000844142_django_python.txt |
Q:
"x Days ago' template filter in Django?
I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?
A:
Have a look at the timesince template filter. It's builtin.
The following returns a humanized diff betwee... | "x Days ago' template filter in Django? | I'm looking for a filter that turns a datetime instance into 'x Days' or 'x years y months' format (as on SO). Suggestions? Am I overlooking something very obvious?
| [
"Have a look at the timesince template filter. It's builtin.\nThe following returns a humanized diff between now and comment_date (e.g. '8 hours'):\n{{ comment_date|timesince }}\n\nThe following returns a humanized diff between question_date and comment_date:\n{{ comment_date|timesince:question_date }}\n\n"
] | [
34
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000845009_django_python.txt |
Q:
VIM: Use python 2.5 with vim 7.2
How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4
Do I have to compile from source?
A:
Here is a link to VIM 7.2 builds with Python 2.5/2.6 support.
| VIM: Use python 2.5 with vim 7.2 | How can use Python2.5 with to write scripts in vim? I'm using vim 7.2 and have Python 2.5. Vim 7.2 seem to be linked with Python 2.4
Do I have to compile from source?
| [
"Here is a link to VIM 7.2 builds with Python 2.5/2.6 support.\n"
] | [
3
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0000845068_python_vim.txt |
Q:
Converting a java System.currentTimeMillis() to date in python
I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.
How should I do that ?
The following give ValueError: timestamp out of range for platfor... | Converting a java System.currentTimeMillis() to date in python | I have timestamp in milliseconds from 1970. I would like to convert it to a human readable date in python. I don't might losing some precision if it comes to that.
How should I do that ?
The following give ValueError: timestamp out of range for platform time_t on Linux 32bit
#!/usr/bin/env python
from datetime import d... | [
"Python expects seconds, so divide it by 1000.0 first:\n>>> print date.fromtimestamp(1241711346274/1000.0)\n2009-05-07\n\n",
"You can preserve the precision, because in Python the timestamp is a float. Here's an example:\nimport datetime\n\njava_timestamp = 1241959948938\nseconds = java_timestamp / 1000\nsub_seco... | [
17,
4,
1
] | [] | [] | [
"date",
"formatting",
"java",
"python",
"timestamp"
] | stackoverflow_0000845153_date_formatting_java_python_timestamp.txt |
Q:
Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on
It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open an... | Canonical/Idiomatic "do what I mean" when passed a string that could a filename, URL, or the actual data to work on | It's not uncommon to see Python libraries that expose a universal "opener" function, that accept as their primary argument a string that could either represent a local filename (which it will open and operate on), a URL(which it will download and operate on), or data(which it will operate on).
Here's an example from Fe... | [
"Ultimately, any module implementing this behaviour is going to parse the string. And act according to the result. In feedparser for example they are parsing the url:\nif urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):\n # do something with the url\nelse:\n # This is a file path\n... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0000845408_python.txt |
Q:
How to print the comparison of two multiline strings in unified diff format?
Do you know any library that will help doing that?
I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:
def print_differences(string1, string2):
"""
Pr... | How to print the comparison of two multiline strings in unified diff format? | Do you know any library that will help doing that?
I would write a function that prints the differences between two multiline strings in the unified diff format. Something like that:
def print_differences(string1, string2):
"""
Prints the comparison of string1 to string2 as unified diff format.
"""
???
... | [
"This is how I solved:\ndef _unidiff_output(expected, actual):\n \"\"\"\n Helper function. Returns a string containing the unified diff of two multiline strings.\n \"\"\"\n\n import difflib\n expected=expected.splitlines(1)\n actual=actual.splitlines(1)\n\n diff=difflib.unified_diff(expected, a... | [
29,
25
] | [] | [] | [
"diff",
"python",
"unified_diff"
] | stackoverflow_0000845276_diff_python_unified_diff.txt |
Q:
using Python objects in C#
Is there an easy way to call Python objects from C#, that is without any COM mess?
A:
Yes, by hosting IronPython.
A:
In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its ha... | using Python objects in C# | Is there an easy way to call Python objects from C#, that is without any COM mess?
| [
"Yes, by hosting IronPython.\n",
"In the current released version of C# there is no great way to achieve this without using some sort of bridge layer. You can host it IronPython to a degree but its hard to take advantage of the dynamic features of IronPython since C# is a very statically typed language\nIf you'r... | [
8,
6,
5
] | [] | [] | [
"c#",
"ironpython",
"python"
] | stackoverflow_0000845502_c#_ironpython_python.txt |
Q:
How do I choose which Python installation to run in a PyObjC program?
I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it inst... | How do I choose which Python installation to run in a PyObjC program? | I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?
| [
"Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework.\n",
"Try specifying the full path to the Python interpreter in the command line, something like:\n/foo/bar/python2.6 script.... | [
3,
2,
2
] | [] | [] | [
"macos",
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0000843698_macos_objective_c_pyobjc_python.txt |
Q:
Get the amplitude at a given time within a sound file?
I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer.
I'm currently using Python with the Snack Sound Toolkit and I can record audio coming in from the microphone, but I need to know how loud that audi... | Get the amplitude at a given time within a sound file? | I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer.
I'm currently using Python with the Snack Sound Toolkit and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another t... | [
"Looking at the Snack Sound Toolkit examples, there seems to be a dbPowerSpectrum function.\nFrom the reference:\n\ndBPowerSpectrum ( )\nComputes the log FFT power spectrum of the sound (at the sample number given in the start option) and returns a list of dB values. See the section item for a description of the re... | [
3,
1,
0
] | [] | [] | [
"amplitude",
"audio",
"input",
"microphone",
"python"
] | stackoverflow_0000742546_amplitude_audio_input_microphone_python.txt |
Q:
Unable to make an iterable decimal function in Python
I want to calculate the sum of
1/1 + 1/2 + 1/3 + ... + 1/30
I run the code unsuccessfully
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
I get the error
'Decimal' object is not iterable
How can you make the ite... | Unable to make an iterable decimal function in Python | I want to calculate the sum of
1/1 + 1/2 + 1/3 + ... + 1/30
I run the code unsuccessfully
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
I get the error
'Decimal' object is not iterable
How can you make the iterable function in Python?
| [
"What you want is this:\nprint(sum(decimal.Decimal(1) / i for i in range(1, 31)))\n\nThe reason your code doesn't work, is that you try to iterate over one Decimal instance (through the use of sum). Furthermore, your definition of var is invalid. Your intention was probably something like this:\nvar = lambda i: dec... | [
11,
3,
2
] | [] | [] | [
"iteration",
"python",
"sum"
] | stackoverflow_0000845787_iteration_python_sum.txt |
Q:
Defining dynamic functions to a string
I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dea... | Defining dynamic functions to a string | I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For ex... | [
"It is possible to map string operations to numbers:\n>>> import string\n>>> ops = {1:string.split, 2:string.replace}\n>>> my = \"a,b,c\"\n>>> ops[1](\",\", my)\n[',']\n>>> ops[1](my, \",\")\n['a', 'b', 'c']\n>>> ops[2](my, \",\", \"-\")\n'a-b-c'\n>>> \n\nBut maybe string descriptions of the operations will be more... | [
2,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0000844886_python.txt |
Q:
What's the quickest way for a Ruby programmer to pick up Python?
I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that... | What's the quickest way for a Ruby programmer to pick up Python? | I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical langua... | [
"A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, lots of it. Your experience in Ruby will make it easy to pick up python's dynamic concepts (which might be harder to get used to for say a Java... | [
11,
3,
3,
2
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0000846139_python_ruby.txt |
Q:
Unit tests for automatically generated code: automatic or manual?
I know similar questions have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.
I've written a module in Python which contai... | Unit tests for automatically generated code: automatic or manual? | I know similar questions have been asked before but they don't really have the information I'm looking for - I'm not asking about the mechanics of how to generate unit tests, but whether it's a good idea.
I've written a module in Python which contains objects representing physical constants and units of measurement. A... | [
"If you auto-generate the tests:\n\nYou might find it faster to then read all the tests (to inspect them for correctness) that it would have been to write them all by hand.\nThey might also be more maintainable (easier to edit, if you want to edit them later).\n\n",
"You're right to identify the weakness of autom... | [
1,
1,
1,
1
] | [] | [] | [
"code_generation",
"python",
"unit_testing"
] | stackoverflow_0000845887_code_generation_python_unit_testing.txt |
Q:
Snapshot Movies
I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? An... | Snapshot Movies | I'm currently learning Python and have taken up several small projects to help learn the language. Are there currently any libraries (possibly PythonMagick) out there that are capable of extracting snapshots from .wmv, .avi, .mpg, or other movie formats with only command-line options (no GUI)? And if so, can anyone p... | [
"A quick search in google revealed pymedia. It supports avi, dvd, wma, ...\nHere is an example on how to get snapshots from videos\n",
"Additionally, if the CLI situation is not mandatory Pyglet is exceptionally easy to use to load movies, images, etc. and is very well documented.\n"
] | [
1,
0
] | [] | [] | [
"movie",
"python",
"screenshot",
"snapshot"
] | stackoverflow_0000846343_movie_python_screenshot_snapshot.txt |
Q:
Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0?
I poked around the mod_python website and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?
A:
Use mod_wsgi.
mod_python has been stagnant for a... | Is there a mod_python for Apache HTTP Server 2.2 and Python 2.6 or 3.0? | I poked around the mod_python website and I only found the files for Python 2.5 and earlier for Apache HTTP Server 2.2. I Googled around a little, without significant luck. Any suggestions?
| [
"Use mod_wsgi.\nmod_python has been stagnant for a while now. Most of the effort for python web apps has been going into mod_wsgi.\n"
] | [
9
] | [] | [] | [
"apache2",
"mod_python",
"python"
] | stackoverflow_0000846420_apache2_mod_python_python.txt |
Q:
How do you store raw bytes as text without losing information in python 2.x?
Suppose I have any data stored in bytes. For example:
0110001100010101100101110101101
How can I store it as printable text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact thi... | How do you store raw bytes as text without losing information in python 2.x? | Suppose I have any data stored in bytes. For example:
0110001100010101100101110101101
How can I store it as printable text? The obvious way would be to convert every 0 to the character '0' and every 1 to the character '1'. In fact this is what I'm currently doing. I'd like to know how I could pack them more tightl... | [
"What about an encoding that only uses \"safe\" characters like base64?\nhttp://en.wikipedia.org/wiki/Base64\nEDIT: That is assuming that you want to safely store the data in text files and such?\nIn Python 2.x, strings should be fine (Python doesn't use null terminated strings, so don't worry about that).\nElse in... | [
7,
3,
1,
0
] | [] | [] | [
"bit",
"compression",
"python",
"python_2.7",
"storage"
] | stackoverflow_0000840981_bit_compression_python_python_2.7_storage.txt |
Q:
Twisted and p2p applications
Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
A:
The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent.
Last known Twis... | Twisted and p2p applications | Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?
| [
"The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent.\n\nLast known Twisted version of BitTorrent\n\n\nhttp://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz\n\nOlder versions\n\n\nhttp://download.bittorren... | [
13,
4,
1,
0
] | [] | [] | [
"p2p",
"protocols",
"python",
"twisted"
] | stackoverflow_0000839384_p2p_protocols_python_twisted.txt |
Q:
Modelling a swiss tournament in Django
I'm trying to create models that represent a swiss tournament, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye.
I need to keep track of the outcome of each pa... | Modelling a swiss tournament in Django | I'm trying to create models that represent a swiss tournament, with multiple rounds. Each round everyone will be paired up with another player, except in the case where there is an odd player out, when one player will get a bye.
I need to keep track of the outcome of each pairing; i.e., which player won. Also, I'd lik... | [
"You can refactor your TournamentPairing class to be more \"round\" centric to aid in making queries.\nCHOICES = (\n ('n', 'Normal'),\n ('b', 'Bye'),\n )\nclass Round(models.Model): \n number = models.IntegerField()\n round_type = models.CharField(max_length=1, default=\"n\", choices=CHOICES)\... | [
5,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000846485_django_django_models_python.txt |
Q:
Parsing in Python: what's the most efficient way to suppress/normalize strings?
I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my ... | Parsing in Python: what's the most efficient way to suppress/normalize strings? | I'm parsing a source file, and I want to "suppress" strings. What I mean by this is transform every string like "bla bla bla +/*" to something like "string" that is deterministic and does not contain any characters that may confuse my parser, because I don't care about the value of the strings. One of the issues here i... | [
"Option 1: To sanitize Python source code, try the built-in tokenize module. It can correctly find strings and other tokens in any Python source file.\nOption 3: Use pygments with HTML output, and replace anything in blue (etc.) with \"string\". pygments supports a few dozen languages.\nOption 2: For most of the la... | [
4,
1,
1
] | [] | [] | [
"parsing",
"python",
"string"
] | stackoverflow_0000846869_parsing_python_string.txt |
Q:
Is Twisted an httplib2/socket replacement?
Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.
Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, espe... | Is Twisted an httplib2/socket replacement? | Many python libraries, even recently written ones, use httplib2 or the socket interface to perform networking tasks.
Those are obviously easier to code on than Twisted due to their blocking nature, but I think this is a drawback when integrating them with other code, especially GUI one. If you want scalability, concurr... | [
"See asychronous-programming-in-python-twisted, you'll have to decide if depending on a non-standard (external) library fits your needs. Note the answer by @Glyph, he is the founder of the Twisted project, and can authoritatively answer any Twisted related question.\n\nAt the core of libraries like Twisted, the fun... | [
5,
0
] | [] | [] | [
"httplib2",
"networking",
"python",
"sockets",
"twisted"
] | stackoverflow_0000846950_httplib2_networking_python_sockets_twisted.txt |
Q:
how to use list of python objects whose representation is unicode
I have a object which contains unicode data and I want to use that in its representaion
e.g.
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("ut... | how to use list of python objects whose representation is unicode | I have a object which contains unicode data and I want to use that in its representaion
e.g.
# -*- coding: utf-8 -*-
class A(object):
def __unicode__(self):
return u"©au"
def __repr__(self):
return unicode(self).encode("utf-8")
__str__ = __repr__
a = A()
s1 = u"%s"%a # works
#s2 = u"... | [
"s1 = u\"%s\"%a # works\nThis works, because when dealing with 'a' it is using its unicode representation (i.e. the unicode method),\nwhen however you wrap it in a list such as '[a]' ... when you try to put that list in the string, what is being called is the unicode([a]) (which is the same as repr in the case of l... | [
4,
3,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0000842696_python_unicode.txt |
Q:
Read Unicode characters from command-line arguments in Python 2.x on Windows
I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?
Example c... | Read Unicode characters from command-line arguments in Python 2.x on Windows | I want my Python script to be able to read Unicode command line arguments in Windows. But it appears that sys.argv is a string encoded in some local encoding, rather than Unicode. How can I read the command line in full Unicode?
Example code: argv.py
import sys
first_arg = sys.argv[1]
print first_arg
print type(first_... | [
"Here is a solution that is just what I'm looking for, making a call to the Windows GetCommandLineArgvW function:\nGet sys.argv with Unicode characters under Windows (from ActiveState)\nBut I've made several changes, to simplify its usage and better handle certain uses. Here is what I use:\nwin32_unicode_argv.py\n\... | [
30,
12,
2,
0
] | [] | [] | [
"command_line",
"python",
"python_2.x",
"unicode",
"windows"
] | stackoverflow_0000846850_command_line_python_python_2.x_unicode_windows.txt |
Q:
Importing a python module to .net - "No module named signal"
I'm trying to import a Python module in a C# code like this:
var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var module = engine.ImportModule("my... | Importing a python module to .net - "No module named signal" | I'm trying to import a Python module in a C# code like this:
var setup = Python.CreateRuntimeSetup(null);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var module = engine.ImportModule("mymodule");
but I get an error saying "No module named signal", doe... | [
"The 'signal' module is used to handle all that has to do with ... you guessed it: signals. There are special \"messages\" that the OS send to a process to tell it something: eg. Break, Kill, Terminate, etc... The exact set of message are generally OS specific, but as the signals python manual page states, python e... | [
2
] | [] | [] | [
".net",
"ironpython",
"python"
] | stackoverflow_0000847109_.net_ironpython_python.txt |
Q:
User-defined derived data in Django
How do I let my users apply their own custom formula to a table of data to derive new fields?
I am working on a Django application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am g... | User-defined derived data in Django | How do I let my users apply their own custom formula to a table of data to derive new fields?
I am working on a Django application which is going to store and process a lot of data for subscribed users on the open web. Think 100-10,000 sensor readings in one page request. I am going to be drawing graphs using this data... | [
"I would work out what operations you want to support [+,-,*,/,(,),etc] and develop client side (javascript) to edit and apply those values to new fields of the data. I don't see the need to do any of this server-side and you will end up with a more responsive and enjoyable user experience as a result.\nIf you allo... | [
2,
2,
0
] | [] | [] | [
"django",
"python",
"user_defined_functions"
] | stackoverflow_0000847201_django_python_user_defined_functions.txt |
Q:
Exposing a C++ API to Python
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.
The alternatives I tried were:
Boost.Python
I liked the cleaner API produced by ... | Exposing a C++ API to Python | I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program.
The alternatives I tried were:
Boost.Python
I liked the cleaner API produced by Boost.Python, but the fact that it... | [
"I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies,... | [
23,
18,
7,
5,
2
] | [] | [] | [
"boost",
"c++",
"python",
"swig"
] | stackoverflow_0000276761_boost_c++_python_swig.txt |
Q:
How to write a vb.net code to compile C/C++ programs?
I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile butt... | How to write a vb.net code to compile C/C++ programs? | I'm trying to make a vb.net application that has got 2 textboxes, 7 radio buttons and 2 buttons(one named compile and the other 'run'). How can I load the content of a C/C++(or any programming language) file into the 1st textbox and on clicking the compile button, i should be able to show the errors or the C/C++ progra... | [
"Look at the System.IO namespace for clues as to how you go about loading the contents of a file into a text box. In particular, the File class.\nSystem.IO.File Class\nLook at the System.Diagnostics namespace for clues as to how to go about launching a process and capturing the output. In particular, the Process cl... | [
2,
1
] | [] | [] | [
"c",
"c#",
"c++",
"python",
"vb.net"
] | stackoverflow_0000847860_c_c#_c++_python_vb.net.txt |
Q:
Convert C++ Header Files To Python
I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.
A:
I don't know h2py, but you may want ... | Convert C++ Header Files To Python | I have a C++ header that contains #define statements, Enums and Structures. I have tried using the h2py.py script that is included with Python to no avail (except giving me the #defines converted). Any help would be greatly appreciated.
| [
"I don't know h2py, but you may want to look at 'ctypes' and 'ctypeslib'. ctypes is included with python 2.5+, and is targeted at creating binary compatibility with c-structs.\nIf you add ctypeslib, you get a sub-tool called codegen, which has a 'h2xml.py' script, and a 'xml2py.py', the combination of which will a... | [
11,
2,
1,
0
] | [] | [] | [
"c++",
"data_structures",
"enums",
"header",
"python"
] | stackoverflow_0000374217_c++_data_structures_enums_header_python.txt |
Q:
Rename invalid filename in XP via Python
My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to m... | Rename invalid filename in XP via Python | My problem is similar to Python's os.path choking on Hebrew filenames
however, I don't know the original encoding of the filename I need to rename (unlike the other post he knew it was Hebrew originally).
I was doing data recovery for a client and copied over the files to my XP SP3 machine,
and some of the file names h... | [
"'?' is not valid character for filenames. That is the reason while your approach failed.\nYou may try to use DOS short filenames:\nimport win32api\nfilelist = win32api.FindFiles(r'F:/recovery/My Music/*.*')\n\n# this will extract \"short names\" from WIN32_FIND_DATA structure\nfilelist = [i[9] if i[9] else i[8] fo... | [
2,
0
] | [] | [] | [
"python",
"unicode",
"windows_xp"
] | stackoverflow_0000845926_python_unicode_windows_xp.txt |
Q:
OOP: good class design
My question is related to this one: Python tool that builds a dependency diagram for methods of a class.
After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies... | OOP: good class design | My question is related to this one: Python tool that builds a dependency diagram for methods of a class.
After not finding any tools I wrote a quick hack myself: I've used the compiler module, I've parsed the source code into an Abstract Source Tree and I've walked it to collect dependencies between class methods. My s... | [
"We follow the following principles when designing classes:\n\nThe Single Responsibility Principle: A class (or method) should have only one reason to change.\nThe Open Closed Principle: A class (or method) should be open for extension and closed for modification.\nThe Liskov Substitution Principle: Subtypes must b... | [
30,
3,
1,
0,
0
] | [] | [] | [
"language_agnostic",
"oop",
"python"
] | stackoverflow_0000845966_language_agnostic_oop_python.txt |
Q:
Javascript graphing library to draw a region
As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so ... | Javascript graphing library to draw a region | As a keen windsurfer, I'm interested in how windy the next few weeks are going to be. To that end, I've been writing a little app to scrape a popular weather site (personal use only - not relaying the information or anything) and collate the data into a single graph so that I can easily see when's going to be worth hea... | [
"Take a look at the Google chart API's. They make this sort of thing pretty easy. Without some example code, I would have a hard time giving you an example, but Google has nice one on the docs.\n",
"You should check out Dojo. It looks like it'd be pretty easy for you to do, just plot the bottom line with the s... | [
1,
1,
0
] | [] | [] | [
"django",
"graph",
"javascript",
"python",
"screen_scraping"
] | stackoverflow_0000848604_django_graph_javascript_python_screen_scraping.txt |
Q:
Deploying Python via CGI
How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.
Any resource links are appreciated.
The web host in question is GoDaddy.
A:
Generally, we use mod_wsgi to make a... | Deploying Python via CGI | How do I deploy a Python project to a webserver that supports Python via CGI? I'm well versed in PHP, but do not understand CGI's relation to Python in the deployment process.
Any resource links are appreciated.
The web host in question is GoDaddy.
| [
"Generally, we use mod_wsgi to make a Python application respond to CGI. \nPHP has a special role -- the language runtime IS a CGI application.\nPython does not have this special role. Python -- by default -- is not a CGI application. It requires a piece of glue to play well with Apache. mod_wsgi is this glue.\... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0000849384_python.txt |
Q:
Standard non-code resource location for python packages
This should be a common scenario, but could not find any relevant post yet..
I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such i... | Standard non-code resource location for python packages | This should be a common scenario, but could not find any relevant post yet..
I plan to deploy a Python library (I guess the same applies to regular applications) which makes use of some images and other resource files. What is the standard location for such items? I imagine, for project Foo, the choices would be
Have ... | [
"This question is somewhat incomplete, because a proper answer would depend on the underlying operating system, as each has its own modus operandi. In linux (and most unix based OSs) for example /usr/share/foo or /usr/local/share/foo would be the standard. In OS X you can do the same, but I would think \"/Library/A... | [
2,
2,
0
] | [] | [] | [
"location",
"package",
"python",
"resources",
"shared"
] | stackoverflow_0000849334_location_package_python_resources_shared.txt |
Q:
Performing Photoshop's "Luminosity" filter programmatically
I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-L... | Performing Photoshop's "Luminosity" filter programmatically | I have two JPEG's and would like to overlay one on the other with the same results as the "Luminosity" mode available in Photoshop (and Fireworks). You can read more about Luminosity mode here: http://www.adobetutorialz.com/articles/662/1/Photoshop%92s-Luminosity-Mode
How can I do this? Programming language doesn't m... | [
"First you need to understand what Photoshop does.\nIt preserves under layer perceptual color information and replaces it's luminosity with the top layer's perceptual luminosity information. To do that, you need to convert the images to the right color space.\nHere is the shoping list of things you will need to do ... | [
5,
1,
1,
0,
0
] | [] | [] | [
"image",
"image_processing",
"php",
"python",
"python_imaging_library"
] | stackoverflow_0000849654_image_image_processing_php_python_python_imaging_library.txt |
Q:
Python multiprocessing on Python 2.6 Win32 (xp)
I tried to copy this example from this Multiprocessing lecture by jesse noller (as recommended in another SO post)[http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4]
But for some reason I'm getting an error, as though it's ... | Python multiprocessing on Python 2.6 Win32 (xp) | I tried to copy this example from this Multiprocessing lecture by jesse noller (as recommended in another SO post)[http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4]
But for some reason I'm getting an error, as though it's ignoring my function definitions:
I'm on Windows XP (... | [
"Seems from the traceback that you are running the code directly into the python interpreter (REPL).\nDon't do that. Save the code in a file and run it from the file instead, with the command:\npython myfile.py\n\nThat will solve your issue.\n\nAs an unrelated note, this line is wrong:\nprint 'Sleeping for ' + wait... | [
4
] | [] | [] | [
"multiprocessing",
"python",
"python_2.6",
"winapi"
] | stackoverflow_0000850424_multiprocessing_python_python_2.6_winapi.txt |
Q:
Can a Python module use the imports from another file?
I have something like this:
# a.py
import os
class A:
...
# b.py
import a
class B(A):
...
In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I... | Can a Python module use the imports from another file? | I have something like this:
# a.py
import os
class A:
...
# b.py
import a
class B(A):
...
In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?
Edit: I'm not worried abo... | [
"Yes you can use the imports from the other file by going a.os.\nHowever, the pythonic way is to just import the exact modules you need without making a chain out of it (which can lead to circular references).\nWhen you import a module, the code is compiled and inserted into a dictionary of names -> module objects.... | [
13,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000850566_python.txt |
Q:
Scope of Python Recursive Generators
Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in r... | Scope of Python Recursive Generators | Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.
The code is similar to this snippet.
def testGen(a,n):
if n <= 1:
print('yield', a)
yield a
else:
for i in range(2):
a[i] += n
... | [
"I would guess you are mutating the array, so when you print it has a particular value, then the next time you print it has actually updated the value, and so on. At the end, you have 5 references to the same array, so of course you have the same value 5 times.\n",
"The print statement displays the list at that ... | [
2,
2,
2,
0
] | [] | [] | [
"generator",
"python",
"recursion",
"scope"
] | stackoverflow_0000850725_generator_python_recursion_scope.txt |
Q:
How to prevent every malicious file upload on my server? (check file type)?
my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
function checkFile($nomeFile, $myExt = false){
if($myExt != fals... | How to prevent every malicious file upload on my server? (check file type)? | my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_.doc_.... | [
"I'm afraid to say that the answer you selected as correct is not correct. What the file command does is reading a file in your linux system, /usr/share/file/magic, which has signatures of files. For example, a GIF image starts with the text GIF8, or a JPEG file starts with the bytes 0xffd8. You just need to have t... | [
15,
7,
6,
2,
1,
0
] | [] | [] | [
"file",
"php",
"python",
"security",
"types"
] | stackoverflow_0000690108_file_php_python_security_types.txt |
Q:
Can you pass a class (not an object) as a parameter to a method in python?
I want to do something like the following
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
I want this to be equivalent to A.static_method(). Is this possible?
A:
Sure. Classes are first-... | Can you pass a class (not an object) as a parameter to a method in python? | I want to do something like the following
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
I want this to be equivalent to A.static_method(). Is this possible?
| [
"Sure. Classes are first-class objects in Python.\nAlthough, in your example, you should use the @classmethod (class object as initial argument) or @staticmethod (no initial argument) decorator for your method.\n",
"You should be able to do the following (note the @staticmethod decorator):\nclass A:\n @staticmet... | [
8,
5,
0
] | [] | [] | [
"parameters",
"python",
"static"
] | stackoverflow_0000850921_parameters_python_static.txt |
Q:
How to Make an Image Uniform Brightness (using Python/PIL)
I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would b... | How to Make an Image Uniform Brightness (using Python/PIL) | I want to take an image of a document that was photographed and make it look like it was scanned. Since a scanner will put a constant light source over the whole document, I want to achieve that effect on a photo of a document. The desired effect would be to remove any shadows or areas of low light (or at least make ... | [
"As a first attempt, try thresholding the image. Dark areas become black, light areas become white. I haven't used PIL, but I imagine there's any easy way to do it.\n",
"Try ImageChops.screen(image1, image2) with 2 copies of the image. If that's not satisfactory, try some of the other functions in the ImageChop... | [
2,
2,
0,
0
] | [] | [] | [
"brightness",
"image",
"image_processing",
"python",
"python_imaging_library"
] | stackoverflow_0000664760_brightness_image_image_processing_python_python_imaging_library.txt |
Q:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are th... | Python: Callbacks, Delegates, ... ? What is common? | Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?
| [
"Personally I don't see a difference between callbacks, listeners, and delegates.\nThe observer pattern (a.k.a listeners, a.k.a \"multiple callbacks\") is easy to implement - just hold a list of observers, and add or remove callables from it. These callables can be functions, bound methods, or classes with the __ca... | [
19,
2,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"callback",
"delegates",
"events",
"python"
] | stackoverflow_0000443885_callback_delegates_events_python.txt |
Q:
Newbie teaching self python, what else should I be learning?
I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs ... | Newbie teaching self python, what else should I be learning? | I'm a newbie to programming. I had 1 semester of computer science (we used java). I got an A in the course and was able to do everything assigned, however I'm not sure I really understood it. I ignored the text and learned by looking at sample programs and then trial and error. I was ahead of the class except for two ... | [
"My recommendation is always to start at the high level of abstraction. You don't need to know how logic gates work and how you can use them to build a CPU -- it's cool stuff, but it's cool stuff that makes a lot more sense once you've messed around at the higher levels. Python is therefore an excellent choice as... | [
14,
9,
5,
3,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"theory"
] | stackoverflow_0000805720_python_theory.txt |
Q:
Faster way to sum a list of numbers than with a for-loop?
Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorte... | Faster way to sum a list of numbers than with a for-loop? | Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.
| [
"You can use sum() to sum the values of an array.\na = [1,9,12]\nprint sum(a)\n\n",
"Yet another way to sum up a list with the loop time:\n s = reduce(lambda x, y: x + y, l)\n\n",
"If each term in the list simply increments by 1, or if you can find a pattern in the series, you could find a formula for summin... | [
36,
4,
1,
1
] | [
"For a general list, you have to at least go over every member at least once to get the sum, which is exactly what a for loop does. Using library APIs (like sum) is more convenient, but I doubt it would actually be faster.\n"
] | [
-1
] | [
"algorithm",
"for_loop",
"python"
] | stackoverflow_0000850877_algorithm_for_loop_python.txt |
Q:
Is a graph library (eg NetworkX) the right solution for my Python problem?
I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use... | Is a graph library (eg NetworkX) the right solution for my Python problem? | I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather... | [
"Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a d... | [
2,
0
] | [] | [] | [
"graph",
"python"
] | stackoverflow_0000844505_graph_python.txt |
Q:
Python -- Regex -- How to find a string between two sets of strings
Consider the following:
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
... | Python -- Regex -- How to find a string between two sets of strings | Consider the following:
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
How would you go about taking out the sitemap line with re... | [
"Don't use a regex. Use BeautfulSoup, an HTML parser.\nfrom BeautifulSoup import BeautifulSoup\n\nhtml = \\\n\"\"\"\n<div id=hotlinklist>\n <a href=\"foo1.com\">Foo1</a>\n <div id=hotlink>\n <a href=\"/\">Home</a>\n </div>\n <div id=hotlink>\n <a href=\"/extract\">Extract</a>\n </div>\n <div id=hotlink>... | [
13,
6,
5,
1
] | [] | [] | [
"python",
"regex",
"string",
"tags"
] | stackoverflow_0000849912_python_regex_string_tags.txt |
Q:
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 th... | What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django) | I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g.
[("hello", 3, 4), ("cat", 5, 3), ...... | [
"For MySQL specifically, the fastest way to load data is using LOAD DATA INFILE, so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table.\n",
"You can write the rows to a file in the format\n\"field1\", \"field2\", .. and then use LOAD DATA to load... | [
12,
12,
4,
4,
2,
1,
1,
1
] | [] | [] | [
"django",
"insert",
"mysql",
"python",
"sql"
] | stackoverflow_0000850117_django_insert_mysql_python_sql.txt |
Q:
Django ImageField issue
I have a similar model
Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""
name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
As we can see photo field is op... | Django ImageField issue | I have a similar model
Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""
name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
As we can see photo field is optional. I wanted all the stud... | [
"It doesn't work because field lookups only work on other models. Here, name is an attribute on the return value of your photo field.\nTry this instead:\nStudent.objects.exclude(photo__isnull=True)\n\nIt is preferred to use isnull instead of comparing equality to None.\nEDIT:\nJeff Ober's suggestion:\nStudent.objec... | [
13
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000851830_django_django_models_python.txt |
Q:
Reverse proxy capable pure python webserver?
I am looking for a pure python based web server has the capability for reverse proxy as well?
A:
pretty sure you can do that with twisted,
twisted web
but why not just use apache?
| Reverse proxy capable pure python webserver? | I am looking for a pure python based web server has the capability for reverse proxy as well?
| [
"pretty sure you can do that with twisted,\ntwisted web\nbut why not just use apache?\n"
] | [
2
] | [] | [] | [
"proxy",
"python",
"reverse",
"webserver"
] | stackoverflow_0000852541_proxy_python_reverse_webserver.txt |
Q:
Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python)
I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.
The Perl code is:
use DBI;
my $DSN = "DBI:Proxy:hostname=some.... | Python equivalent of perl's dbi/DBD::Proxy access? (Perl DBI/DBD::Proxy for Python) | I have a Perl script that interfaces with an existing database (type of database is unknown) through the DBI module, that I would like to access in python 2.6 on WinXP.
The Perl code is:
use DBI;
my $DSN = "DBI:Proxy:hostname=some.dot.com;port=12345;dsn=DBI:XXXX:ZZZZZ";
my $dbh = DBI->connect($DSN);
Can this be tran... | [
"Your python script doesn't have to be a line by line translation of your Perl script.\nWhy not just use the Python DB-API compatible module for the database you want to access? For MySQL, use MySQLdb. For PostgreSQL, use PyGreSQL. \nOr search Google for \"YourDatabaseName + python\"\n",
"sqlalchemy is pretty ... | [
5,
0
] | [] | [] | [
"dbi",
"odbc",
"perl",
"python"
] | stackoverflow_0000847032_dbi_odbc_perl_python.txt |
Q:
Reverse proxy capable pure python webserver?
I am looking for a pure python based web server has the capability for reverse proxy as well?
A:
Have a look at Twisted, especially its ReverseProxyResource.
Twisted Web also provides various facilities for being set up behind a reverse-proxy, which is the suggested... | Reverse proxy capable pure python webserver? | I am looking for a pure python based web server has the capability for reverse proxy as well?
| [
"Have a look at Twisted, especially its ReverseProxyResource.\n\nTwisted Web also provides various facilities for being set up behind a reverse-proxy, which is the suggested mechanism to integrate your Twisted application with an existing site.\n\n",
"http://pypi.python.org/pypi/proxylet/\nFrom http://www.rfk.id.... | [
3,
0
] | [] | [] | [
"proxy",
"python",
"reverse",
"webserver"
] | stackoverflow_0000852690_proxy_python_reverse_webserver.txt |
Q:
Python: getting a reference to a function from inside itself
If I define a function:
def f(x):
return x+3
I can later store objects as attributes of the function, like so:
f.thing="hello!"
I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the functio... | Python: getting a reference to a function from inside itself | If I define a function:
def f(x):
return x+3
I can later store objects as attributes of the function, like so:
f.thing="hello!"
I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?
| [
"The same way, just use its name.\n>>> def g(x):\n... g.r = 4\n...\n>>> g\n<function g at 0x0100AD68>\n>>> g(3)\n>>> g.r\n4\n\n",
"If you are trying to do memoization, you can use a dictionary as a default parameter:\ndef f(x, memo={}):\n if x not in memo:\n memo[x] = x + 3\n return memo[x]\n\n",
"Or use... | [
21,
3,
3
] | [] | [] | [
"function",
"python",
"self_reference"
] | stackoverflow_0000852401_function_python_self_reference.txt |
Q:
Tokenizing left over data with lex/yacc
Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:
I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes o... | Tokenizing left over data with lex/yacc | Forgive me, I'm completely new to parsing and lex/yacc, and I'm probably in way over my head, but nonetheless:
I'm writing a pretty basic calculator with PLY, but it's input might not always be an equation, and I need to determine if it is or not when parsing. The extremes of the input would be something that evaluates... | [
"There is a built-in error token in yacc. You would normally do something like:\n\nline: goodline | badline ;\nbadline : error '\\n' /* Error-handling action, if needed */\ngoodline : equation '\\n' ;\n\nAny line that doesn't match equation will be handled by badline.\nYou might want to use yyerrok in the error han... | [
1,
1,
0,
0
] | [] | [] | [
"lex",
"ply",
"python",
"yacc"
] | stackoverflow_0000841159_lex_ply_python_yacc.txt |
Q:
How to establish communication between flex and python code build on Google App Engine
I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.
Can anyone give me a hint about how to send login infor... | How to establish communication between flex and python code build on Google App Engine | I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.
Can anyone give me a hint about how to send login information from Flex to python
Any ideas suggest me some examples.....please provide me some he... | [
"I've been able to use flex on GAE using the examples found at The GAE SWF Project which uses PyAMF.\n",
"Do a HTTP post from Flex to your AppEngine app using the URLRequest class.\n"
] | [
2,
0
] | [] | [] | [
"apache_flex",
"google_app_engine",
"python"
] | stackoverflow_0000854353_apache_flex_google_app_engine_python.txt |
Q:
Strange python behaviour
I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
The answer to [4] is not 4294967296L, it's a very long numbe... | Strange python behaviour | I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
The answer to [4] is not 4294967296L, it's a very long number, but I can't really figure o... | [
"Python is going right to left on the mathematical power operation. For example, IN[2] is doing:\n2**(4) = 16\nIN[3] = 2222 = 22**(4) = 2**16 = 65536\nYou would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomi... | [
16,
7,
4,
4,
3
] | [] | [] | [
"ipython",
"python"
] | stackoverflow_0000853407_ipython_python.txt |
Q:
Can I Pass Dictionary Values/Entry and Keys to function
I am writing a function and intended to use a dictionary key and its value as parameters. For example:
testDict={'x':2,'xS':4}
def newFunct(key,testDict['key']):
newvalue=key+str(testDict['key'])
return newValue
for key in testDict:
newValue=ne... | Can I Pass Dictionary Values/Entry and Keys to function | I am writing a function and intended to use a dictionary key and its value as parameters. For example:
testDict={'x':2,'xS':4}
def newFunct(key,testDict['key']):
newvalue=key+str(testDict['key'])
return newValue
for key in testDict:
newValue=newFunct(key,testDict[key])
print newValue
I get a SyntaxE... | [
"Is this what you want?\ndef func(**kwargs):\n for key, value in kwargs.items():\n pass # Do something\n\nfunc(**myDict) # Call func with the given dict as key/value parameters\n\n(See the documentation for more about keyword arguments. The keys in myDict must be strings.)\n\nEdit: you edited your questio... | [
7,
2,
0,
0
] | [] | [] | [
"dictionary",
"function",
"python"
] | stackoverflow_0000853483_dictionary_function_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.