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:
Python - List of Strings to Java
I'm getting a list of strings from python code and need to read it in Java. When trying to read it, i get the hashCode
[Ljava.lang.Object;@7cf1bb78
I want to read the values in a list. In python my return is something like
return SUCCESS(OK, params={'data':nameList()})
How would... | Python - List of Strings to Java | I'm getting a list of strings from python code and need to read it in Java. When trying to read it, i get the hashCode
[Ljava.lang.Object;@7cf1bb78
I want to read the values in a list. In python my return is something like
return SUCCESS(OK, params={'data':nameList()})
How would I read this in Java and print the con... | [
"You already have what you want. Try System.out.println(java.util.Arrays.toString(getName)); (the default toString() for an array in Java is not very useful).\n",
"The usual way to print out each item in a Java array would be something like:\nfor (Object name: (Object[]) getNameList()) {\n System.out.println(nam... | [
1,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0001720778_java_python.txt |
Q:
Python .sort() not working as expected
Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the lis... | Python .sort() not working as expected | Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my progr... | [
"You are sorting strings, not numbers. '101101' < '10201' because '1' < '2'. Change list.append(reversed) to list.append(int(reversed)) and it will work (or use a different sorting function).\n",
"Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how t... | [
25,
13,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0001513727_list_python_sorting.txt |
Q:
Will python.subprocess(cppBinaryExe) compromise cppBinaryExe's performance?
i am quite new to python.subprocess()
if i folk a new process from python, will the execution speed of this new process be compromised?
imagine that i have the
#python
import subprocess
subprocess.call( MyBinary )
basically, is there an... | Will python.subprocess(cppBinaryExe) compromise cppBinaryExe's performance? | i am quite new to python.subprocess()
if i folk a new process from python, will the execution speed of this new process be compromised?
imagine that i have the
#python
import subprocess
subprocess.call( MyBinary )
basically, is there any difference between
./MyBinary
and
./python ruMyBinary.py
?
| [
"No. A separate process is a separate process. It competes for OS resources with all other processes \"fairly\".\nYour python process that simply does subprocess.call is a process, and does consume some system resources. But relatively few, since it will be waiting for a system call to finish. It will occupy a ... | [
3,
2,
0
] | [] | [] | [
"linux",
"python"
] | stackoverflow_0001721530_linux_python.txt |
Q:
python contour for binary 2D matrix
I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on ... | python contour for binary 2D matrix | I want to calculate a convex hull around a shape in a binary NxM matrix. The convex hull algorithm expects a list of coordinates, so I take numpy.argwhere(im) to have all shape point coordinates. However, most of those points are not contributing to the convex hull (they lie on the inside of the shape). Because convex ... | [
"In the absence of an acceptable answer I post my best working code as the solution.\ndef outline(im):\n ''' Input binary 2D (NxM) image. Ouput array (2xK) of K (y,x) coordinates\n where 0 <= K <= 2*M.\n '''\n topbottom = np.empty((1,2*im.shape[1]), dtype=np.uint16)\n topbottom[0,0:im.shape[1]] =... | [
3,
0,
0
] | [] | [] | [
"algorithm",
"contour",
"numpy",
"python"
] | stackoverflow_0001601613_algorithm_contour_numpy_python.txt |
Q:
Is there any "remote console" for twisted server?
I am developing a twisted server. I need to control the memory usage. It is not a good idea to modify code, insert some memory logging command and restart the server. I think it is better to use a "remote console", so that I can type heapy command and see the respo... | Is there any "remote console" for twisted server? | I am developing a twisted server. I need to control the memory usage. It is not a good idea to modify code, insert some memory logging command and restart the server. I think it is better to use a "remote console", so that I can type heapy command and see the response from the server directly. All I need is a remote co... | [
"twisted.manhole.telnet uses the deprecated module twisted.protocols.telnet. It is recommended to use twisted.conch.manhole instead.\nHere are some tutorials of how to use it:\n\nWriting a client with Twisted.Conch -- twisted.conch documentation\nNetwork programming with the Twisted framework, Part 4 -- IBM develop... | [
13,
6
] | [] | [] | [
"console",
"python",
"twisted"
] | stackoverflow_0001721699_console_python_twisted.txt |
Q:
Unable to send function arguments from webapp.RequestHandler class
I am getting this errorpage after uploading my application to the google app engine and calling it in the browser.
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call... | Unable to send function arguments from webapp.RequestHandler class | I am getting this errorpage after uploading my application to the google app engine and calling it in the browser.
Traceback (most recent call last):
File "/base/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 507, in __call__
handler.get(*groups)
File "/base/data/home/apps/bulkloader160by... | [
"Perhaps in:\naccount = db.get(src_key)\n\nsrc_key is None?\n",
"You're getting this error because src_key is None, which implies this statement:\n src_key = db.GqlQuery('SELECT __key__ FROM UserDetails WHERE user_name = :uname', uname = src_username).get()\n\nIs not matching any rows. Try logging the result o... | [
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001721156_google_app_engine_python.txt |
Q:
Diference between appengine_django BaseModel and db.Model
I'm using the Google App Engine helper for Django. This helper includes the following lines in its template:
from appengine_django.models import BaseModel
from google.appengine.ext import db
# Create your models here.
Should I derive my models from db.Mod... | Diference between appengine_django BaseModel and db.Model | I'm using the Google App Engine helper for Django. This helper includes the following lines in its template:
from appengine_django.models import BaseModel
from google.appengine.ext import db
# Create your models here.
Should I derive my models from db.Model or from BaseModel?
I've tried both and I don't see any diffe... | [
"The BaseModel also does a registration of the inherited model inside django (so f.e. you can request it by calling django.db.models.loading.get_model('app_lable.ModelName') and all other stuff related to this)\n",
"BaseModel is a class defined by the Django helper. It extends db.Model in order to make Django wor... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"google_app_engine",
"python"
] | stackoverflow_0001720157_django_django_models_google_app_engine_python.txt |
Q:
In the MVC pattern, what goes in the model and what goes in the view?
I'm using the MVC pattern to design some data analysis software (in
Python). I'm not sure whether some functions should go in the model or the controller.
The way I've designed it, the user supplies the program a configuration file which contai... | In the MVC pattern, what goes in the model and what goes in the view? | I'm using the MVC pattern to design some data analysis software (in
Python). I'm not sure whether some functions should go in the model or the controller.
The way I've designed it, the user supplies the program a configuration file which contains the parameters for analysis. The program parses this file to find out wh... | [
"The model should be your entity classes, or simply classes that model the problem domain you're working with. And the view anything basically having to do with how your user interacts with the system you're building. The controller marries the two.\n",
"On your first point, the parsing should go in the model if ... | [
2,
1,
0
] | [] | [] | [
"model_view_controller",
"python"
] | stackoverflow_0001718813_model_view_controller_python.txt |
Q:
Haystack Whoosh Spelling Suggestion too greedy
This questions is about Django Haystack, with Whoosh backend.
I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much.
Say I have two models:
Apples and Oranges.
If I have somethine like this:
result = SearchQuerySet().model... | Haystack Whoosh Spelling Suggestion too greedy | This questions is about Django Haystack, with Whoosh backend.
I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much.
Say I have two models:
Apples and Oranges.
If I have somethine like this:
result = SearchQuerySet().models(Apples).filter(
content=escaped_value).spellin... | [
"This is the problem because Haystack creates spelling suggestions based on the fields which have document=True (which in my case are the primary search field in all models and they have the same name). So it does not care about models at all and alway searches across all the knowledgebase.\nI filed an issue with h... | [
2
] | [] | [] | [
"django",
"django_haystack",
"python",
"whoosh"
] | stackoverflow_0001718758_django_django_haystack_python_whoosh.txt |
Q:
django datefield filter
I'd like to use an object filter similar to the following
Shipment.objects.filter(date__gte=datetime.date(2005,1,1))
However there doesn't seem to be support for comparison operators on datetime objects. Is there a method I'm unaware of or should I look into writing a custom filter.
A:
I... | django datefield filter | I'd like to use an object filter similar to the following
Shipment.objects.filter(date__gte=datetime.date(2005,1,1))
However there doesn't seem to be support for comparison operators on datetime objects. Is there a method I'm unaware of or should I look into writing a custom filter.
| [
"I use date comparison in my code a lot and they work e.g copied a snippet from my calendar code\nq.filter(start_date__gt=pay_period.start_date).order_by(\"start_date\")\n\n"
] | [
4
] | [] | [] | [
"datetime",
"django",
"filter",
"python"
] | stackoverflow_0001722111_datetime_django_filter_python.txt |
Q:
How can I measure the execution time of a for loop?
I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything wi... | How can I measure the execution time of a for loop? | I want to measure the execution time of for loops on various platforms like php, c, python, Java, javascript... How can i measure it?
I know these platforms so i am talking about these:
for (i = 0; i < 1000000; i++)
{
}
I don't want to measure anything within the loop.
Little bit modification:
@all Some of the ... | [
"Although an answer has been given for C++, it looks from your description (\"[You] don't want to measure anything within the loop\") like you're trying to measure the time which it takes a program to iterate over an empty loop.\nPlease take care here: not only will it take varying times from different platforms an... | [
5,
2,
2,
2,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"c",
"c++",
"java",
"php",
"python"
] | stackoverflow_0001721351_c_c++_java_php_python.txt |
Q:
403 error in Google App Engine with staticdir
For some reason I can't get static_dir to work. In my app.ymal I have:
- url: /ui
static_dir: ui
- url: /dump
static_dir: dump
Loading static files from /ui works (i.e /ui/images/logo.png). But when I try to access something from /dumo I just get:
INFO ... | 403 error in Google App Engine with staticdir | For some reason I can't get static_dir to work. In my app.ymal I have:
- url: /ui
static_dir: ui
- url: /dump
static_dir: dump
Loading static files from /ui works (i.e /ui/images/logo.png). But when I try to access something from /dumo I just get:
INFO 2009-11-12 14:03:55,497 dev_appserver.py:3034] "G... | [
"HTTP 403 code is usually returned by GAE for quota problems, read http://code.google.com/appengine/docs/quotas.html\nI think your zip file is more than 1 MB, and I have read it doesn't allow such big zip files. Try with a smaller file to make sure dump is working, I think it will work.\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"http_status_code_403",
"http_status_codes",
"linux",
"python"
] | stackoverflow_0001722441_google_app_engine_http_status_code_403_http_status_codes_linux_python.txt |
Q:
Is the first entry in sys.path supposed to represent the current working directory?
I had always assumed that the first entry in sys.path by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in... | Is the first entry in sys.path supposed to represent the current working directory? | I had always assumed that the first entry in sys.path by default was the current working directory. But as it turns out, on my system the first entry is the path on which the script resides. So if I'm executing a script that's in /usr/bin from /some/directory, the first entry in sys.path is /usr/bin. Is something mi... | [
"This is by design:\n\nAs initialized upon program startup,\n the first item of this list, path[0],\n is the directory containing the script\n that was used to invoke the Python\n interpreter.\n\nsource: http://docs.python.org/library/sys.html#sys.path\n",
"You can get the current directory with os.getcwd().\... | [
6,
1
] | [] | [] | [
"python",
"pythonpath",
"sys.path"
] | stackoverflow_0001722901_python_pythonpath_sys.path.txt |
Q:
Twisted/tkinter program crashes on exit
I am running an app using twisted and tkinter that sends the result to the server, waits for the server to send back a confirmation, and then exits. So, the function I use to exit is this:
def term():
'''To end the program'''
reactor.stop()
root.quit()
root.d... | Twisted/tkinter program crashes on exit | I am running an app using twisted and tkinter that sends the result to the server, waits for the server to send back a confirmation, and then exits. So, the function I use to exit is this:
def term():
'''To end the program'''
reactor.stop()
root.quit()
root.destroy()
This is then set in the factory and... | [
"You only need to call reactor.stop to exit: the root.quit() and root.destroy() calls are superfluous. Consider this short example which runs Twisted and Tk for three seconds and then exits:\nimport Tkinter\nfrom twisted.internet import tksupport\n\nroot = Tkinter.Tk()\ntksupport.install(root)\n\nfrom twisted.inte... | [
1
] | [] | [] | [
"python",
"tkinter",
"twisted"
] | stackoverflow_0001722865_python_tkinter_twisted.txt |
Q:
How to write the output of this code to HTML file?
from HTMLParser import HTMLParser
from urllib import urlopen
class Spider(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urlopen(url)
self.feed(req.read())
def handle_startt... | How to write the output of this code to HTML file? | from HTMLParser import HTMLParser
from urllib import urlopen
class Spider(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag == 'a' and ... | [
"python spider.py > output.html\n\n",
"Put this at the top of your script:\nimport sys\nsys.stdout = file('output.html', 'w')\n\nThis will redirect everything your script writes to the standard output (which includes print statements) to the file 'output.html'.\n",
"I haven't messed with Spider at all, but is i... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001722239_python.txt |
Q:
Multiple programs using the same UDP port? Possible?
I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of se... | Multiple programs using the same UDP port? Possible? | I currently have a small Python script that I'm using to spawn multiple executables, (voice chat servers), and in the next version of the software, the servers have the ability to receive heartbeat signals on the UDP port. (There will be possibly thousands of servers on one machine, ranging from ports 7878 and up)
My p... | [
"This isn't possible. What you'll have to do is have one UDP master program that handles all UDP communication over the one port, and communicates with your servers in another way (UDP on different ports, named pipes, ...)\n",
"I'm pretty sure this is possible on Linux; I don't know about other UNIXes.\nThere are... | [
2,
1
] | [] | [] | [
"communication",
"daemon",
"ports",
"python",
"udp"
] | stackoverflow_0001722993_communication_daemon_ports_python_udp.txt |
Q:
python function slowing down for no apparent reason
I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP
def compareLists(list1, list2):
curIndex = 0
while curIndex < len(list1):
if list1[curIndex] i... | python function slowing down for no apparent reason | I have a python function defined as follows which i use to delete from list1 the items which are already in list2. I am using python 2.6.2 on windows XP
def compareLists(list1, list2):
curIndex = 0
while curIndex < len(list1):
if list1[curIndex] in list2:
list1.pop(curIndex)
else:
... | [
"Try a more pythonic approach to the filtering, something like\n[x for x in list1 if x not in set(list2)]\n\nConverting both lists to sets is unnessescary, and will be very slow and memory hungry on large amounts of data.\nSince your data is a list of lists, you need to do something in order to hash it.\nTry out\nl... | [
12,
3,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001723494_python.txt |
Q:
Get django-paypal working with pycrypto?
I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.
C... | Get django-paypal working with pycrypto? | I would like to use the button encryption in django-paypal, but it requires M2Crypto which will not build on webfaction servers. Tech support at Webfaction told me that pycrypto is already installed on the system, but I am too dumb to translate from M2Crypto to pycrypto.
Can anyone tell me how to convert the following... | [
"I was able to get it to build. Here is all you need to do to make it happen:\ncat >> ~/.pydistutils.cfg << EOF\n[build_ext]\ninclude_dirs=/usr/include/openssl\nEOF\neasy_install-2.5 --install-dir=$HOME/lib/python2.5 --script-dir=$HOME/bin m2crypto\n\n",
"pycrypto is very incomplete. It does not support the padd... | [
2,
1,
0
] | [] | [] | [
"django",
"encryption",
"paypal",
"python"
] | stackoverflow_0001485903_django_encryption_paypal_python.txt |
Q:
Django unit testing - Why can't I just run ./tests.py on myApp?
So I'm very familiar with manage.py test myapp. But I can't figure out how to make my tests.py work as an stand-alone executable. You may be wondering why I would want to do this.. Well I'm working (now) in Eclipse and I can't seem to figure out how... | Django unit testing - Why can't I just run ./tests.py on myApp? | So I'm very familiar with manage.py test myapp. But I can't figure out how to make my tests.py work as an stand-alone executable. You may be wondering why I would want to do this.. Well I'm working (now) in Eclipse and I can't seem to figure out how to set up the tool to simply run this command. Regardless it would ... | [
"You could create an \"External Tool\" configuration for your project, such as:\nLocation: ${project_loc}/src/${project_name}/manage.py\nWorking Directory: ${project_loc}/src/${project_name}/\nArguments: test ${string_prompt}\n\nThis will run manage.py test <whatever name you type in the string prompt>.\nThe values... | [
1
] | [
"a. this should be the first line at your code file (tests.py)\n#!/usr/bin/env python\n\nb. run $ chmod +x tests.py \n"
] | [
-1
] | [
"django",
"eclipse",
"pydev",
"python",
"unit_testing"
] | stackoverflow_0001719883_django_eclipse_pydev_python_unit_testing.txt |
Q:
aspect-oriented techniques in python?
So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:
I have a bunch of modules, each of which has a bunch of functions.
I have an executable that calls some set of functions in those modules.
When the... | aspect-oriented techniques in python? | So I have an interesting problem in Python, that could possibly be solved with aspect-oriented techniques. Here's the situation:
I have a bunch of modules, each of which has a bunch of functions.
I have an executable that calls some set of functions in those modules.
When the executable calls one of those functions, I... | [
"Modify the behavior of the functions in the executable can be done using a decorator:\n#!/usr/bin/env python\nfrom module1 import foo\nfrom module2 import bar\n\ndef trace(f):\n def tracewrapper(*arg, **kw):\n arg_str=','.join(['%r'%a for a in arg]+['%s=%s'%(key,kw[key]) for key in kw])\n print \"... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001723849_python.txt |
Q:
Referencing classes in Python
I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.
The following won't work!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem =... | Referencing classes in Python | I'm having a spot of bother with Python (using for app engine). I'm fairly new to it (more used to Java), but I had been enjoying....until now.
The following won't work!
class SomeClass(db.Model):
item = db.ReferenceProperty(AnotherClass)
class AnotherClass(db.Model):
otherItem = db.ReferenceProperty(SomeClass)
A... | [
"One way to view the \"class\" keyword in Python is as simply creating a new named scope during the initial execution of your script. So your code throws a NameError: name 'AnotherClass' is not defined exception because Python hasn't executed the class AnotherClass(db.Model): line yet when it executes the self.ite... | [
6,
1
] | [] | [] | [
"class",
"definition",
"google_app_engine",
"python"
] | stackoverflow_0001724316_class_definition_google_app_engine_python.txt |
Q:
Trace/BPT trap when calling urllib.urlopen
For some reason I'm getting a Trace/BPT trap error when calling urllib.urlopen. I've tried both urllib and urllib2 with identical results. Here is the code which throws the error:
def get_url(url):
from urllib2 import urlopen
if not url or not url.startswith('http... | Trace/BPT trap when calling urllib.urlopen | For some reason I'm getting a Trace/BPT trap error when calling urllib.urlopen. I've tried both urllib and urllib2 with identical results. Here is the code which throws the error:
def get_url(url):
from urllib2 import urlopen
if not url or not url.startswith('http://'): return None
return urlopen(url).read(... | [
"Adding the following lines to the top of the main file solved the problem:\nimport urllib2\nurllib2.install_opener(urllib2.build_opener())\n\nIn other words, it is not enough to import the urllib2 module but you actually need to create the opener in the main thread.\n",
"Are you running this under OS X 10.6? App... | [
3,
2
] | [] | [] | [
"python",
"trace",
"urllib",
"urllib2",
"web.py"
] | stackoverflow_0001628916_python_trace_urllib_urllib2_web.py.txt |
Q:
Deleting duplicate dictionaries in a list in python
I have two lists of dictionaries
list1 = [ {..}, {..}, ..]
list2 = [ {..}, {..}, ..]
I want to remove the dictionaries in list1 which are in list2. I had a similar problem where I had a list of lists instead of a dictionary and it is solved here
python function ... | Deleting duplicate dictionaries in a list in python | I have two lists of dictionaries
list1 = [ {..}, {..}, ..]
list2 = [ {..}, {..}, ..]
I want to remove the dictionaries in list1 which are in list2. I had a similar problem where I had a list of lists instead of a dictionary and it is solved here
python function slowing down for no apparent reason
If I use the same cod... | [
"You can't use dicts in sets because they're mutable and don't have stable identities. You can work around that by making a tuple out of their items. Note that simply wrapping a dict in a tuple doesn't get around the fact that distinct dicts will still appear to be distinct objects even if they contain the same ite... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0001724588_python.txt |
Q:
Exclude on a many-to-many relationship through a third table
I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:
class Project... | Exclude on a many-to-many relationship through a third table | I have a problem making "exclude" querys on tables which have a many-to-many relationship through a third table. I have a table with projects, a table with people and a relationsship table with the flags "is_green, is_yellow, is_red", like:
class Project(models.Model):
...
class Person(models.Model):
projects ... | [
"Maybe this? (untested)\nPerson.objects.exclude(id__in=Person.objects.filter(project=p, status__is_red=True).values(id))\n\n",
"If you have a list of Status objects called 'objects', you can use\n[s.person for s in objects]\n\nto make it into a list of the corresponding Persons.\n"
] | [
4,
0
] | [] | [] | [
"django",
"many_to_many",
"python"
] | stackoverflow_0001724317_django_many_to_many_python.txt |
Q:
How can I use PHP's gettext in conjunction with python's gettext?
I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., "Hello %1s" in PHP vs. "Hello {0}" or "Hello {name}" in Python.
We'll be maintaining both apps for a while, but is there a way to use t... | How can I use PHP's gettext in conjunction with python's gettext? | I have an app that I'm migrating portions of to Django, but Python and PHP have a different string format, e.g., "Hello %1s" in PHP vs. "Hello {0}" or "Hello {name}" in Python.
We'll be maintaining both apps for a while, but is there a way to use the Python format in PHP or vice versa?
| [
"PHP's gettext doesn't expand/substitute %s - this is done by output functions (e.g. printf).\nIt also appears to be the case in Python.\nMost importantly, in Python you can use %s to represent strings, see http://docs.python.org/library/stdtypes.html#string-formatting\nSo you should be able to use %s-style strings... | [
0,
0
] | [] | [] | [
"gettext",
"php",
"python"
] | stackoverflow_0001724629_gettext_php_python.txt |
Q:
Just curious about result from NumPy function!
I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:
m = numpy.ones((10,2))
m[:,0]
which returns:
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
and when I ref to:
m... | Just curious about result from NumPy function! | I have used NumPy for my Master thesis. I've converted parts of the code from MATLAB code, but I have doubts in NumPy/Python when I reference:
m = numpy.ones((10,2))
m[:,0]
which returns:
array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
and when I ref to:
m[:,0:1]
it returns:
array([[ 1.],
[ 1.],
... | [
"This is because numpy has the concept of 1d arrays which Matlab doesn't have. Coupled with numpys broadcasting this provides a powerful simplification (less worrying about inserting transposes everywhere) but does mean you have to think a little bit about translating from Matlab. In this case, extracting a single ... | [
5,
3,
0
] | [] | [] | [
"matlab",
"numpy",
"python"
] | stackoverflow_0001724504_matlab_numpy_python.txt |
Q:
TypeError when trying to upload Pictures from Google App Engine to Picasa with the GData API
I'm trying to write a small tool to upload Pictures from Google App Engine to Picasa. Fetching the image works, but when i try to upload it i get the error "TypeError: stat() argument 1 must be (encoded string without NULL... | TypeError when trying to upload Pictures from Google App Engine to Picasa with the GData API | I'm trying to write a small tool to upload Pictures from Google App Engine to Picasa. Fetching the image works, but when i try to upload it i get the error "TypeError: stat() argument 1 must be (encoded string without NULL bytes), not str"
The Code basically looks like this:
def getfile(url):
result = urlfetch.fet... | [
"The Solution to this problem was using StringIO :-)\n( http://docs.python.org/library/stringio.html )\nadding\npic = StringIO.StringIO(pic)\n\nconverts the result.content from urlfetch into a file-like format gdata expects.\n"
] | [
5
] | [] | [] | [
"gdata_api",
"google_app_engine",
"picasa",
"python",
"typeerror"
] | stackoverflow_0001715574_gdata_api_google_app_engine_picasa_python_typeerror.txt |
Q:
Given a list of slices, how do I split a sequence by them?
Given a list of slices, how do I separate a sequence based on them?
I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:
str = "MSEPAGDVRQNPCGSKAC"
split... | Given a list of slices, how do I split a sequence by them? | Given a list of slices, how do I separate a sequence based on them?
I have long amino-acid strings that I would like to split based on start-stop values in a list. An example is probably the most clear way of explaining it:
str = "MSEPAGDVRQNPCGSKAC"
split_points = [[1,3], [7,10], [12,13]]
output >> ['M', '(SEP)', 'AG... | [
"Strange way to split strings you have there:\ndef splitter( s, points ):\n c = 0\n for x,y in points:\n yield s[c:x]\n yield \"(%s)\" % s[x:y+1]\n c=y+1\n yield s[c:]\n\nprint list(splitter(str, split_points))\n# => ['M', '(SEP)', 'AGD', '(VRQN)', 'P', '(CG)', 'SKAC']\n\n# if some sta... | [
9,
2,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001724675_python.txt |
Q:
Lxml html xpath context
I'm using lxml to parse a HTML file and I'd like to know how can I set the context of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search //input return only in... | Lxml html xpath context | I'm using lxml to parse a HTML file and I'd like to know how can I set the context of xpath search. What I mean I that I have a node element and want to make xpath search only inside this node as if it was the root one. For example, I have a form node and xpath search //input return only inputs of the given form as opp... | [
"XPath expression //input will match all input elements, anywhere in your document, while .//input will match all inside current context.\nMaybe if you improve your scenario description we can help you further.\n"
] | [
12
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0001725268_lxml_python_xpath.txt |
Q:
Python Unit Tests - Am I using SetUp wrong?
What am I doing wrong here?
import unittest
class Test_1(unittest.TestCase):
def SetUp(self):
self.data = []
def test_data(self):
self.assertEqual(len(self.data),0)
if __name__=='__main__':
unittest.main()
When I run it, it says:
Traceba... | Python Unit Tests - Am I using SetUp wrong? | What am I doing wrong here?
import unittest
class Test_1(unittest.TestCase):
def SetUp(self):
self.data = []
def test_data(self):
self.assertEqual(len(self.data),0)
if __name__=='__main__':
unittest.main()
When I run it, it says:
Traceback (most recent call last):
File "C:...\break_u... | [
"It must be named setUp, starting with a lowercase s.\n"
] | [
5
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0001725366_python_unit_testing.txt |
Q:
How do I strip a character in Django admin after submission before sending value to dB?
I'm more comfortable with PHP & MySQL, don't know a lick of Python (yet) except for the teeny tiny bit I picked up using the Django admin recently...therefore please excuse this very stupid question that I'm embarrassed to ask.... | How do I strip a character in Django admin after submission before sending value to dB? | I'm more comfortable with PHP & MySQL, don't know a lick of Python (yet) except for the teeny tiny bit I picked up using the Django admin recently...therefore please excuse this very stupid question that I'm embarrassed to ask. In PHP this would be trivial for me...
I'm using a color picker (farbtastic) w/ Django Admin... | [
"Usually, you do a customized form to clean the data properly. It seems (at first) like overkill, but it's a very general solution.\nYou have to (1) define the modified Form, and then (2) bind the modified Form into the Admin interface.\nOn the other hand, you might be able to do this in the model's save method, w... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001725175_django_python.txt |
Q:
How to check if a list is empty in Python?
The API I'm working with can return empty [] lists.
The following conditional statements aren't working as expected:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
What will work?
A:
if not myList:
print "Nothing here"
A:
I... | How to check if a list is empty in Python? | The API I'm working with can return empty [] lists.
The following conditional statements aren't working as expected:
if myList is not None: #not working
pass
if myList is not []: #not working
pass
What will work?
| [
"if not myList:\n print \"Nothing here\"\n\n",
"I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:\nif len(my_list) == 0:\n print \"my_list is empty\"\n\n",
"Empty lists evaluate to False in boolean contexts (such as if some_list:).\n"
] | [
207,
21,
19
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001725517_list_python.txt |
Q:
Working with JSON in Python 2.6?
I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.
I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterat... | Working with JSON in Python 2.6? | I'm really new to Python, but I've picked a problem that actually pertains to work and I think as I figure out how to do it I'll learn along the way.
I have a directory full of JSON-formatted files. I've gotten as far as importing everything in the directory into a list, and iterating through the list to do a simple pr... | [
"What you get when you json.load a file containing the JSON form of a Javascript object such as {'abc': 'def'} is a Python dictionary (normally and affectionately called a dict) (which in this case happens to have the same textual representation as the Javascript object).\nTo access a specific item, you use indexin... | [
11
] | [
"To access all properties, try eval() statement before append a list.\nlike:\nimport os\n\n#define path to reports\nreportspath = \"reports/\"\n\n# Gets all json files and imports them\n\ndir = os.listdir(reportspath)\n\n\nfor fname in dir:\n json = eval(open(fname).read())\n # now, json is a normal python ob... | [
-1
] | [
"json",
"python"
] | stackoverflow_0001725682_json_python.txt |
Q:
time.sleep and suspend (ie. standby and hibernate)
For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?
If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibern... | time.sleep and suspend (ie. standby and hibernate) | For example, if I do time.sleep(100) and immediately hibernate my computer for 99 seconds, will the next statement be executed in 1 second or 100 seconds after waking up?
If the answer is 1 second, how do you "sleep" 100 seconds, regardless of the length of hibernate/standby?
| [
"time.sleep(N) attempts to sleep at least N seconds of elapsed, AKA \"wall-clock\" time - of course there can be no guarantee that the sleep will last exactly N seconds; for example, the thread becomes ready to execute again at that time, but it cannot necessarily preempt whatever other thread is executing at that ... | [
5,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0001725758_python.txt |
Q:
CherryPy3 and IIS 6.0
I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers.
I got Cherrypy working with Apache using mod_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site.
The site runs perfectly as a st... | CherryPy3 and IIS 6.0 | I have a small Python web application using the Cherrypy framework. I am by no means an expert in web servers.
I got Cherrypy working with Apache using mod_python on our Ubuntu server. This time, however, I have to use Windows 2003 and IIS 6.0 to host my site.
The site runs perfectly as a stand alone server - I am jus... | [
"I run CherryPy behind my IIS sites. There are several tricks to get it to work.\n\nWhen running as the IIS Worker Process identity, you won't have the same permissions as you do when you run the site from your user process. Things will break. In particular, anything that wants to write to the file system will prob... | [
10,
2
] | [] | [] | [
"cherrypy",
"iis_6",
"isapi_wsgi",
"python"
] | stackoverflow_0001677828_cherrypy_iis_6_isapi_wsgi_python.txt |
Q:
How to connect to a GObject signal in python, without it keeping a reference to the connecter?
The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:
class ClipboardMonitor (object):
def __init__(self):
clip = gtk.clipboard_get(gtk... | How to connect to a GObject signal in python, without it keeping a reference to the connecter? | The problem is basically this, in python's gobject and gtk bindings. Assume we have a class that binds to a signal when constructed:
class ClipboardMonitor (object):
def __init__(self):
clip = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)
clip.connect("owner-change", self._clipboard_changed)
The problem is ... | [
"The standard way is to disconnect the signal. This however needs to have a destructor-like method in your class, called explicitly by code which maintains your object. This is necessary, because otherwise you'll get circular dependency.\nclass ClipboardMonitor(object):\n [...]\n\n def __init__(self):\n ... | [
10,
1,
1
] | [] | [] | [
"pygobject",
"pygtk",
"python"
] | stackoverflow_0001364923_pygobject_pygtk_python.txt |
Q:
Get functions called in a Python expression
I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the dat... | Get functions called in a Python expression | I have a database that holds the name of Python functions and a string for their code. I want the user to be able to enter a Python code and see the result. The problem is that I need to know the names of the functions they call in order to retrieve the code from the database. For instance, if they enter cubic_fit(1, 2... | [
"The built-in function compile will do that for you exactly:\n>>> compile(\"cubic_fit(1, 2, get_data())\", '<string>', 'eval').co_names\n('cubic_fit', 'get_data')\n\nAnd it is safe to run. No code is actually being executed just compiled.\n",
"A quick example to you started. Note that you'll be expecting valid py... | [
11,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0001726251_python.txt |
Q:
python stdin eof
How to pass python eof to stdin
here is my code
p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE)
o = p.communicate(inputstring)[0]
when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input.
How can I pass eof or Ctrl+Z in p... | python stdin eof | How to pass python eof to stdin
here is my code
p = Popen(commd,stdout=PIPE,stderr=PIPE,stdin=PIPE)
o = p.communicate(inputstring)[0]
when i run the commd in command line after i input the inputstring windows still expecting a Ctrl+Z to finish accepting input.
How can I pass eof or Ctrl+Z in program?
Thanks!
| [
"p.stdin.close()\n\nafter p.communicate, finishes the input and sends EOF to commd.\n"
] | [
9
] | [] | [] | [
"eof",
"python",
"stdin"
] | stackoverflow_0001726590_eof_python_stdin.txt |
Q:
programmatically determine if an evaluation of a function is being assigned?
I would like to do this:
def foo():
if <a magical condition>:
return x
else:
poof()
# or...
def foo():
x = <a magical object>
return x
def poof():
print 'poof!'
bar = foo() # bar points to <a magica... | programmatically determine if an evaluation of a function is being assigned? | I would like to do this:
def foo():
if <a magical condition>:
return x
else:
poof()
# or...
def foo():
x = <a magical object>
return x
def poof():
print 'poof!'
bar = foo() # bar points to <a magical object> but poof() is not called
foo() # prints 'poof!'
I guess it comes down ... | [
"I'm pretty confused by your question, but I think what you are trying to do is run a function when a value is reassigned.\nInstead of doing tricky things with a __del__() method function, I suggest you just put your value into a class instance, and then overload __setattr__(). You could also overload __delattr__(... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0001726655_python.txt |
Q:
Unzip part of a file using python gzip module
I am trying to unzip a gzipped file in Python using the gzip module. The pre-condition is that, I get 160 bytesof data at a time, and I need to unzip it before I request for the next 160 bytes. Partial unzipping is OK, before requesting the next 160 bytes. The code I h... | Unzip part of a file using python gzip module | I am trying to unzip a gzipped file in Python using the gzip module. The pre-condition is that, I get 160 bytesof data at a time, and I need to unzip it before I request for the next 160 bytes. Partial unzipping is OK, before requesting the next 160 bytes. The code I have is
import gzip
import time
import StringIO
fil... | [
"Create your own class with a read() method (and whatever else GzipFile needs from fileobj, like close and seek) and pass it to GzipFile. Something like:\nclass MyBuffer(object):\n def __init__(self, input_file):\n self.input_file = input_file\n\n def read(self, size=-1):\n if size < 0:\n size = 160\n ... | [
4
] | [] | [] | [
"gzip",
"python",
"unzip"
] | stackoverflow_0001726696_gzip_python_unzip.txt |
Q:
How to split the file content by space and end-of-line character?
When I do the following list comprehension I end up with nested lists:
channel_values = [x for x in [ y.split(' ') for y in
open(channel_output_file).readlines() ] if x and not x == '\n']
Basically I have a file composed of this:
7656 7653 7649... | How to split the file content by space and end-of-line character? | When I do the following list comprehension I end up with nested lists:
channel_values = [x for x in [ y.split(' ') for y in
open(channel_output_file).readlines() ] if x and not x == '\n']
Basically I have a file composed of this:
7656 7653 7649 7646 7643 7640 7637 7634 7631 7627 7624 7621 7618 7615
8626 8623 8620 ... | [
"You don't need list comprehensions for this:\nchannel_values = open(channel_output_file).read().split()\n\n",
"Just do this:\nchannel_values = open(channel_output_file).read().split()\n\nsplit() will split according to whitespace that includes ' ' '\\t' and '\\n'. It will split all the values into one list.\nIf ... | [
17,
7,
2,
1,
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0001724080_list_comprehension_python.txt |
Q:
How can I use Facebook Connect with Google App Engine without using Django?
I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Goog... | How can I use Facebook Connect with Google App Engine without using Django? | I'm developing on the Google App Engine and I would like to integrate Facebook Connect into my site as a means for registering and authenticating. In the past, I relied on Google's Accounts API for user registration. I'm trying to use Google's webapp framework instead of Django but it seems that all the resources regar... | [
"It's not Facebook Connect, really, but at least it's webapp FBML handling:\nhttp://github.com/WorldMaker/pyfacebook/.../facebook/webappfb.py\nThis guy made a post about Facebook Connect on Google AppEngine via webapp framework. (It's stickied in the Connect Authentication forum, with 8515 views.)\nHere's an exampl... | [
10,
4,
1
] | [] | [] | [
"authentication",
"facebook",
"google_app_engine",
"python"
] | stackoverflow_0001183863_authentication_facebook_google_app_engine_python.txt |
Q:
Returning array of data mapping values to parameters in python
I have a few functions that return an array of data corresponding to parameters ranges.
Example: for a 2d array a, the a_{ij} value corresponds to the parameter set (param1_i, param2_j). How do I return the result and keep the parameter-value correspon... | Returning array of data mapping values to parameters in python | I have a few functions that return an array of data corresponding to parameters ranges.
Example: for a 2d array a, the a_{ij} value corresponds to the parameter set (param1_i, param2_j). How do I return the result and keep the parameter-value correspondence?
Calling the function for each and every of param1_i, para2_j... | [
"I recommend your last suggestion... just return two arrays {'values': a, 'params':params}.\nThere are a few reasons for this. \n\nPrimarily, your other solution (using dtype and recarrays) tangles too many things together. For example, what about quantities derived from a that correspond to the same parameters..... | [
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0001726750_arrays_numpy_python.txt |
Q:
Sorting a 3 parallel list that includes strings and numeric value in Python
how to sort using 3 parallel array lists:
num1 = ['a','b','c,']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
I used 2 for statements followed by a if statement. Sorting by elements the output should be:
a apple 2.5
b ... | Sorting a 3 parallel list that includes strings and numeric value in Python | how to sort using 3 parallel array lists:
num1 = ['a','b','c,']
num2 = ['apple','pear','grapes']
num3 = [2.5,4.0,.68]
I used 2 for statements followed by a if statement. Sorting by elements the output should be:
a apple 2.5
b pear 4.0
c grapes .68
unfortunately, I am having issues with so... | [
"Since you say the lists are parallel, let's group them into tuples, and then sort the list of tuples.\nnum1 = ['a','b','c']\nnum2 = ['apple','pear','grapes']\nnum3 = [2.5,4.0,.68]\n\nlst = zip(num1, num2, num3)\nlst.sort()\n\nfor x1, x2, x3 in lst:\n print x1, x2, x3,\n\nprint\n\nThe result is:\na apple 2.5 b p... | [
2,
1
] | [] | [] | [
"list",
"parallel_processing",
"python",
"sorting"
] | stackoverflow_0001726865_list_parallel_processing_python_sorting.txt |
Q:
how to install python-spidermonkey on windows
I'm writing some scripts with python mechanize. One of problems I'm having is it is really hard to find which support javascript supported web client scraping or crawler. I found some such as python-spidermonkey and pykhtml, but most are only supported on Linux.
I want... | how to install python-spidermonkey on windows | I'm writing some scripts with python mechanize. One of problems I'm having is it is really hard to find which support javascript supported web client scraping or crawler. I found some such as python-spidermonkey and pykhtml, but most are only supported on Linux.
I want to make my python script with exe file, so definit... | [] | [] | [
"Both these links: http://code.google.com/p/python-spidermonkey/issues/detail?id=5 and http://www.ohloh.net/p/python-spidermonkey say that Spedermonkey is not supported for Windows... yet.\nAs far as I can tell, PyKHTML is not out for Windows yet, but \"support for Windows/Mac should appear in the next few months.\... | [
-1
] | [
"python"
] | stackoverflow_0001727157_python.txt |
Q:
Can a python module have a __repr__?
Can a python module have a __repr__? The idea would be to do something like:
import mymodule
print mymodule
EDIT: precision: I mean a user-defined repr!
A:
Short answer: basically the answer is no.
But can't you find the functionality you are looking for using docstrings?
te... | Can a python module have a __repr__? | Can a python module have a __repr__? The idea would be to do something like:
import mymodule
print mymodule
EDIT: precision: I mean a user-defined repr!
| [
"Short answer: basically the answer is no.\nBut can't you find the functionality you are looking for using docstrings?\ntestmodule.py\n\"\"\" my module test does x and y\n\"\"\"\nclass myclass(object):\n ...\n\ntest.py\nimport testmodule\nprint testmodule.__doc__\n\nLong answer:\nYou can define your own __repr__... | [
10,
9,
6,
2,
1
] | [] | [] | [
"module",
"python"
] | stackoverflow_0001725515_module_python.txt |
Q:
Log all errors to console or file on Django site
How can I get Django 1.0 to write all errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process_exception function as described in the accepted answer to this question:
How do you log server errors o... | Log all errors to console or file on Django site | How can I get Django 1.0 to write all errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process_exception function as described in the accepted answer to this question:
How do you log server errors on django sites
The process_exception function is calle... | [
"It's a bit extreme, but for debugging purposes, you can turn on the DEBUG_PROPAGATE_EXCEPTIONS setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override sys.excepthook. This will terminate your application, but it will work. There may be ... | [
13,
6,
2,
1
] | [
"If you are on a *nix system you could \nwrite to a log (eg. mylog.txt) in python\nthen run \"tail -f mylog.txt\" in the console\nthis is a handy way to view any kind of log in near real time\n"
] | [
-1
] | [
"django",
"facebook",
"python"
] | stackoverflow_0000690723_django_facebook_python.txt |
Q:
Implement OpenID in Python
How should I implement OpenID in Python using the OpenID API?
A:
For hassle free installation of openid use the RPX
The installation is quite simple. visit the website for more details. You will be able to understand it very easily.
| Implement OpenID in Python | How should I implement OpenID in Python using the OpenID API?
| [
"For hassle free installation of openid use the RPX\nThe installation is quite simple. visit the website for more details. You will be able to understand it very easily.\n"
] | [
3
] | [] | [] | [
"openid",
"python"
] | stackoverflow_0001727429_openid_python.txt |
Q:
Finding the correct Python framework with cmake
I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt
include(FindPythonInterp)
i... | Finding the correct Python framework with cmake | I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt
include(FindPythonInterp)
include(FindPythonLibs )
However, while cmake identi... | [
"Adding the following in ~/.bash_profile\nexport DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks\n\nfixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefully fixed in the new version.\n",
"I am n... | [
5,
1
] | [] | [] | [
"cmake",
"frameworks",
"macos",
"macports",
"python"
] | stackoverflow_0001718251_cmake_frameworks_macos_macports_python.txt |
Q:
Classify array of strings based on commonalities
I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this
"AB 500"
"Bus AB 500"
"News CA"
"News CA BLAH"
My plan was
a. T... | Classify array of strings based on commonalities | I have huge list (200000) of strings (multi word). I want to group these strings based on comman array of word match among these strings. I cant think of a low computation time algorithm for this
"AB 500"
"Bus AB 500"
"News CA"
"News CA BLAH"
My plan was
a. Tokenize them to words.
b. Create a global array tokens... | [
"200000 is not that much, you can do this\n\nSplit each string to get tokens\ne.g. \"News CA BLAH\" -> [\"Blah\", \"CA\", \"News\"]\ncreate a dict entry each length of list e.g. in case of [\"Blah\", \"CA\", \"News\"] all combinations in order\nNow just loop thru the dict and see the groups\n\nexample code:\ndata=\... | [
2,
1,
1,
0
] | [] | [] | [
"algorithm",
"classification",
"python",
"string"
] | stackoverflow_0001719865_algorithm_classification_python_string.txt |
Q:
Seeking a High-Level Library for Socket Programming (Java or Python)
In short I'm creating a Flash based multiplayer game and I'm now starting to work on the server-side code. Well I'm the sole developer of the project so I'm seeking a high-level socket library that works well with games to speed up my developmen... | Seeking a High-Level Library for Socket Programming (Java or Python) | In short I'm creating a Flash based multiplayer game and I'm now starting to work on the server-side code. Well I'm the sole developer of the project so I'm seeking a high-level socket library that works well with games to speed up my development time.
I was trying to use the Twisted Framework (for Python) but I'm hav... | [
"An option for Python is the Concurrence framework. I used it fairly recently, in conjunction with Stackless Python, to simulate an environment in which there were potentially thousands of requests per second, each of which had to be processed in less than 2 seconds. The API is very straightforward and is well docu... | [
7,
0,
0,
0
] | [] | [] | [
"java",
"python",
"sockets"
] | stackoverflow_0001728266_java_python_sockets.txt |
Q:
Chat server with Twisted framework in python can't receive data from flash client
I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear...
(the flash client work find with my old php chat server, I rewrote the server in p... | Chat server with Twisted framework in python can't receive data from flash client | I've develop a chat server using Twisted framework in Python. It works fine with a Telnet client. But when I use my flash client problem appear...
(the flash client work find with my old php chat server, I rewrote the server in python to gain performance)
The connexion is establish between the flash client and the... | [
"Changing LineOnlyReceiver.delimiter is a pretty bad idea, since that changes the delivery for all instances of LineOnlyReceiver (unless they've changed it themselves on a subclass or on the instance). If you ever happen to use any such code, it will probably break.\nYou should change delimiter by setting it on yo... | [
1,
0
] | [] | [] | [
"flash",
"python",
"twisted"
] | stackoverflow_0001489931_flash_python_twisted.txt |
Q:
How to remove unique, then duplicate dictionaries in a list?
Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single instances? I gotta say I only recently started getting into ... | How to remove unique, then duplicate dictionaries in a list? | Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single instances? I gotta say I only recently started getting into Python but its making this project so much easier. I'm just a bit ... | [
"One idea is to sort the data. Assume inputdata is your list from above:\nfrom itertools import groupby\nfrom operator import itemgetter\n\ninputdata.sort(key=itemgetter(*inputdata[0])) # ensures order\nprint [k for k, g in groupby(inputdata) if len(list(g)) > 1]\n\nprints:\n[{'line': u'line 666', 'file': u'/file.t... | [
4,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0001726925_dictionary_list_python.txt |
Q:
list management python
I have extracted some url list and want to manipulate this list. Following is extracted list sample:
http://help.naver.com/service/svc_index.jsp?selected_nodeId=NODE0000000235
http://www.naver.com/rules/service.html
http://news.naver.com/main/principle.nhn
http://www.naver.com/rules/privacy.... | list management python | I have extracted some url list and want to manipulate this list. Following is extracted list sample:
http://help.naver.com/service/svc_index.jsp?selected_nodeId=NODE0000000235
http://www.naver.com/rules/service.html
http://news.naver.com/main/principle.nhn
http://www.naver.com/rules/privacy.html
http://www.naver.com/ru... | [
"If your old list is contains all urls as strings you can use a list comprehension to filter them.\nnew = [url for url in old if url.startswith('http://www.naver.com')]\n\nYou could write it as a explicit loop, but it adds nothing but lines of code:\nnew = []\nfor url in old:\n if url.startswith('http://www.naver... | [
6,
2,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001730261_python.txt |
Q:
Multiple grids on matplotlib
I'm making plots in Python and matplotlib, which I found huge and flexible, till now.
The only thing I couldn't find how to do, is to make my plot have multiple grids.
I've looked into the documentation, but that's just for line style...
I'm thinking on something like two plots each on... | Multiple grids on matplotlib | I'm making plots in Python and matplotlib, which I found huge and flexible, till now.
The only thing I couldn't find how to do, is to make my plot have multiple grids.
I've looked into the documentation, but that's just for line style...
I'm thinking on something like two plots each one with a different grid, which wil... | [
"How about something like this (adapted from here):\nfrom pylab import *\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\nt = arange(0.0, 100.0, 0.1)\ns = sin(0.1*pi*t)*exp(-t*0.01)\n\nax = subplot(111)\nplot(t,s)\n\nax.xaxis.set_major_locator(MultipleLocator(20))\nax.xaxis.set_major_formatter(... | [
32
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0001729995_matplotlib_python.txt |
Q:
Pack program *and* dynamically loaded files into single executable? (python + pygame, or language agnostic)
There are plenty of great answers to questions about making a standalone executable, but I can't figure out how to pack art assets (or dynamically loaded files) into it as well. Why would I want to do this?... | Pack program *and* dynamically loaded files into single executable? (python + pygame, or language agnostic) | There are plenty of great answers to questions about making a standalone executable, but I can't figure out how to pack art assets (or dynamically loaded files) into it as well. Why would I want to do this? Because it would be great to distribute a simple (throw away) game that lives entirely in a single executable w... | [
"Game development is not field of expertise, but if you haven't already checked out py2exe, I would strongly recommend that you do. It seems to me that any and all scripting import statements will be taken care of by py2exe.\nHope this helps\n"
] | [
2
] | [] | [] | [
"executable",
"packaging",
"pygame",
"python"
] | stackoverflow_0001730742_executable_packaging_pygame_python.txt |
Q:
gqlQuery returns object, want list of keys
Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys? For example:
items = db.GqlQuery("SELECT __key__ FROM Items")
returns an object containing the keys:
<google.appengine.ext.db.GqlQuery ob... | gqlQuery returns object, want list of keys | Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys? For example:
items = db.GqlQuery("SELECT __key__ FROM Items")
returns an object containing the keys:
<google.appengine.ext.db.GqlQuery object at 0x0415E210>
I need to compare it to an ... | [
"Certainly - you can fetch the results by calling .fetch(count) on the GqlQuery object. This is the recommended way, in fact - iterating fetches results in batches, and so is less efficient.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0001730694_google_app_engine_gql_python.txt |
Q:
A server side component for tracking a large number of RSS & Atom feeds
I am looking for an open source component that can help me track a large number of RSS feeds (>> 10K RSS sources).
I don't care about the programming language, but it should be something with a simple API where I can add or remove RSS feeds an... | A server side component for tracking a large number of RSS & Atom feeds | I am looking for an open source component that can help me track a large number of RSS feeds (>> 10K RSS sources).
I don't care about the programming language, but it should be something with a simple API where I can add or remove RSS feeds and asynchronously receive notifications every time an RSS is updated.
Preferab... | [
"I found this site. Most of these seem to be client apps but some listed APIs. Not sure if there's something here for you. http://java-source.net/open-source/rss-rdf-tools\n"
] | [
0
] | [] | [] | [
"atom_feed",
"java",
"python",
"rss"
] | stackoverflow_0001710718_atom_feed_java_python_rss.txt |
Q:
Python code to accept many different formats of US phone numbers?
I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:
5555555555
555-555-5555
555-555/5555
1555-555-5555
etc...
How could I easily parse in all of these phone numbers in Py... | Python code to accept many different formats of US phone numbers? | I'm reading in lots of user entered data that represent phone numbers from files. They are all slightly entered in differently:
5555555555
555-555-5555
555-555/5555
1555-555-5555
etc...
How could I easily parse in all of these phone numbers in Python and produce a canonical output like:
555-555-5555?
| [
"Dive into Python has a section on parsing phone numbers\nhttp://www.diveintopython.org/regular_expressions/phone_numbers.html\n",
"I'm not american, but this works with russian phone numbers... maybe it applies to american ones too?\n\nDiscard all non-number characters\nValidate amount of the numbers left\nInser... | [
9,
6,
4,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0001731025_python.txt |
Q:
Is there an existing Python class that can hold any user attributes?
I can use this when I need multiple objects with different attributes:
class struct(object):
def __init__(self,*args,**kwargs):
for key,val in kwargs.items():
setattr(self,key,val)
But I'm wondering if there isn't a built-in al... | Is there an existing Python class that can hold any user attributes? | I can use this when I need multiple objects with different attributes:
class struct(object):
def __init__(self,*args,**kwargs):
for key,val in kwargs.items():
setattr(self,key,val)
But I'm wondering if there isn't a built-in already?
| [
"Unless I'm not understanding your question, isn't this what we use a dict for? Sure, it's notationally slightly different, but an object's attributes are internally still stored in a dict (namely __dict__). It's a matter of notation.\nBut, if you insist, then this is one way to do it:\n>>> class struct(dict):\n...... | [
9,
3,
3
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0001730769_python_struct.txt |
Q:
How do I check the HTTP status code of an object without downloading it?
>>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? ... | How do I check the HTTP status code of an object without downloading it? | >>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200
My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it immediately check the error code without saving the file?
| [
"You want to actually tell the server not to send the full content of the file. HTTP has a mechanism for this called \"HEAD\" that is an alternative to \"GET\". It works the same way, but the server only sends you the headers, none of the actual content.\nThat'll save at least one of you bandwidth, while simply not... | [
18,
1,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0001731298_http_python.txt |
Q:
How should unit tests be documented?
I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is be... | How should unit tests be documented? | I'm trying to improve the number and quality of tests in my Python projects. One of the the difficulties I've encountered as the number of tests increase is knowing what each test does and how it's supposed to help spot problems. I know that part of keeping track of tests is better unit test names (which has been addre... | [
"I document most on my unit tests with the method name exclusively:\ntestInitializeSetsUpChessBoardCorrectly()\ntestSuccessfulPromotionAddsCorrectPiece()\n\nFor almost 100% of my test cases, this clearly explains what the unit test is validating and that's all I use. However, in a few of the more complicated test ... | [
17,
15,
4,
0,
0
] | [] | [] | [
"docstring",
"documentation",
"python",
"unit_testing"
] | stackoverflow_0001726622_docstring_documentation_python_unit_testing.txt |
Q:
Getting only one dimension of indexes from the getSelectedIndexes function in QT?
I'm working on a small project in QT (well, pyQT4 actually, but it shouldn't matter too much) and I've run into the following problem. I have a QTableView with several rows and columns. I have set the selection mode to be rows only. ... | Getting only one dimension of indexes from the getSelectedIndexes function in QT? | I'm working on a small project in QT (well, pyQT4 actually, but it shouldn't matter too much) and I've run into the following problem. I have a QTableView with several rows and columns. I have set the selection mode to be rows only. When I call getSelectedIndexes() on my QTableView, I get an index for every row and col... | [
"The selection is maintained by QItemSelectionModel, which provides a method called selectedRows() that does what you want. For example:\nmyTableView->selectionModel()->selectedRows()\n\n"
] | [
4
] | [] | [] | [
"indexing",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0001731272_indexing_pyqt4_python_qt_qt4.txt |
Q:
httplib in Python to get the status code...but it is too tricky?
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
This code will get the HTTP status code. However, notice that I spli... | httplib in Python to get the status code...but it is too tricky? | >>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
This code will get the HTTP status code. However, notice that I split up "google.com" and "/index.html" on 2 lines.
And it's confusing.
Wh... | [
"Maybe you are better off using the URL library instead?\nIn Python 2, use urllib2:\n>>> import urllib2\n>>> url = urllib2.urlopen(\"http://www.google.com/index.html\")\n>>> url.getcode()\n200\n\nIn Python 3, use urllib.request:\n>>> import urllib.request\n>>> url = urllib.request.urlopen(\"http://www.google.com/in... | [
6,
6,
2,
0,
0,
0
] | [] | [] | [
"http",
"http_headers",
"python",
"regex"
] | stackoverflow_0001731657_http_http_headers_python_regex.txt |
Q:
How to play sound till the user hits a key?
First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads.
Is there any proper platform independent way of doing this?
A:
Can you be more specific? This could be done in pygame, but... | How to play sound till the user hits a key? | First thought of implementing this using threads but python doesnt have a way for killing threads. I have read the other topic on killing threads.
Is there any proper platform independent way of doing this?
| [
"Can you be more specific? This could be done in pygame, but you'd need to open a graphical window.\n",
"I think you'd better use a Tk timer for ringing periodically, and then stop it when you get the key press.\nSee http://www.java2s.com/Code/Python/GUI-Tk/Clockevent.htm for an example how to use timer.\nThus yo... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0001731986_python_tkinter.txt |
Q:
Alternatives to wx.lib.masked.NumCtrl
In a wxPython application I'm developing I need a lot of input fields for numbers (integers and floats), so I tried using wx.lib.masked.NumCtrl, but my users now tell me that it's quite uncomfortable to use (and I agree with them).
Is there an alternative widget implementatio... | Alternatives to wx.lib.masked.NumCtrl | In a wxPython application I'm developing I need a lot of input fields for numbers (integers and floats), so I tried using wx.lib.masked.NumCtrl, but my users now tell me that it's quite uncomfortable to use (and I agree with them).
Is there an alternative widget implementation I can use, or should I just roll my own, ... | [
"In the usual wxPython distribution there's IntCtrl, and then a few other GUI controls like Slider, Spin, FloatSpin, and KnobCtrl.\nThere's also the Enthought Traits approach, and the GUI part of this seems to have put a fair amount of focus on numerical entry and display, such as logarithmic sliders, float array e... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001730647_python_wxpython.txt |
Q:
a better way to do ajax in django
The other day I wrote some AJAX for a Django app that i have been working on.
I come from Ruby on Rails, so I haven't done much in the way of raw JS.
So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:
1) JS function ... | a better way to do ajax in django | The other day I wrote some AJAX for a Django app that i have been working on.
I come from Ruby on Rails, so I haven't done much in the way of raw JS.
So based on Rails' partials, I something similar to the following in a sort of pseudocode, don't sweat the details:
1) JS function using prototype's Ajax.Updater ('tabled... | [
"It kinda depends what you want to do I think. Ajax being quite a wide range of scenarios from Google Maps to a simple auto-complete varys greatly in complexity and the best approach.\nHowever, there are some useful things you can do that help.\n1) Template level\nMake sure you have \"django.core.context_processors... | [
5,
4,
3,
1
] | [] | [] | [
"ajax",
"django",
"javascript",
"python"
] | stackoverflow_0001491618_ajax_django_javascript_python.txt |
Q:
wxPython : Problem updating background color of controls
[EDIT - Reduced and re-posted code, restated question]
I would like to change the background color of a frame (or panel; whichever makes it work).
The problem is that the background color of controls on that frame (or panel) don't have their background color... | wxPython : Problem updating background color of controls | [EDIT - Reduced and re-posted code, restated question]
I would like to change the background color of a frame (or panel; whichever makes it work).
The problem is that the background color of controls on that frame (or panel) don't have their background color updated until I click on the control (the slider control, spe... | [
"Try putting a panel in each frame and then putting your controls on the panel. In wxPython, frames don't like to have multiple windows (especially for Windows OS), so it usually helps to have the frame own one panel and the panel to own the other controls.\nIf this doesn't solve the problem, please to to phrase y... | [
1,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001710724_python_wxpython.txt |
Q:
The correct case&format of variable and methods and for Python
So I know some languages have expected conventions.
PHP - underscore_case() [for the most part, lolo]
Java - camelCase()
C# - PascalCase()
etc.
What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wondering if there i... | The correct case&format of variable and methods and for Python | So I know some languages have expected conventions.
PHP - underscore_case() [for the most part, lolo]
Java - camelCase()
C# - PascalCase()
etc.
What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wondering if there is a "best practice" way that most modules are done in.
| [
"Two words: PEP 8.\nPEP 8 is the (de facto) Python style guide. Some highlights from this document (I left some stuff out on purpose; go read the original document for the ins and outs): \n\nPackage and Module Names: All-lowercase names. Underscores can be used in the module name if it improves readability.\nClass ... | [
8,
5,
1
] | [] | [] | [
"camelcasing",
"pascalcasing",
"python"
] | stackoverflow_0001732234_camelcasing_pascalcasing_python.txt |
Q:
Packaging resources with setuptools/distribute
I'm developing an Python egg that has several .txt dependencies (they're templates used to generate files by the egg itself), and I'm struggling to get those dependencies copied to site-packages during setup.py install. According to the distribute documentation...
Fil... | Packaging resources with setuptools/distribute | I'm developing an Python egg that has several .txt dependencies (they're templates used to generate files by the egg itself), and I'm struggling to get those dependencies copied to site-packages during setup.py install. According to the distribute documentation...
Filesystem of my package:
setup.py
package
|--- __init_... | [
"The information can be found in the setuptools documentation for including package data: https://setuptools.readthedocs.io/en/latest/setuptools.html#including-data-files\nBasically, you just need to set include_package_data=True in your setup.py file. If you are using subversion or CVS, all versioned files will b... | [
5
] | [] | [] | [
"distribute",
"pypi",
"python",
"setuptools"
] | stackoverflow_0001732619_distribute_pypi_python_setuptools.txt |
Q:
What is a suitable buffer for Python's struct module
In Python I'm accessing a binary file by reading it into a string and then using struct.unpack(...). Now I want to write to that string using struct.pack_into(...), but I get the error "Cannot use string as modifiable buffer". What would be a suitable buffer for... | What is a suitable buffer for Python's struct module | In Python I'm accessing a binary file by reading it into a string and then using struct.unpack(...). Now I want to write to that string using struct.pack_into(...), but I get the error "Cannot use string as modifiable buffer". What would be a suitable buffer for use with the struct module?
| [
"As noted in another answer, struct_pack is probably all you need and should use. However, objects of type array support the buffer protocol and can be modified:\n>>> import array, struct\n>>> a = array.array('c', ' ' * 1000)\n>>> c = 'a'; i = 1\n>>> struct.pack_into('ci', a, -0, c, i)\n>>> a\narray('c', 'a\\x00\\... | [
7,
6
] | [
"Two possibilities leap immediately to mind:\n\nYou can use the Python stringio module to make a read/write buffer with file semantics.\nYou can use the Python array module to get a buffer you can treat like a list, but which will contain just binary bytes.\n\n"
] | [
-1
] | [
"binary",
"buffering",
"python"
] | stackoverflow_0001732660_binary_buffering_python.txt |
Q:
Lexical Analysis of Python Programming Language
Does anyone know where a FLEX or LEX specification file for Python exists? For example, this is a lex specification for the ANSI C programming language: http://www.quut.com/c/ANSI-C-grammar-l-1998.html
FYI, I am trying to write code highlighting into a Cocoa applicat... | Lexical Analysis of Python Programming Language | Does anyone know where a FLEX or LEX specification file for Python exists? For example, this is a lex specification for the ANSI C programming language: http://www.quut.com/c/ANSI-C-grammar-l-1998.html
FYI, I am trying to write code highlighting into a Cocoa application. Regex won't do it because I also want grammar pa... | [
"Lex is typically just used for tokenizing, not full parsing. Projects that use flex/lex for tokenizing typically use yacc/bison for the actual parsing.\nYou may want to take a look at ANTLR, a more \"modern\" alternative to lexx & yacc.\nThe ANTLR Project has a Github repo containing many ANTLR 4 grammars includin... | [
6,
3,
0
] | [] | [] | [
"lex",
"lexical_analysis",
"python",
"syntax_highlighting"
] | stackoverflow_0001732743_lex_lexical_analysis_python_syntax_highlighting.txt |
Q:
Cannot write a script to "svn export" in Python
I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.22... | Cannot write a script to "svn export" in Python | I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"' % s
print cmd
o... | [
"This is a problem with SSH.\n\nPermission denied, please try again.\n\nThis means that ssh can't login. Either your ssh agent doesn't have the correct key loaded, you're running the script as a different user or the environment isn't passed on correctly. Check that the variables SSH_AUTH_SOCK and SSH_AGENT_PID are... | [
2,
0,
0
] | [] | [] | [
"linux",
"python",
"svn",
"unix"
] | stackoverflow_0001720743_linux_python_svn_unix.txt |
Q:
UnicodeEncodeError on MySQL insert in Python
I used lxml to parse some web page as below:
>>> doc = lxml.html.fromstring(htmldata)
>>> element in doc.cssselect(sometag)[0]
>>> text = element.text_content()
>>> print text
u'Waldenstr\xf6m'
Why it prints u'Waldenstr\xf6m' but not "Waldenström" here?
After that, I ... | UnicodeEncodeError on MySQL insert in Python | I used lxml to parse some web page as below:
>>> doc = lxml.html.fromstring(htmldata)
>>> element in doc.cssselect(sometag)[0]
>>> text = element.text_content()
>>> print text
u'Waldenstr\xf6m'
Why it prints u'Waldenstr\xf6m' but not "Waldenström" here?
After that, I tried to add this text to a MySQL table with UTF-8... | [
"you want text.encode('utf8')\n",
">>> print text\nu'Waldenstr\\xf6m'\n\nThere is a difference between displaying something in the shell (which uses the repr) and printing it (which just spits out the string):\n>>> u'Waldenstr\\xf6m'\nu'Waldenstr\\xf6m'\n\n>>> print u'Waldenstr\\xf6m'\nWaldenström\n\nSo, I'm not ... | [
2,
0
] | [] | [] | [
"mysql",
"python",
"unicode"
] | stackoverflow_0001732762_mysql_python_unicode.txt |
Q:
python: how to send packets in multi thread and then the thread kill itself
I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python.
Here is my code so far:
#! /usr/bin/env python ... | python: how to send packets in multi thread and then the thread kill itself | I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python.
Here is my code so far:
#! /usr/bin/env python
import socket
import thread
import time
IP = "192.168.0.2"
PADDING = "a"... | [
"I recommned using threading module. Even more benefit is to use InterruptableThread for terminating the thread. You do not have to use flag for terminating your thread but exception will occur if you call terminate() on this thread from parent. You can handle exception or not.\nimport threading, ctypes\n\nclass In... | [
5,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"multithreading",
"packet",
"python",
"sockets",
"timer"
] | stackoverflow_0000605013_multithreading_packet_python_sockets_timer.txt |
Q:
Python: next() function
I'm learning Python from a book, and I came across this example:
M = [[1,2,3],
[4,5,6],
[7,8,9]]
G = (sum(row) for row in M) # create a generator of row sums
next(G) # Run the iteration protocol
Since I'm an absolute beginner, and the author hasn't provided any explanation of th... | Python: next() function | I'm learning Python from a book, and I came across this example:
M = [[1,2,3],
[4,5,6],
[7,8,9]]
G = (sum(row) for row in M) # create a generator of row sums
next(G) # Run the iteration protocol
Since I'm an absolute beginner, and the author hasn't provided any explanation of the example or the next() funct... | [
"The expression (sum(row) for row in M) creates what's called a generator. This generator will evaluate the expression (sum(row)) once for each row in M. However, the generator doesn't do anything yet, we've just set it up.\nThe statement next(G) actually runs the generator on M. So, if you run next(G) once, you'll... | [
78,
10
] | [] | [] | [
"next",
"python",
"sum"
] | stackoverflow_0001733004_next_python_sum.txt |
Q:
Optimal datafile format loading on a game console
I need to load large models and other structured binary data on an older CD-based game console as efficiently as possible. What's the best way to do it? The data will be exported from a Python application. This is a pretty elaborate hobby project.
Requierements:
n... | Optimal datafile format loading on a game console | I need to load large models and other structured binary data on an older CD-based game console as efficiently as possible. What's the best way to do it? The data will be exported from a Python application. This is a pretty elaborate hobby project.
Requierements:
no reliance on fully standard compliant STL - i might us... | [
"On platforms like the Nintendo GameCube and DS, 3D models are usually stored in a very simple custom format:\n\nA brief header, containing a magic number identifying the file, the number of vertices, normals, etc., and optionally a checksum of the data following the header (Adler-32, CRC-16, etc).\nA possibly comp... | [
4,
3,
3,
0
] | [] | [] | [
"c++",
"embedded",
"playstation",
"python"
] | stackoverflow_0001727594_c++_embedded_playstation_python.txt |
Q:
`from QTKit import *` causes a 'FAILED TO establish the default connection to the WindowServer' in PyObjC application
I've been trying out PyObjC and I can't seem to get the QTKit imports to work. If I import QTKit like so: from QTKit import * I get a flood of errors:
[Session started at 2009-11-13 21:03:49 -0600... | `from QTKit import *` causes a 'FAILED TO establish the default connection to the WindowServer' in PyObjC application | I've been trying out PyObjC and I can't seem to get the QTKit imports to work. If I import QTKit like so: from QTKit import * I get a flood of errors:
[Session started at 2009-11-13 21:03:49 -0600.]
_RegisterApplication(), FAILED TO establish the default connection to the WindowServer, _CGSDefaultConnection() is NULL.... | [
"Take a look at this tutorial. Apparently QTKit cannot be imported until after the runloop has been established.\n"
] | [
1
] | [] | [] | [
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0001733098_objective_c_pyobjc_python.txt |
Q:
wxPython: Update wx.ListBox list
I have a wx.ListBox in a python program, and I wan't to change out the list in it on a wx.Timer update. I have the timer working, I just don't know how to change out the list that it displays.
A:
Here's an example for modifying a ListBox.
Generally, it uses the Append and Clear m... | wxPython: Update wx.ListBox list | I have a wx.ListBox in a python program, and I wan't to change out the list in it on a wx.Timer update. I have the timer working, I just don't know how to change out the list that it displays.
| [
"Here's an example for modifying a ListBox.\nGenerally, it uses the Append and Clear methods of ListBox. You can call those in your timer handler.\nSince ListBox derives from ItemContainer, see more item modification methods here.\n"
] | [
9
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001733461_python_wxpython.txt |
Q:
pymedia.audio.sound - How do I get up and running with this module?
Im trying to get my hands on this pymedia.audio.sound module and have attempted to get it several times from python.org, but I think I am doing something wrong like.
Any help greatly appreciated.
Im running Windows XP, Python 2.5 and its running f... | pymedia.audio.sound - How do I get up and running with this module? | Im trying to get my hands on this pymedia.audio.sound module and have attempted to get it several times from python.org, but I think I am doing something wrong like.
Any help greatly appreciated.
Im running Windows XP, Python 2.5 and its running fine, but how do I download and where do I extract the new module to be ab... | [
"The homepage for pymedia.\nDownload from here.\nExtract the compressed tar file. Then run python setup.py install from the extracted directory.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0001733052_python.txt |
Q:
Making BeautifulSoup ignore contents inside script tags
I have been trying to get BeautifulSoup (3.1.0.1)to parse a html page that has a lot of javascript that generates html inside tags.
One example fragment looks like this :
<html><head><body><div>
<script type='text/javascript'>
if(ii > 0) {
html += '<span i... | Making BeautifulSoup ignore contents inside script tags | I have been trying to get BeautifulSoup (3.1.0.1)to parse a html page that has a lot of javascript that generates html inside tags.
One example fragment looks like this :
<html><head><body><div>
<script type='text/javascript'>
if(ii > 0) {
html += '<span id="hoverMenuPosSepId" class="hoverMenuPosSep">|</span>'
}
htm... | [
"Reverting to BeautifulSoup 3.0.7a solved this issue and many other html oddities that 3.1.0.1 has choked on. \n",
"I've faced this kind of problem before, and what I normally do is replace every occurrence of <script with <!-- and </script> with -->. That way, all the <script></script> tags are commented out.\n"... | [
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0001732956_beautifulsoup_html_parsing_python.txt |
Q:
More pythonic way of skipping header lines
Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?
In other words, a neater way of doing this
fin = open("data.txt")
line = fin.readline()
while line.startswith("#"):
line = fin.readlin... | More pythonic way of skipping header lines | Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character?
In other words, a neater way of doing this
fin = open("data.txt")
line = fin.readline()
while line.startswith("#"):
line = fin.readline()
| [
"At this stage in my arc of learning Python, I find this most Pythonic:\ndef iscomment(s):\n return s.startswith('#')\n\nfrom itertools import dropwhile\nwith open(filename, 'r') as f:\n for line in dropwhile(iscomment, f):\n # do something with line\n\nto skip all of the lines at the top of the file sta... | [
16,
14,
10,
6,
5,
5,
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0001730649_python.txt |
Q:
run unit tests and coverage in certain python structure
I have some funny noob problem.
I try to run unit tests from commandline:
H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
File "src\test\python\test_power_estimator.py", line 2, in <module>
import src... | run unit tests and coverage in certain python structure | I have some funny noob problem.
I try to run unit tests from commandline:
H:\PRO\pyEstimator>python src\test\python\test_power_estimator.py
Traceback (most recent call last):
File "src\test\python\test_power_estimator.py", line 2, in <module>
import src.main.python.power_estimator as power
ImportError: No module ... | [
"The immediate issue you are facing is a misunderstanding of what is \"local code\" in Python (I am not sure if there is an official terminology, so I am making this one up) and how to import it.\nWhen you run python src\\test\\python\\test_power_estimator.py, the first element in sys.path is set to the directory c... | [
1
] | [] | [] | [
"code_coverage",
"python",
"python_coverage",
"unit_testing"
] | stackoverflow_0001734001_code_coverage_python_python_coverage_unit_testing.txt |
Q:
Grokking Timsort
There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be the new Array.sort in Java 7.
There's some documentation and a tiny Wikipedia article describing the high-level properties of the sort and some low-level performance evaluation... | Grokking Timsort | There's a (relatively) new sort on the block called Timsort. It's been used as Python's list.sort, and is now going to be the new Array.sort in Java 7.
There's some documentation and a tiny Wikipedia article describing the high-level properties of the sort and some low-level performance evaluations, but I was curious i... | [
"Quoting the relevant portion from a now deleted blog post: Visualising Sorting Algorithms: Python's timsort\n\nThe business-end of timsort is a mergesort that operates on runs of pre-sorted elements. A minimum run length minrun is chosen to make sure the final merges are as balanced as possible - for 64 elements, ... | [
15,
8
] | [] | [] | [
"algorithm",
"java",
"python",
"sorting",
"timsort"
] | stackoverflow_0001733073_algorithm_java_python_sorting_timsort.txt |
Q:
Using keys with spaces
Is there a way to do something like the following in Django templates?
{% for hop in hops%}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>{{ hop."boil time" }}</td>
</tr>
{% endfor %}
The hop."boil time" doesn't work. The simple solution is ren... | Using keys with spaces | Is there a way to do something like the following in Django templates?
{% for hop in hops%}
<tr>
<td>{{ hop.name }}</td>
<td>{{ hop.mass }}</td>
<td>{{ hop."boil time" }}</td>
</tr>
{% endfor %}
The hop."boil time" doesn't work. The simple solution is rename the key boil_time, but I... | [
"The best way to get at it is to sneak the property name into another variable, like so:\n{% for key, value in hop.items %}\n {% ifequal key 'boil time' %}\n {{ value }}\n {% endifequal %}\n{% endfor %}\n\nIn Django 0.96 (the version used by Google AppEngine) the templating language doesn't support tup... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"django",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0001726640_dictionary_django_django_templates_google_app_engine_python.txt |
Q:
What is more efficient in python new array creation or in place array manipulation?
Say I have an array with a couple hundred elements. I need to iterate of the array and replace one or more items in the array with some other item. Which strategy is more efficient in python in terms of speed (I'm not worried about... | What is more efficient in python new array creation or in place array manipulation? | Say I have an array with a couple hundred elements. I need to iterate of the array and replace one or more items in the array with some other item. Which strategy is more efficient in python in terms of speed (I'm not worried about memory)?
For example: I have an array
my_array = [1,2,3,4,5,6]
I want to replace the f... | [
"If you want to replace an item or a set of items in a list, you should never use your first option. Removing and adding to a list in the middle is slow (reference). Your second option is also fairly inefficient, since you're doing two operations for a single replacement.\nInstead, just do slice assignment, as eibe... | [
6,
3,
0,
0
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0001733468_performance_python.txt |
Q:
How to access YQL in Python (Django)?
Hey, I need a simple example for the following task:
Send a query to YQL and receive a response
I am accessing public data from python backend of my Django app.
If I just copy/paste an example from YQL, it says "Please provide valid credentials".
I guess, I need OAuth authoriz... | How to access YQL in Python (Django)? | Hey, I need a simple example for the following task:
Send a query to YQL and receive a response
I am accessing public data from python backend of my Django app.
If I just copy/paste an example from YQL, it says "Please provide valid credentials".
I guess, I need OAuth authorization to do it.
So I got an API key and a s... | [
"I've just released python-yql also available on pypi. It can do public, two-legged oauth a.k.a signed requests and facilitate 3-legged outh too.\nIt's brand new so there may be some bugs whilst I work on improving the test coverage but should hopefully do what you need. See the source for some idea on how to use i... | [
3,
2,
0
] | [] | [] | [
"api",
"django",
"oauth",
"python",
"yql"
] | stackoverflow_0001512926_api_django_oauth_python_yql.txt |
Q:
Optimal / best pratice to maintain continuos connection between Python and Postgresql using Psycopg2
I'm writing an application in Python with Postgresql 8.3 which runs on several machines on a local network.
All machines
1) fetch huge amount of data from the database server ( lets say database gets 100 different ... | Optimal / best pratice to maintain continuos connection between Python and Postgresql using Psycopg2 | I'm writing an application in Python with Postgresql 8.3 which runs on several machines on a local network.
All machines
1) fetch huge amount of data from the database server ( lets say database gets 100 different queries from a machine with in 2 seconds time) and there are about 10 or 11 machines doing that.
2) After ... | [
"This sounds a bit like your DB server might have some problems, especially if your database server literally crashes. I'd start by trying to figure out from logs what is the root cause of the problems. It could be something like running out of memory, but it could also happen because of faulty hardware.\nIf you're... | [
1,
1
] | [] | [] | [
"linux",
"out_of_memory",
"performance",
"postgresql",
"python"
] | stackoverflow_0001728350_linux_out_of_memory_performance_postgresql_python.txt |
Q:
2 mysql instances in MAC
i recently switched to mac. first and foremost i installed xampp.
then for django-python-mysql connectivity, i "somehow" ended up installing a seperate MySQL.
now the seperate mysql installation is active all the time and the Xampp one doesnt switch on unless i kill the other one.
what i w... | 2 mysql instances in MAC | i recently switched to mac. first and foremost i installed xampp.
then for django-python-mysql connectivity, i "somehow" ended up installing a seperate MySQL.
now the seperate mysql installation is active all the time and the Xampp one doesnt switch on unless i kill the other one.
what i wanted to know is it possible t... | [
"You could change the listening port of one of the installations and they shouldn't conflict anymore with each other.\nUpdate: You need to find the mysql configuration file my.cnf of the server which should get a new port (the one from xampp should be somewhere in the xampp folder). Find the line port=3306 in the [... | [
1
] | [] | [] | [
"django",
"macos",
"mysql",
"python",
"xampp"
] | stackoverflow_0001734918_django_macos_mysql_python_xampp.txt |
Q:
Each looping return a result
I am a beginner and got an issue, really head around now.
Here is the code:
n=3 #time step
#f, v and r are arrays,eg [3,4,5]
#r,v,f all have initial array which is when n=0
def force():
r=position()
f=r*2
return f
def position(n):
v=velocity(n)
for i in range(n):... | Each looping return a result | I am a beginner and got an issue, really head around now.
Here is the code:
n=3 #time step
#f, v and r are arrays,eg [3,4,5]
#r,v,f all have initial array which is when n=0
def force():
r=position()
f=r*2
return f
def position(n):
v=velocity(n)
for i in range(n): #This part may wrong...
... | [
"You can use yield.\ndef velocity(n):\n f=force\n for i in range(n):\n v=f*i\n yield(v)\nfor vel in velocity(n):\n //do something\n\nOne working example. It will print the output of function test as soon as it yields. So you do not need to wait for the next iteration of the loop.\nimport time\ndef test():\... | [
4,
2,
0,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0001734626_arrays_numpy_python.txt |
Q:
How to keep pyglet from clearing the screen?
I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks
from pyglet.gl import *
window=pyglet.window.Window()
def drawline():
...
@window.event
def on_draw():
drawline()
pyglet.app.run()
... | How to keep pyglet from clearing the screen? | I want to draw a scene and sequentially add lines to it. But pyglet keeps updating without control :( , so all I get is blinks
from pyglet.gl import *
window=pyglet.window.Window()
def drawline():
...
@window.event
def on_draw():
drawline()
pyglet.app.run()
should I change the decorator(if there exist opti... | [
"You'll need to draw your lines each time the window is redrawn as they won't be retained. You're probably better off using batches of vertex lists and adding to them. See here and here for details.\n"
] | [
2
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0001734801_pyglet_python.txt |
Q:
How do I use the quartz scheduler with Python?
Is there a guide or tutorial on how to use the quartz Scheduler with Python.
Is there an existing API for Python?
A:
Given that Quartz is a Java application/library, the simplest thing to do may be to run it within Jython.
Failing that, and if you simply want to con... | How do I use the quartz scheduler with Python? | Is there a guide or tutorial on how to use the quartz Scheduler with Python.
Is there an existing API for Python?
| [
"Given that Quartz is a Java application/library, the simplest thing to do may be to run it within Jython.\nFailing that, and if you simply want to control the configuration of jobs from Python, perhaps the JDBC-JobStore is of use, and you could write jobs into the database via Python. You'll still need an instance... | [
0
] | [] | [] | [
"python",
"quartz_scheduler"
] | stackoverflow_0001735266_python_quartz_scheduler.txt |
Q:
How to create program startup parameters in python
I'm just beginning to learn python and the program I'm writing requires parameters for it to run with a specific task. For example (programs name is Samtho)
samtho -i Mozilla_Firefox
How can I do that?
A:
Read the documentation on optparse. It is very powerful ... | How to create program startup parameters in python | I'm just beginning to learn python and the program I'm writing requires parameters for it to run with a specific task. For example (programs name is Samtho)
samtho -i Mozilla_Firefox
How can I do that?
| [
"Read the documentation on optparse. It is very powerful and will let you lots of parameters and create the help text.\n",
"You can use the modules optparse and getopt from the standard library. The former is more flexible and thus recommended.\nIf you want to write your own parser, then you'll have to inspect th... | [
9,
6,
2,
1,
0
] | [] | [] | [
"parameters",
"pydev",
"python",
"startup"
] | stackoverflow_0001735202_parameters_pydev_python_startup.txt |
Q:
Understanding Zope internals, from Django eyes
I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
What is the "real" purpose of zod... | Understanding Zope internals, from Django eyes | I am a newbie to zope and I previously worked on Django for about 2.5 years. So when I first jumped into Zope(v2) (only because my new company is using it since 7 years), I faced these questions. Please help me in understanding them.
What is the "real" purpose of zodb as such? I know what it does, but tell me one grea... | [
"First things first: current zope2 versions include all of zope3, too. And if you look at modern zope2 applications like Plone, you'll see that it uses a lot of \"zope 3\" (now called the \"zope tool kit\", ZTK) under the hood.\nThe real purpose of the ZODB: it is one of the few object databases (as opposed to rela... | [
16,
10,
7,
6,
3,
1
] | [] | [] | [
"acquisition",
"django",
"python",
"zodb",
"zope"
] | stackoverflow_0001706309_acquisition_django_python_zodb_zope.txt |
Q:
Class-level read-only properties in Python
Is there some way to make a class-level read-only property in Python? For instance, if I have a class Foo, I want to say:
x = Foo.CLASS_PROPERTY
but prevent anyone from saying:
Foo.CLASS_PROPERTY = y
EDIT:
I like the simplicity of Alex Martelli's solution, but not the ... | Class-level read-only properties in Python | Is there some way to make a class-level read-only property in Python? For instance, if I have a class Foo, I want to say:
x = Foo.CLASS_PROPERTY
but prevent anyone from saying:
Foo.CLASS_PROPERTY = y
EDIT:
I like the simplicity of Alex Martelli's solution, but not the syntax that it requires. Both his and ~unutbu's... | [
"The existing solutions are a bit complex -- what about just ensuring that each class in a certain group has a unique metaclass, then setting a normal read-only property on the custom metaclass. Namely:\n>>> class Meta(type):\n... def __new__(mcl, *a, **k):\n... uniquemcl = type('Uniq', (mcl,), {})\n... ... | [
10,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0001735434_python.txt |
Q:
Why isn't psycopg2 executing any of my SQL functions? (IndexError: tuple index out of range)
I'll take the simplest of the SQL functions as an example:
CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
... | Why isn't psycopg2 executing any of my SQL functions? (IndexError: tuple index out of range) | I'll take the simplest of the SQL functions as an example:
CREATE OR REPLACE FUNCTION skater_name_match(INTEGER,VARCHAR)
RETURNS BOOL AS
$$
SELECT $1 IN (SELECT skaters_skater.competitor_ptr_id FROM skaters_skater
WHERE name||' '||surname ILIKE '%'||$2||'%'
OR surname||' '||name ILIKE '%'||$2||'%');
$$ LAN... | [
"By default psycopg2 identifies argument placeholders using the % symbol (usually you'd have %s in the string). \nSo, if you use cursor.execute('... %s, %s ...', (arg1, arg2)) then those %s get turned into the values of arg1 and arg2 respectively.\nBut since you call: cursor.execute(sql_function_above), without ext... | [
32,
3,
1
] | [] | [] | [
"django",
"postgresql",
"psycopg2",
"python",
"sql"
] | stackoverflow_0001734814_django_postgresql_psycopg2_python_sql.txt |
Q:
I set a proxy server on urllib2, and then I can't change it
Like the title says, my code basically does this:
set proxy, test proxy, do some cool stuff
But after the proxy is set the first time, it sticks that way, never changing. This is the failing code:
# Pick proxy
r = random.randint(0, len(proxies) - ... | I set a proxy server on urllib2, and then I can't change it | Like the title says, my code basically does this:
set proxy, test proxy, do some cool stuff
But after the proxy is set the first time, it sticks that way, never changing. This is the failing code:
# Pick proxy
r = random.randint(0, len(proxies) - 1)
proxy = proxies[r]
print proxy
# Setup proxy
... | [
"That does seem strange. I've always found the httplib2 module to be the easiest Python HTTP client to work with. There is an example of using httplib2 with the socks module.\nSorry, I know this isn't a specific answer to your question, but it might be a workaround to try.\n"
] | [
1
] | [] | [] | [
"proxy",
"python",
"urllib2"
] | stackoverflow_0001735852_proxy_python_urllib2.txt |
Q:
Production quality Python opensocial container and client?
Is there any production quality library for developing opensocial containers and clients in python and django?
A:
Regarding containers, there's GAE-opensocial which can run in App Engine (should also be usable stand-alone); unfortunately it looks like dj... | Production quality Python opensocial container and client? | Is there any production quality library for developing opensocial containers and clients in python and django?
| [
"Regarding containers, there's GAE-opensocial which can run in App Engine (should also be usable stand-alone); unfortunately it looks like django-opensocial is dormant. For clients, opensocial-python-client.\n"
] | [
3
] | [] | [] | [
"django",
"opensocial",
"python"
] | stackoverflow_0001735180_django_opensocial_python.txt |
Q:
passing value to other module python
i have two script name is A.py and B.py
i want to know how to send value from A.py to B.py.
for more detail,when run finished A.py script at the end of script ,A.py call B.py.
my question is i have to send some value from A.py to B.py.
anybody some help me how to send value A.... | passing value to other module python | i have two script name is A.py and B.py
i want to know how to send value from A.py to B.py.
for more detail,when run finished A.py script at the end of script ,A.py call B.py.
my question is i have to send some value from A.py to B.py.
anybody some help me how to send value A.py to B.py,so i can use some value in B.p... | [
"Your question isn't quite clear.\nimport B\nB.methodToExecute(argument)\n\n",
"Do I assume correctly that you want to have B.py to use all the variables with values that exist when A.py finishes?\n[edit]\nOk, the problem is you cannot easily do this without any variable assignments. What you'd like to achieve is... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001735395_python.txt |
Q:
How to read data from Game Port with Python?
I like programming with robots and stuff. For this approach, I'm using the LPT port for output and the Gameport for input.
For younger guys: Just some old fashioned USB Ports ;-)
Game Port http://img44.imageshack.us/img44/3650/da15dsubm.png Parallel Port http://img44.im... | How to read data from Game Port with Python? | I like programming with robots and stuff. For this approach, I'm using the LPT port for output and the Gameport for input.
For younger guys: Just some old fashioned USB Ports ;-)
Game Port http://img44.imageshack.us/img44/3650/da15dsubm.png Parallel Port http://img44.imageshack.us/img44/1369/800pxparallelport.jpg
With ... | [
"I cannot really help you much. I don't work with joy/parallel port anymore and I forgot almost everything.\nWhat I can tell you is that under linux, there's a specific driver and device for the joystick port. You find information about it here (google cache, the main doc is down)\nhttp://74.125.153.132/search?q=ca... | [
2,
1,
1
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0001734779_python_ubuntu.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.