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:
Using python to extract a few lines from a data file
I have a large file which has an enormous of data in it. I need to extract 3 lines every 5000 or so lines. The format of the data file is as follows:
...
O_sh 9215 1.000000 -2.304400
-1.0680E+00 1.3617E+00 -5.7138E+00
O_sh 9216 1... | Using python to extract a few lines from a data file | I have a large file which has an enormous of data in it. I need to extract 3 lines every 5000 or so lines. The format of the data file is as follows:
...
O_sh 9215 1.000000 -2.304400
-1.0680E+00 1.3617E+00 -5.7138E+00
O_sh 9216 1.000000 -2.304400
-8.1186E-01 -1.7454E+00 -5.8169E+00... | [
"Assuming this is not homework, I think regex is overkill for the problem. If you know that you need three lines after one starts with 'timestep' why not approach the problem this way:\nMatrices = []\n\nwith open('data.txt') as fh:\n for line in fh:\n # If we see timestep put the next three lines in our Matric... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005939612_python.txt |
Q:
Python bus error problem when writing to database
Whenever I try to write/update/delete from MySQL I've been experiencing a bus error problem since I've installed zlib on my machine. Has anyone else experienced this problem? There's no error message or anything. Python just prints Bus error to console and quits. I... | Python bus error problem when writing to database | Whenever I try to write/update/delete from MySQL I've been experiencing a bus error problem since I've installed zlib on my machine. Has anyone else experienced this problem? There's no error message or anything. Python just prints Bus error to console and quits. I can read from database without any problems though.
Co... | [
"It is really hard recommending something useful without (much) more informations. But try:\nsudo dtruss python your_python_program\n\nyou will get a long syscall trace, what can be the 1st step to figure out what is wrong.\n"
] | [
2
] | [] | [] | [
"bus_error",
"macos",
"mysql",
"python",
"zlib"
] | stackoverflow_0005941459_bus_error_macos_mysql_python_zlib.txt |
Q:
how to insert to a mysql table using mysaldb, where the table name is in a python variable?
I'm using python-mysql db api to insert some values to a table where the table name is in a python variable. So I wrote the below code
DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,... | how to insert to a mysql table using mysaldb, where the table name is in a python variable? | I'm using python-mysql db api to insert some values to a table where the table name is in a python variable. So I wrote the below code
DB_CURSOR.execute("""INSERT INTO %s (name,created_by,state,description,docs,admin_email,date_created) VALUES(%s,%s,%s,%s,%s,%s,%s)""", (hosts_table, hostname, created_by, state, descrip... | [
"DB_CURSOR.execute(\"\"\"INSERT INTO %s \n (name,created_by,state,description,docs,admin_email,date_created) \n VALUES(%%s,%%s,%%s,%%s,%%s,%%s,%%s)\"\"\" % hosts_table,\n (hostname, created_by, state, description, docroot, admin_email, date_created))\n\nNote that the hosts_table variable is a single % sign... | [
6,
0,
0
] | [] | [] | [
"mysql_python",
"python"
] | stackoverflow_0005936806_mysql_python_python.txt |
Q:
Can someone explain how this mgiza script works?
$:~/mgizapp/scripts$ ./plain2snt-hasvcb.py
Error, the input should be
./plain2snt-hasvcb.py evcb fvcb etxt ftxt esnt(out) fsnt(out) evcbx(out) fvcbx(out)
You should concatenate the evcbx and fvcbx to existing vcb files
can someone explain what the all the acrane i... | Can someone explain how this mgiza script works? | $:~/mgizapp/scripts$ ./plain2snt-hasvcb.py
Error, the input should be
./plain2snt-hasvcb.py evcb fvcb etxt ftxt esnt(out) fsnt(out) evcbx(out) fvcbx(out)
You should concatenate the evcbx and fvcbx to existing vcb files
can someone explain what the all the acrane inputs for the plain2snt script? the script is from the... | [
"Based on my (not equivalent) experience with GIZA++ and the page you link to, I'd say evcb and fvcb are the \"English\" and \"Foreign\" vocab files you've generated already and that etxt and ftxt are the \"English\" and \"Foreign\" text inputs. It seems then that esnt and fsnt are the \"English\" and \"Foreign\" s... | [
2
] | [] | [] | [
"corpus",
"machine_translation",
"nlp",
"python"
] | stackoverflow_0005375980_corpus_machine_translation_nlp_python.txt |
Q:
Python: merging tally data
Okay - I'm sure this has been answered here before but I can't find it....
My problem: I have a list of lists with this composition
0.2 A
0.1 A
0.3 A
0.3 B
0.2 C
0.5 C
My goal is to output the following:
0.6 A
0.3 B
0.7 C
In other words, I need to merge the data from multiple lines toget... | Python: merging tally data | Okay - I'm sure this has been answered here before but I can't find it....
My problem: I have a list of lists with this composition
0.2 A
0.1 A
0.3 A
0.3 B
0.2 C
0.5 C
My goal is to output the following:
0.6 A
0.3 B
0.7 C
In other words, I need to merge the data from multiple lines together.
Here's the code I'm using:
... | [
"You want to use a dict, but collections.defaultdict can come in really handy here so that you don't have to worry about whether the key exists in the dict or not -- it just defaults to 0.0:\nimport collections\n\nlines = [[0.2, 'A'], [0.1, 'A'], [0.3, 'A'], [0.3, 'B'], [0.2, 'C'], [0.5, 'C']]\namounts = collection... | [
6,
3,
2,
2,
1,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"break",
"duplicates",
"loops",
"nested_loops",
"python"
] | stackoverflow_0005941699_break_duplicates_loops_nested_loops_python.txt |
Q:
Getting contents of Tornado's xsrf_form_html() function outside of a template
I'm using Tornado for a python application, I want to put the value of xsrf_form_html() in my forms but I'm using Mustache to render templates instead of the standard Tornado template system. Is there any way to get that value to a varia... | Getting contents of Tornado's xsrf_form_html() function outside of a template | I'm using Tornado for a python application, I want to put the value of xsrf_form_html() in my forms but I'm using Mustache to render templates instead of the standard Tornado template system. Is there any way to get that value to a variable? I did try
xsrfform = xsrf_form_html()
but that didn't work. Is it under som... | [
"I don't know how mustache works, but every RequestHandler has that method, so you must pass it to the template like any other value.\n"
] | [
1
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0005937782_python_tornado.txt |
Q:
Displaying & Modifying Diagrams / Flowgraphs in PyQt GUI
Essentially what I would like to do is draw a circuit diagram in a PyQt based on input given from another part of the GUI. My first thought was to simply use graphical tiles, and switch them out as pixmaps based on the input, but that is pretty clunky.
I su... | Displaying & Modifying Diagrams / Flowgraphs in PyQt GUI | Essentially what I would like to do is draw a circuit diagram in a PyQt based on input given from another part of the GUI. My first thought was to simply use graphical tiles, and switch them out as pixmaps based on the input, but that is pretty clunky.
I suppose finding a way to actively display dia diagrams in a fram... | [
"To anyone that needs to go down this route in the future, the best option was definitely pydot. Easy to use, and pretty full-featured. Way to go, Graphviz.\n"
] | [
3
] | [] | [] | [
"dia",
"diagram",
"pyqt",
"python",
"user_interface"
] | stackoverflow_0005834779_dia_diagram_pyqt_python_user_interface.txt |
Q:
'utf-8' can't decode byte 0xc0 in position 0: invalid start byte
I'm trying to execute Django's createsuperuser and recieve the following error. Before syncdb database is empty and coded in 'utf-8'. I'm using pymysql.
D:\Python27\site\mysite>python manage.py syncdb
Creating tables ...
Creating table auth_permissio... | 'utf-8' can't decode byte 0xc0 in position 0: invalid start byte | I'm trying to execute Django's createsuperuser and recieve the following error. Before syncdb database is empty and coded in 'utf-8'. I'm using pymysql.
D:\Python27\site\mysite>python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Crea... | [
"The byte with code C0 is invalid in UTF-8 encoded text. I don't know where this text is coming from, but it is either invalid UTF-8, or your code is erroneously trying to treat it as UTF-8.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005942031_django_python.txt |
Q:
In python, how would I open a PIL or Imagemagick Image as a file
I'm taking uploaded files which I can save to S3 using SimpleS3:
from simples3.bucket import S3Bucket
upload = request.POST['image']
s = S3Bucket("cdn", s3.access_key, s3.secret_key)
s.put(upload.filename, upload.file.read())
Somewhere between savin... | In python, how would I open a PIL or Imagemagick Image as a file | I'm taking uploaded files which I can save to S3 using SimpleS3:
from simples3.bucket import S3Bucket
upload = request.POST['image']
s = S3Bucket("cdn", s3.access_key, s3.secret_key)
s.put(upload.filename, upload.file.read())
Somewhere between saving that as a file and uploading it I save the file which is an image as... | [
"Figured it out: \nfrom StringIO import StringIO\nf = StringIO() \nthumb.save(f, ext) \ns.put(self.filename+ext, f.getvalue())\n\n",
"For ImageMagick case, if you are using PythonMagick, you can use underlying Blob class,\n>>> from PythonMagick import Image, Blob\n>>> image = Image(\"images/test_image.miff\")\n>>... | [
4,
0
] | [] | [] | [
"amazon_s3",
"file_io",
"imagemagick",
"python",
"python_imaging_library"
] | stackoverflow_0005930931_amazon_s3_file_io_imagemagick_python_python_imaging_library.txt |
Q:
Python - Subprocess - How to call a Piped command in Windows?
How do I run this command with subprocess?
I tried:
proc = subprocess.Popen(
'''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''',
stdin=s... | Python - Subprocess - How to call a Piped command in Windows? | How do I run this command with subprocess?
I tried:
proc = subprocess.Popen(
'''ECHO bosco|"C:\Program Files\GNU\GnuPG\gpg.exe" --batch --passphrase-fd 0 --output "c:\docume~1\usi\locals~1\temp\tmptlbxka.txt" --decrypt "test.txt.gpg"''',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.ST... | [
"First and foremost, you don't actually need a pipe; you are just sending input. You can use subprocess.communicate for that.\nSecondly, don't specify the command as a string; that's messy as soon as filenames with spaces are involved.\nThirdly, if you really wanted to execute a piped command, just call the shell. ... | [
11,
4
] | [] | [] | [
"echo",
"pipe",
"popen",
"python",
"subprocess"
] | stackoverflow_0001046474_echo_pipe_popen_python_subprocess.txt |
Q:
Resolving template block structure conflicts with third-party django apps
When incorporating a third-party django app, I typically want it to be integrated aesthetically with the rest of my django project. While this is typically a matter of overriding the apps 'base.html' (if that), we all structure our templates... | Resolving template block structure conflicts with third-party django apps | When incorporating a third-party django app, I typically want it to be integrated aesthetically with the rest of my django project. While this is typically a matter of overriding the apps 'base.html' (if that), we all structure our templates a little differently, so incompatibilities often arise. For instance, suppose ... | [
"First, the html inheritance should go:\nmy-sitebase.html\n |-- app-base.html\n |-- app-foo-template.html\n\nI think this is what you meant, but the wording was a bit ambiguous. You might be able to just edit the app-base.html.\nSecond, a reusable app that overrides something like {% block footer %} is almost wi... | [
2
] | [] | [] | [
"django",
"extensibility",
"inheritance",
"python",
"templates"
] | stackoverflow_0005940755_django_extensibility_inheritance_python_templates.txt |
Q:
Finding type in python - TypeError 'unicode' object is not callable
I'm trying to make sure an object is a string type in Python (for google app engine). I'm doing this so that I can change it to a db.Text type if its more than 500 bytes. However, I keep getting the error: TypeError 'unicode' object is not calla... | Finding type in python - TypeError 'unicode' object is not callable | I'm trying to make sure an object is a string type in Python (for google app engine). I'm doing this so that I can change it to a db.Text type if its more than 500 bytes. However, I keep getting the error: TypeError 'unicode' object is not callable
if type(value) in types.StringTypes and len(value) > 499:
... | [
"I think you just need to remove the parentheses from types.StringTypes, since it is a tuple (and not callable, hence the error). Either that, or your code is actually using StringType, which means your code is making a new string instance instead of returning the str type. Either way, it looks like a typo. See the... | [
6,
4,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"types"
] | stackoverflow_0005942624_google_app_engine_python_types.txt |
Q:
pyqt: how to remove a widget?
I have a QGroupBox widget with children in it that I want to remove. How do I do that? I can't find any removeWidget, removeChild, removeItem, or anything similar in the docs. I can only see how to remove things from a layout, but that, apparently, doesn't remove it from the actual wi... | pyqt: how to remove a widget? | I have a QGroupBox widget with children in it that I want to remove. How do I do that? I can't find any removeWidget, removeChild, removeItem, or anything similar in the docs. I can only see how to remove things from a layout, but that, apparently, doesn't remove it from the actual widget.
| [
"If your widget have no child widgets that depend on it i think you can use:\nlayout.removeWidget(self.widget_name)\nself.widget_name.deleteLater()\nself.widget_name = None\n\nin my tests when it is a widget that have childs you have to:\nimport sip\nlayout.removeWidget(self.widget_name)\nsip.delete(self.widget_nam... | [
66,
42
] | [] | [] | [
"pyqt",
"python",
"qt",
"widget"
] | stackoverflow_0005899826_pyqt_python_qt_widget.txt |
Q:
checkbox values in cherrypy
I understand that Cherrypy makes checkbox values available as a list cfg question (CherryPy - saving checkboxes selection to variables)
Let's say I have following form data:
... snip ...
<input type=checkbox id="1">
<input type=checkbox id="1">
<input type=checkbox id="1">
<input type=... | checkbox values in cherrypy | I understand that Cherrypy makes checkbox values available as a list cfg question (CherryPy - saving checkboxes selection to variables)
Let's say I have following form data:
... snip ...
<input type=checkbox id="1">
<input type=checkbox id="1">
<input type=checkbox id="1">
<input type=checkbox id="2">
<input type=chec... | [
"First a nit: The \"id\" attribute in HTML is supposed to be unique for the whole document.\nYou then have two options:\n\nChange the \"name\" attributes to be unique, like <input type=\"checkbox\" name=\"3b\">, in which case you'll get back {..., '3a': u'on' '3c': u'on'}, or\nMake the values unique, like <input ty... | [
2
] | [] | [] | [
"checkbox",
"cherrypy",
"python"
] | stackoverflow_0005928970_checkbox_cherrypy_python.txt |
Q:
Add an item between each item already in the list
Possible Duplicate:
python: most elegant way to intersperse a list with an element
Assuming I have the following list:
['a','b','c','d','e']
How can I append a new item (in this case a -) between each item in this list, so that my list will look like the followi... | Add an item between each item already in the list |
Possible Duplicate:
python: most elegant way to intersperse a list with an element
Assuming I have the following list:
['a','b','c','d','e']
How can I append a new item (in this case a -) between each item in this list, so that my list will look like the following?
['a','-','b','-','c','-','d','-','e']
Thanks.
| [
"Here's a solution that I would expect to be very fast -- I believe all these operations will happen at optimized c speed.\ndef intersperse(lst, item):\n result = [item] * (len(lst) * 2 - 1)\n result[0::2] = lst\n return result\n\nTested:\n>>> l = [1, 2, 3, 4, 5]\n>>> intersperse(l, '-')\n[1, '-', 2, '-', ... | [
48,
20,
13,
7,
2,
2,
1,
1
] | [] | [] | [
"insert",
"list",
"python"
] | stackoverflow_0005920643_insert_list_python.txt |
Q:
Unserialize PHP data in python
Possible Duplicate:
How to read/make sense of a PHP serialised data string in python
I'm using python to access a database which is managed by a Drupal install. The data I want to access in Drupal in saved in the database as a PHP serialized object.
Are there any pre-built python m... | Unserialize PHP data in python |
Possible Duplicate:
How to read/make sense of a PHP serialised data string in python
I'm using python to access a database which is managed by a Drupal install. The data I want to access in Drupal in saved in the database as a PHP serialized object.
Are there any pre-built python modules which can deserialize a PHP ... | [
"Are you looking for phpserialize?\n",
"If you don't need object serialization (which can be compensated with associative arrays), then a faster alternative might be this: http://code.google.com/p/serek/ (it's a Python module written in C)\nIt's used in production servers under heavy load at my company, so I migh... | [
31,
5
] | [] | [] | [
"deserialization",
"drupal",
"php",
"python"
] | stackoverflow_0005935501_deserialization_drupal_php_python.txt |
Q:
PySide web browser appears, but inspector doesn't display anything
I am currently running this code, and although the web browser appears, the web inspector doesn't seem to display anything, am i doing something incorrectly?
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit imp... | PySide web browser appears, but inspector doesn't display anything | I am currently running this code, and although the web browser appears, the web inspector doesn't seem to display anything, am i doing something incorrectly?
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("htt... | [
"It is in the Qt Documentation:\n\nNote: A QWebInspector will display a\n blank widget if either: page() is null\n QWebSettings::DeveloperExtrasEnabled\n is false\n\nYou must enable it, like this:\nimport sys\nfrom PySide.QtCore import *\nfrom PySide.QtGui import *\nfrom PySide.QtWebKit import *\n\napp = QApplic... | [
16
] | [] | [] | [
"pyside",
"python",
"qt",
"webkit"
] | stackoverflow_0005942487_pyside_python_qt_webkit.txt |
Q:
python 3.2 plugin factory: instantiation from class/metaclass
I'm riffing from the information here: Metaclass not being called in subclasses
My problem is that I'm unable to create an instance of an object using this class registry. If I use "regular" construction methods, then it seems to instantiate objects co... | python 3.2 plugin factory: instantiation from class/metaclass | I'm riffing from the information here: Metaclass not being called in subclasses
My problem is that I'm unable to create an instance of an object using this class registry. If I use "regular" construction methods, then it seems to instantiate objects correctly; but when I try to use the class object associated with reg... | [
"I think the issue you're having is that the cls parameter passed to a metaclass constructor is actually a reference to the metaclass and not the class which is being created. Since __new__ is a classmethod of PluginMetaclass, it's associated with that class just like any regular classmethod. You probably want to b... | [
6
] | [] | [] | [
"factory_pattern",
"metaclass",
"python"
] | stackoverflow_0005940806_factory_pattern_metaclass_python.txt |
Q:
How to join detail twice on a master in SQLAlchemy?
Situation: I have two tables, say 'master' and 'detail', where 'master' has two columns that refer to 'detail': 'foo_id', 'bar_id'. That is, I need to join detail twice with different names. I want to do:
SELECT master.id, foo.name, bar.name, other stuff ...
FROM... | How to join detail twice on a master in SQLAlchemy? | Situation: I have two tables, say 'master' and 'detail', where 'master' has two columns that refer to 'detail': 'foo_id', 'bar_id'. That is, I need to join detail twice with different names. I want to do:
SELECT master.id, foo.name, bar.name, other stuff ...
FROM master
JOIN detail AS foo ON foo.id = master.foo_id
JOIN... | [
"Fighting for quite a long time with the problem, i've solved it couple of minutes after posting my question here. The solution was to store and then reuse all aliased tables. Before I was using alias in join and then same alias for table to fetch column reference in SELECT, which resulted in redundant and broken '... | [
2
] | [] | [] | [
"join",
"python",
"sqlalchemy"
] | stackoverflow_0005780516_join_python_sqlalchemy.txt |
Q:
Confusion with unicode in Python
As part of a Django site, users can enter street names and the entry will be added to a google maps geocoding link. Everything works well, until users enter special characters.
I would like to display the special character in the link, however python replaces the character with the... | Confusion with unicode in Python | As part of a Django site, users can enter street names and the entry will be added to a google maps geocoding link. Everything works well, until users enter special characters.
I would like to display the special character in the link, however python replaces the character with the unicode symbol. Is there a way to pre... | [
"First, check if addressString is a Unicode object (it is if you're using Python 3, or if type(addressString) shows 'unicode'). If it is, then you probably need to try the following:\nurl = \"http://maps.googleapis.com/maps/api/geocode/json?address=\" +\n urllib.quote(addressString.encode('utf-8')) + \"&sensor... | [
5,
2,
0
] | [] | [] | [
"ascii",
"decode",
"hyperlink",
"python",
"unicode"
] | stackoverflow_0005936665_ascii_decode_hyperlink_python_unicode.txt |
Q:
PyUSB backend not accessible
hey i am trying to run the simple script available in the tutorial;. the usb is getting imported but when i try to search the device i get the following error,please help
>>> dev=usb.core.find()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python2... | PyUSB backend not accessible | hey i am trying to run the simple script available in the tutorial;. the usb is getting imported but when i try to search the device i get the following error,please help
>>> dev=usb.core.find()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.py", ... | [
"You need to install libusb-1.0, libusb-0.1, or openusb as a backend to pyusb. Is this a Windows machine?\nIf so, you can download a simple installer here: http://www.craftedge.com/products/libusb.html \n"
] | [
11
] | [] | [] | [
"python",
"pyusb"
] | stackoverflow_0005152133_python_pyusb.txt |
Q:
Script function to check if IP is whitelisted
I have a Python script which blocks some IPs if they perform some actions. This script contains a function to check if the IP is already blocked. In addition to this, I'd like the function to also check if the IP is stored in a database table and if it is, do not block... | Script function to check if IP is whitelisted | I have a Python script which blocks some IPs if they perform some actions. This script contains a function to check if the IP is already blocked. In addition to this, I'd like the function to also check if the IP is stored in a database table and if it is, do not block it ( whitelist )
The function looks like this :
de... | [
"If you're planning on editing this whitelist manually, you could just use a file with your list of IP addresses. (one per line) You could then use code something like this to check it:\ndef check_ip(ip_address):\n cmd = \"/sbin/iptables -L INPUT -n|grep \" + ip_address\n signal,output = commands.getstatusout... | [
0
] | [] | [] | [
"function",
"python",
"sql",
"whitelist"
] | stackoverflow_0005943549_function_python_sql_whitelist.txt |
Q:
Django: why are Django model fields class attributes?
In Django a model's fields are defined as class attributes.
So that would mean all instances of a model would share the same values for those fields, no?
Say I have a model
class Tag(models.Model):
name = models.CharField(max_length=30)
And I have a form i... | Django: why are Django model fields class attributes? | In Django a model's fields are defined as class attributes.
So that would mean all instances of a model would share the same values for those fields, no?
Say I have a model
class Tag(models.Model):
name = models.CharField(max_length=30)
And I have a form in which users can submit tags. Say a user submitted 2 tags:... | [
"No, for the same reason as this:\n>>> class Foo(object):\n... bar = 'Foo attribute'\n...\n>>> f = Foo()\n>>> f.bar\n'Foo attribute'\n>>> Foo.bar\n'Foo attribute'\n>>> f.bar = 'instance attribute'\n>>> f.bar\n'instance attribute'\n>>> Foo.bar\n'Foo attribute'\n\nWhen you assign an attribute to an object, a clas... | [
18
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005943846_django_django_models_python.txt |
Q:
Determine killer of process
I got a python program running as a windows service which does in my opinion catch all exceptions. In my development environment I cannot reproduce any situation, where no exception is logged, when the program crashes. Except 2 cases: the program is killed via Task Manager or I power of... | Determine killer of process | I got a python program running as a windows service which does in my opinion catch all exceptions. In my development environment I cannot reproduce any situation, where no exception is logged, when the program crashes. Except 2 cases: the program is killed via Task Manager or I power off the computer.
However, on the t... | [
"You need to give more information like \"Is your program multi-threaded ?\" Does the code depend on the version of Python interpreter you are using, or any imported modules used not present in the target environment ?\nIf you have GDB for Windows, you can do \"gdb -p pid\" where \"pid\" is the pid of the python pr... | [
0,
0
] | [] | [] | [
"python",
"windows_services"
] | stackoverflow_0005402245_python_windows_services.txt |
Q:
Is there a way to find out the name of the file stdout is redirected to in Python
I know how to detect if my Python script's stdout is being redirected (>) using sys.stdout.isatty() but is there a way to discover what it's being redirected to?
For example:
python my.py > somefile.txt
Is there a way to discover th... | Is there a way to find out the name of the file stdout is redirected to in Python | I know how to detect if my Python script's stdout is being redirected (>) using sys.stdout.isatty() but is there a way to discover what it's being redirected to?
For example:
python my.py > somefile.txt
Is there a way to discover the name somefile.txt on both Windows and Linux?
| [
"I doubt you can do that in a system-independent way. On Linux, the following works:\nimport os\nmy_output_file = os.readlink('/proc/%d/fd/1' % os.getpid())\n\n",
"If you need a platform-independent way to get the name of the file, pass it as an argument and use argparse (or optparse) to read your arguments, don'... | [
10,
1
] | [] | [] | [
"filenames",
"io_redirection",
"python",
"python_2.7"
] | stackoverflow_0005943778_filenames_io_redirection_python_python_2.7.txt |
Q:
Boost.Python id of object
How do I get the id of a python object in boost python. I was hoping for something like
boost::python::obj = ...;
int id = boost::python::id(obj);
A:
From the Python documentation, in CPython, the value returned is the address of the object. So, if you're looking for something similar ... | Boost.Python id of object | How do I get the id of a python object in boost python. I was hoping for something like
boost::python::obj = ...;
int id = boost::python::id(obj);
| [
"From the Python documentation, in CPython, the value returned is the address of the object. So, if you're looking for something similar in Boost Python:\nboost::python::api::object obj = ...;\nlong id = static_cast<long>(obj.ptr());\n\nA cursory glance in the source; the built-in id function's implementation (I'm ... | [
2
] | [] | [] | [
"boost_python",
"python"
] | stackoverflow_0005944127_boost_python_python.txt |
Q:
"sorted 1-d iterator" based on "2-d iterator" (Cartesian product of iterators)
I'm looking for a clean way to do this in Python:
Let's say I have two iterators "iter1" and "iter2": perhaps a prime number generator, and itertools.count(). I know a priori that both are are infinite and monotonically increasing. No... | "sorted 1-d iterator" based on "2-d iterator" (Cartesian product of iterators) | I'm looking for a clean way to do this in Python:
Let's say I have two iterators "iter1" and "iter2": perhaps a prime number generator, and itertools.count(). I know a priori that both are are infinite and monotonically increasing. Now I want to take some simple operation of two args "op" (perhaps operator.add or ope... | [
"import heapq\nimport itertools\nimport operator\n\n\ndef increasing(fn, left, right):\n \"\"\"\n Given two never decreasing iterators produce another iterator\n resulting from passing the value from left and right to fn.\n This iterator should also be never decreasing.\n \"\"\"\n # Imagine an inf... | [
5,
4,
2,
2,
0,
0
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0005938309_iterator_python.txt |
Q:
Can Python automatically communicate with SVN
I was hoping to implement an SVN communicator in my python program so that any file being worked on is automatically stored into the user's SVN account without any user interaction (username and password already provided so Python takes care of storage). Are there any ... | Can Python automatically communicate with SVN | I was hoping to implement an SVN communicator in my python program so that any file being worked on is automatically stored into the user's SVN account without any user interaction (username and password already provided so Python takes care of storage). Are there any libraries that can handle this kind of communicatio... | [
"There are Python bindings for SVN. They follow the C API, so present a fairly low-level interface, not very \"Pythonic\". I'm not sure how easy they are to install these days. I've tried to use it in the past, and found that it requires some digging into the C API documentation to figure out how to make it work.\n... | [
3,
1
] | [] | [] | [
"communicate",
"python",
"svn"
] | stackoverflow_0005944272_communicate_python_svn.txt |
Q:
python run bash command get bad result
Hi I'm trying to run this bash cmd on python 3.2. Here is the python code:
message = '\\x61'
shell_command = "echo -n -e '" + message + "' | md5"
print(shell_command)
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(event.communicate())
... | python run bash command get bad result | Hi I'm trying to run this bash cmd on python 3.2. Here is the python code:
message = '\\x61'
shell_command = "echo -n -e '" + message + "' | md5"
print(shell_command)
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
print(event.communicate())
this gave me next result:
echo -n -e '\x61' ... | [
"The key to this problem is when you say:\n\nBut when I run this printed cmd in bash...\n\nThe Popen function of the subprocess module does not necessarily use bash, it may use some other shell such as /bin/sh which will not necessarily handle the echo command identically to bash. On my system running the command i... | [
3,
1,
0,
0
] | [] | [] | [
"bash",
"cmd",
"python"
] | stackoverflow_0005943820_bash_cmd_python.txt |
Q:
Using easy_install inside a python script?
easy_install python extension allows to install python eggs from console like:
easy_install py2app
But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_insta... | Using easy_install inside a python script? | easy_install python extension allows to install python eggs from console like:
easy_install py2app
But is it possible to access easy_install functionality inside a python script? I means, without calling os.system( "easy_install py2app" ) but instead importing easy_install as a python module and using it's native meth... | [
"When I look at the setup tools source, it looks like you can try the following.\nfrom setuptools.command import easy_install\neasy_install.main( [\"-U\",\"py2app\"] )\n\n",
"from setuptools.command import easy_install\n\ndef install_with_easyinstall(package):\n easy_install.main([\"-U\", package]).\n\ninstall... | [
18,
4,
2,
0
] | [
"I think you can get to that by using either importing setuptools.\n"
] | [
-2
] | [
"python",
"setuptools"
] | stackoverflow_0000935111_python_setuptools.txt |
Q:
how do I remove columns from a collection of ndarrays that correspond to zero elements of one of the arrays?
I have some data in 3 arrays with shapes:
docLengths.shape = (10000,)
docIds.shape = (10000,)
docCounts.shape = (68,10000)
I want to obtain relative counts and their means and standard deviations for some ... | how do I remove columns from a collection of ndarrays that correspond to zero elements of one of the arrays? | I have some data in 3 arrays with shapes:
docLengths.shape = (10000,)
docIds.shape = (10000,)
docCounts.shape = (68,10000)
I want to obtain relative counts and their means and standard deviations for some i:
docRelCounts = docCounts/docLengths
relCountMeans = docRelCounts[i,:].mean()
relCountDeviations = docRelCounts[... | [
"Try this:\ndocRelCounts = docCounts/docLengths\n\ngoodDocRelCounts = docRelCounts[i,:][np.invert(np.isnan(docRelCounts[i,:]))]\nrelCountMeans = goodDocRelCounts.mean()\nrelCountDeviations = goodDocRelCounts.std()\n\nnp.isnan returns an array of the same shape with True where original array is NaN, False elsewhere.... | [
1,
0,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0005673984_numpy_python.txt |
Q:
How do I call a python scipt by php on a less powerful server to be run on an other more powerful server (cluster)?
I have a action.php script from where I call a python script like this:
$call_python = "../python/python myPythonScript.py ".$someArgument;
$python_output = Null; // stores every output generated by ... | How do I call a python scipt by php on a less powerful server to be run on an other more powerful server (cluster)? | I have a action.php script from where I call a python script like this:
$call_python = "../python/python myPythonScript.py ".$someArgument;
$python_output = Null; // stores every output generated by myPythonScript.py
$mystring = exec($call_python, $output_python);
I know, this is perhaps not the best way, but it works... | [
"You can easily replace your exec() call with ssh2_exec(). To get the output use stream_get_context() however. That's probably the sanest solution here.\nYou just need to open a connection to your secondary server beforehand. See ssh2_connect and ssh2_auth_password for that. And of course you need the ssh2 PHP ext... | [
2
] | [] | [] | [
"cluster_computing",
"php",
"python"
] | stackoverflow_0005944615_cluster_computing_php_python.txt |
Q:
sort a list of dicts by x then by y
I want to sort this info(name, points, and time):
list = [
{'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},
{'name':'KARL','points':50,'time': '0:03:00'}
]
so, what I want is the list sorted first by points made, then by time played (in my example, matt go first becau... | sort a list of dicts by x then by y | I want to sort this info(name, points, and time):
list = [
{'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},
{'name':'KARL','points':50,'time': '0:03:00'}
]
so, what I want is the list sorted first by points made, then by time played (in my example, matt go first because of his less time. any help?
I'm trying... | [
"Your example works for me. I would advise you not to use list as a variable name, since it is a builtin type.\nYou could try doing something like this also:\nlist.sort(key=lambda item: (item['points'], item['time']))\n\n",
"edit:\nexample list:\n>>> a = [\n... {'name':'JOHN', 'points' : 30, 'time' : '0:02:20... | [
27,
9,
3
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0005944630_list_python_sorting.txt |
Q:
Google App Engine : get_by_id result length?
How to I return the length of the get_by_id ??
For example I have
query = Model.get_by_id(1)
I tried
if len(query) == 1 and if query.count() == 1 both not working
A:
*Model.get_by_id()* returns only a single object if a single id is passed, it returns a list of objec... | Google App Engine : get_by_id result length? | How to I return the length of the get_by_id ??
For example I have
query = Model.get_by_id(1)
I tried
if len(query) == 1 and if query.count() == 1 both not working
| [
"*Model.get_by_id()* returns only a single object if a single id is passed, it returns a list of objects only when a list of id's is passed, which means it obvioulsy won't have len and count. \nif you want to check if query is not None, you can simply give\nquery=Model.get_by_id(1)\n\nif query is not None:\n\nif yo... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005944669_google_app_engine_python.txt |
Q:
trouble using lambda in python
I am trying to write a lambda where it takes the minutes and divides it by a range, then prints out the result.
I tried
list((lambda minutes: minutes / range),range(Numbe+1,1))
but list only takes one argument, any ideas? Minutes and Number the user supplies
I figured it ou... | trouble using lambda in python | I am trying to write a lambda where it takes the minutes and divides it by a range, then prints out the result.
I tried
list((lambda minutes: minutes / range),range(Numbe+1,1))
but list only takes one argument, any ideas? Minutes and Number the user supplies
I figured it out using
List=[]
Lis... | [
"Do you really need to use a lambda? Here is a list comprehension which most people seem to find easier to read\n[float(minutes)/number for minutes in range(1,number+1)]\n\nThe equivalent using a lambda function is\n map(lambda minutes: float(minutes)/number, range(1,number+1))\n\nAnd a shorter way to write that is... | [
4,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0005944769_lambda_python.txt |
Q:
Passing Linux boot opts to Init
I would like to pass some parameters to a customized Linux init via the boot options configured in the bootloader at boot.
I've written test init's in both Python and C. The Python version is able to see anything in the kernel boot options that doesn't have a '=' or '.' in it. The... | Passing Linux boot opts to Init | I would like to pass some parameters to a customized Linux init via the boot options configured in the bootloader at boot.
I've written test init's in both Python and C. The Python version is able to see anything in the kernel boot options that doesn't have a '=' or '.' in it. The values are found in sys.argv. Howev... | [
"I don't know C, but I think where is int i; (line 4) should be int i = 0;. If I am wrong, add a comment to my answer and I will delete it.\nEdit: you could also do i = 0 in the for loop: for(i = 0; i < argc; i++).\n",
"You need to initialize i to 0 as Artur said. If you dont the value of i is whatever happend to... | [
3,
2
] | [] | [] | [
"boot",
"c",
"init",
"linux",
"python"
] | stackoverflow_0005944692_boot_c_init_linux_python.txt |
Q:
When processing a file, how do I obtain the current line number?
When I am looping over a file using the construct below, I also want the current line number.
with codecs.open(filename, 'rb', 'utf8' ) as f:
retval = []
for line in f:
process(line)
Does something akin to this exist ... | When processing a file, how do I obtain the current line number? | When I am looping over a file using the construct below, I also want the current line number.
with codecs.open(filename, 'rb', 'utf8' ) as f:
retval = []
for line in f:
process(line)
Does something akin to this exist ?
for line, lineno in f:
| [
"for lineno, line in enumerate(f, start=1):\n\nIf you are stuck on a version of Python that doesn't allow you to set the starting number for enumerate (this feature was added in Python 2.6), and you want to use this feature, the best solution is probably to provide an implementation that does, rather than adjusting... | [
10,
1
] | [] | [] | [
"line_numbers",
"python"
] | stackoverflow_0005944908_line_numbers_python.txt |
Q:
What are some good examples of processes to automate for a python beginner to start with?
Trying to get some initial bearings on useful processes that a basic working knowledge of python can assist with or make less tedious. Specifically, processes that can be executed on the command line in a Linux environment. A... | What are some good examples of processes to automate for a python beginner to start with? | Trying to get some initial bearings on useful processes that a basic working knowledge of python can assist with or make less tedious. Specifically, processes that can be executed on the command line in a Linux environment. An example or two of both the tedious process as well as sample code to use as a starting point ... | [
"What you want to automate depends on what you are doing manually and what your role is ? If you are a system administrator (say) and if you have shell scripts written to automate some of the tasks (like server management, user account creation etc.) you can port them to Python. \n"
] | [
1
] | [] | [] | [
"command_line",
"linux",
"python"
] | stackoverflow_0005944764_command_line_linux_python.txt |
Q:
In NLTK pos_tag, why "hello" is classified as Noun?
I've tried
text = nltk.word_tokenize("hello, my name is John")
words = nltk.pos_tag(text)
for w in words:
print "%s = %s" % (w[0], w[1])
And I got:
hello = NN
, = ,
my = PRP$
name = NN
is = VBZ
John = NNP
A:
According to the Penn Treebank tagset, hello is... | In NLTK pos_tag, why "hello" is classified as Noun? | I've tried
text = nltk.word_tokenize("hello, my name is John")
words = nltk.pos_tag(text)
for w in words:
print "%s = %s" % (w[0], w[1])
And I got:
hello = NN
, = ,
my = PRP$
name = NN
is = VBZ
John = NNP
| [
"According to the Penn Treebank tagset, hello is definitely an interjection and is consistently tagged UH. The problem you're running into is that the taggers that NLTK ships with were most likely trained on the part of the Wall Street Journal section of the Penn Treebank that is available for free, which unfortun... | [
9,
2,
2
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0005932227_nlp_nltk_python.txt |
Q:
NSOutputStream or twisted reactor merging TCP packet data
I'm working on some networking code for an iPhone application that interfaces with a Python Twisted backend. I've been running into a problem recently where it appears as though either my NSOutputStream is doubling up the payload on send OR twisted is doubl... | NSOutputStream or twisted reactor merging TCP packet data | I'm working on some networking code for an iPhone application that interfaces with a Python Twisted backend. I've been running into a problem recently where it appears as though either my NSOutputStream is doubling up the payload on send OR twisted is doubling up the payload on receive.
I'm using the "Apple Recommended... | [
"\nI agree -- I shouldn't necessarily\n expect the buffer boundaries to match\n up, but I suppose it's a matter of\n predictable behavior.\n\nThere is no predictable behavior in TCP based communications; there may be any number of routers, NAT boundaries, goofy proxies or whatever in between you and the remote ... | [
1
] | [] | [] | [
"nsoutputstream",
"objective_c",
"python",
"twisted.internet"
] | stackoverflow_0005944208_nsoutputstream_objective_c_python_twisted.internet.txt |
Q:
Python build using wrong version of GCC on OS X
I am attempting to build the python package pycrypto. OS X has gcc-4.2 installed and not gcc-4.0, but python continues to attempt to use gcc-4.0. How can I get it to use gcc-4.2? Or should I go about this a different way.
I am getting the following error:
bash-3.2$ ... | Python build using wrong version of GCC on OS X | I am attempting to build the python package pycrypto. OS X has gcc-4.2 installed and not gcc-4.0, but python continues to attempt to use gcc-4.0. How can I get it to use gcc-4.2? Or should I go about this a different way.
I am getting the following error:
bash-3.2$
bash-3.2$ sudo python setup.py build
running build
r... | [
"Based on the path shown (/Library/Frameworks/Python.framework/Versions/2.6), it appears you have installed a 32-bit-only Python 2.6, perhaps using a python.org installer. When you build a Python package that includes a C extension module, the Python Distutils included with that Python instance will attempt to use... | [
16,
2,
1
] | [] | [] | [
"gcc",
"macos",
"python"
] | stackoverflow_0005944228_gcc_macos_python.txt |
Q:
Array allocation of SWIG C++ type from Python
I'm writing a python script for a program that has exposed its C++ API using SWIG.
A SWIG exposed function has an interface like this:
void writePixelsRect(JoxColor* colors, int left, int top, int width, int height);
JoxColor is a POD struct looking like this:
struct ... | Array allocation of SWIG C++ type from Python | I'm writing a python script for a program that has exposed its C++ API using SWIG.
A SWIG exposed function has an interface like this:
void writePixelsRect(JoxColor* colors, int left, int top, int width, int height);
JoxColor is a POD struct looking like this:
struct JoxColor {
float r, g, b, a;
};
I can easily c... | [
"This is kinda tricky, but could you, at least for this part of the code, use a pure-ctypes solution? Basically manually look at the symbols exported by the shared libary file to find the name that the writePixelsRect function was exported as. C++ does name mangling, so while it might just be writePixelsRect if t... | [
2,
0
] | [] | [] | [
"c++",
"ctypes",
"python",
"swig"
] | stackoverflow_0005862902_c++_ctypes_python_swig.txt |
Q:
How to log exceptions in appengine?
try:
#do something that raises an exception...
except:
logging.error('Error Message')
I want more than just "Error Message" to show in the logs. I want to see the traceback, or at least what the exception was, in the logs as well. How do I do that?
Thanks!
A:
logging.exce... | How to log exceptions in appengine? | try:
#do something that raises an exception...
except:
logging.error('Error Message')
I want more than just "Error Message" to show in the logs. I want to see the traceback, or at least what the exception was, in the logs as well. How do I do that?
Thanks!
| [
"logging.exception(msg[, *args])\nLogs a message with level ERROR on the root logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler.\nhttp://docs.python.org/library/logging.html#logging.exception\n",
"Thi... | [
8,
8,
3,
0
] | [] | [] | [
"error_handling",
"error_logging",
"google_app_engine",
"logging",
"python"
] | stackoverflow_0005944775_error_handling_error_logging_google_app_engine_logging_python.txt |
Q:
How to handle divide-by-zero error when hashing values in two sequences
I have two lists of fixed-length tuples. This function calculates a fraction (ratio) for respective elements (note, fX() does not use comprehension for readability here).
>>> def fX(a,b):
>>> c=[]
>>> for i in range(len(a)):
>>> ... | How to handle divide-by-zero error when hashing values in two sequences | I have two lists of fixed-length tuples. This function calculates a fraction (ratio) for respective elements (note, fX() does not use comprehension for readability here).
>>> def fX(a,b):
>>> c=[]
>>> for i in range(len(a)):
>>> c.append([a[i][x]/float(a[i][x]+b[i][x]) for x in range(len(a[i]))])
>>>... | [
"def f_cell(a, b):\n try: return a / float(a + b) # EAFP\n except: return 0.0 # Or whatever other value you want for this case.\n\ndef fY(a,b): \n return [\n [f_cell(a_cell, b_cell) for a_cell, b_cell in zip(a_row, b_row)]\n for a_row, b_row in zip(a, b)\n ]\n\n",
"Use the a if x else b... | [
4,
3,
0
] | [
"Well you CAN make a hash function without checking the denominator. The trick is to guarantee the denominator is never 0. You can do this by bitwise or-ing in something into the denominator, making sure at least one non sign bit is set before division is done.\nHere's a sample fY:\ndef fY(a,b): \n c=[] \n fo... | [
-1
] | [
"list_comprehension",
"mapping",
"python"
] | stackoverflow_0005944092_list_comprehension_mapping_python.txt |
Q:
python programming query
I'm new to Python programming.
My question is where to write python programs in linux--
in terminal or
any writing pad like gedit etc
Should we write one program again and again for running or we should call the program and run it.
A:
After you install Python (it's installed by default... | python programming query | I'm new to Python programming.
My question is where to write python programs in linux--
in terminal or
any writing pad like gedit etc
Should we write one program again and again for running or we should call the program and run it.
| [
"After you install Python (it's installed by default on most Linux-es), you have two options:\n\nTerminal. Just type python <ENTER> and you will be taken to the Python interpreter interactive prompt. For anything but the most basic stuff, however, you may want to intall IPython - an alternative interactive prompt t... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005945665_python.txt |
Q:
Printing docstrings in Python 3
How do you print doc strings in python 3.1.x?
I tried with the re and sys modules as a test and I keep getting errors. Thanks
import re
print(re._doc_)
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
print(re._doc_)
AttributeError: 'module' object h... | Printing docstrings in Python 3 | How do you print doc strings in python 3.1.x?
I tried with the re and sys modules as a test and I keep getting errors. Thanks
import re
print(re._doc_)
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
print(re._doc_)
AttributeError: 'module' object has no attribute '_doc_'
| [
"It's called __doc__, not _doc_.\nimport re\nprint(re.__doc__)\n\nWorks just fine.\n"
] | [
4
] | [] | [] | [
"docstring",
"python",
"python_3.x"
] | stackoverflow_0005945289_docstring_python_python_3.x.txt |
Q:
python setup.py question
So I have a folder structure something like this:
pckA - core
- io
pckB - core
- io
- main
Now I have to create a setup.py file for both there packages. My current approach is :
from distutils.core import setup
import setuptools
setup(
name='ProjectExternals',
vers... | python setup.py question | So I have a folder structure something like this:
pckA - core
- io
pckB - core
- io
- main
Now I have to create a setup.py file for both there packages. My current approach is :
from distutils.core import setup
import setuptools
setup(
name='ProjectExternals',
version='0.1dev',
packages=["p... | [
"No, if you just want the whole package, specifying its name (i.e. pckA) is enough - no need to list all the modules in it. distutils will recursively discover them.\nSo in your case:\npackages=['pckA', 'pckB'],\n\nDoes the trick. Here's a quote from the docs:\n\nThe packages option tells the\n Distutils to proces... | [
3
] | [] | [] | [
"python",
"setup.py"
] | stackoverflow_0005945914_python_setup.py.txt |
Q:
Simple Music Player Wont Play
I'm trying to write a simple music player. For some reason after I select a mp3 file and hit the play button, no sound occurs. No error, nothing. It seems to skip right over the command. Anyone know why it may be doing this? If there is a better way to play music with python, what is ... | Simple Music Player Wont Play | I'm trying to write a simple music player. For some reason after I select a mp3 file and hit the play button, no sound occurs. No error, nothing. It seems to skip right over the command. Anyone know why it may be doing this? If there is a better way to play music with python, what is it?
from win32com.client import Di... | [
"This probably has something to do with threading.\nIn any case, there are other GUI toolkits for Python, such as WxPython, and there are mp3 player apps written in Python that you could study.\n"
] | [
0
] | [] | [] | [
"python",
"tkinter",
"win32com",
"windows_7"
] | stackoverflow_0005945553_python_tkinter_win32com_windows_7.txt |
Q:
Learning python and having trouble with 1st program
I wrote this code and it is failing at line 11 on the "target_dir" command with invalid syntax I have a vm ubuntu and I just copy and pasted the code and it worked there but not in my win7 and I am not sure why. I was reading another question with similar code bu... | Learning python and having trouble with 1st program | I wrote this code and it is failing at line 11 on the "target_dir" command with invalid syntax I have a vm ubuntu and I just copy and pasted the code and it worked there but not in my win7 and I am not sure why. I was reading another question with similar code but it had a different error and noticed that someone said ... | [
"source = ['\"D:\\\\Warlock\"', 'C:\\\\Druid' is missing an end bracket. Should be source = ['\"D:\\\\Warlock\"', 'C:\\\\Druid'].\nEdit: Also, \nzip_commnad = \"7z a -tzip {0} {1}\" .format(target, ' '.join(source))\n print(zip_command)\n\nshould be\nzip_command = \"7z a -tzip {0} {1}\" .format(target, ' '.join(... | [
7,
1
] | [] | [] | [
"python"
] | stackoverflow_0005943282_python.txt |
Q:
Trigger inotify events
I have a python script using Pyinotify that does some stuff on IN_MOVED_TO. What's the easiest way to trigger the script on specific files, using another python script, without actually moving the files out and back in?
A:
Create a "glue function". Say the original code is:
def some_inane_... | Trigger inotify events | I have a python script using Pyinotify that does some stuff on IN_MOVED_TO. What's the easiest way to trigger the script on specific files, using another python script, without actually moving the files out and back in?
| [
"Create a \"glue function\". Say the original code is:\ndef some_inane_os_api(with, lots, of, arguments):\n ... your code ...\n\nReplace this with:\ndef some_inane_os_api(with, lots, of, arguments):\n your_code(just, the, arguments, you need)\n\ndef your_code(...)\n ... your code ...\n\nNow you can call yo... | [
1,
0
] | [] | [] | [
"pyinotify",
"python"
] | stackoverflow_0005939078_pyinotify_python.txt |
Q:
python simple regex help
Hi first time regex user here.
Just trying to figure out some regex but need some help.
I have a text file with the following items:
10:67 12:12 01:50 23:60 23:50
And I'm trying to get a list of the valid times so the
output should be:
['12:12', '01:50', '23:50']
Here is my code:
import r... | python simple regex help | Hi first time regex user here.
Just trying to figure out some regex but need some help.
I have a text file with the following items:
10:67 12:12 01:50 23:60 23:50
And I'm trying to get a list of the valid times so the
output should be:
['12:12', '01:50', '23:50']
Here is my code:
import re
inFile = open("text.txt")
te... | [
"Python apparently only prints the first group (that's ([01]\\d|2[0-3]) in your case). If you make a non-capturing group ((?: ... )) of it, you should see the desired result:\ntext = '10:67 12:12 01:50 23:60 23:50'\npattern = re.findall('(?:[01]\\d|2[0-3]):[0-5]\\d', text)\nprint pattern\n\ndisplays:\n['12:12', '01... | [
6
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005946905_python_regex.txt |
Q:
wxPython need some kind of tree representation
I have reached a point in my project from which I'm not sure how to continue. My current task is to give the user a possibility to create a folder structure for some custom projects. So basically the user should be able to add a new folder , add some data to the folde... | wxPython need some kind of tree representation | I have reached a point in my project from which I'm not sure how to continue. My current task is to give the user a possibility to create a folder structure for some custom projects. So basically the user should be able to add a new folder , add some data to the folder and of course visualize his project folder/data st... | [
"There are a few widgets you could use:\nwx.TreeCtrl which would probably do everything you are looking to do.\nAn alternative widget that functions differently (Incorporates MVC) would be the wx.lib.mvctree.MVCTree\nThere are even more again that you could customise (Most extending wx.TreeCtrl). Why don't you have... | [
1
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0005947208_python_wxpython_wxwidgets.txt |
Q:
Recursive Nested Lists
I'm having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and an index, and return the part of the list at that index. From this given function, recursivel... | Recursive Nested Lists | I'm having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and an index, and return the part of the list at that index. From this given function, recursively find the value at the give... | [
"This may do you, but I'm still not 100% sure what you are looking for...\n>>> def findItem(nested, pos):\n if pos[0] == 1:\n return nested[pos[1]-1]\n else:\n nextLevelDown = []\n for item in nested:\n if type(item) == type([]):\n nextLevelDown = nextLevelDown +... | [
1,
0
] | [] | [] | [
"list",
"nested",
"python",
"recursion"
] | stackoverflow_0005946648_list_nested_python_recursion.txt |
Q:
Secure python web app
i have python web app build on top of BaseHTTPServer, which runs on specyfic port. It runs system commands and shows output. I want do limit access to this app. What are posible ways to do it? Requirements:
it must not be limited to LAN
simple to implement/deploy
A:
Common methods: VPN acc... | Secure python web app | i have python web app build on top of BaseHTTPServer, which runs on specyfic port. It runs system commands and shows output. I want do limit access to this app. What are posible ways to do it? Requirements:
it must not be limited to LAN
simple to implement/deploy
| [
"Common methods: VPN access. Firewalls, logging, denyhosts style defences, complicated root passwords, no su, run as its own user.\n(if it was my personal server)\nLogic bombs\n",
"Easiest and most secure: Put Apache or Nginx in front of it with an HTTPS proxy.\nUpdate: Or VPN access as suggested by Jakob. Good i... | [
0,
0
] | [] | [] | [
"python",
"security",
"web_applications"
] | stackoverflow_0005947849_python_security_web_applications.txt |
Q:
Google App Engine Python Cron
I've been trying for a few days now to get Google App Engine to run a cron Python script which will simply execute a script hosted on a server of mine.
It doesn't need to post any data to the page, simply open a connection, wait for it to finish then email me.
The code I've previously... | Google App Engine Python Cron | I've been trying for a few days now to get Google App Engine to run a cron Python script which will simply execute a script hosted on a server of mine.
It doesn't need to post any data to the page, simply open a connection, wait for it to finish then email me.
The code I've previously written has logged as "successful"... | [
"Mix of weird things was happening here.\nFirstly, app.yaml I had to place my /cron handler before the root was set:\nhandlers:\n- url: /cron\n script: assets/backup/main.py\n\n- url: /\n static_files: assets/index.html\n upload: assets/index.html\n\nOtherwise I'd get crazy errors about not being able to find th... | [
4
] | [] | [] | [
"cron",
"email",
"google_app_engine",
"python",
"urllib"
] | stackoverflow_0005942312_cron_email_google_app_engine_python_urllib.txt |
Q:
Vectorize over the rows of an array
I have an array X and I want to apply a function f to all the rows of X:
# silly example
X = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]], 'i')
def f(row): return sum(row)
y = numpy.vectorize(f, 'i')(rows(X))
Now, y should be array([15,30], 'i'). Which meth... | Vectorize over the rows of an array | I have an array X and I want to apply a function f to all the rows of X:
# silly example
X = numpy.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0]], 'i')
def f(row): return sum(row)
y = numpy.vectorize(f, 'i')(rows(X))
Now, y should be array([15,30], 'i'). Which method or slicing magic will implement rows i... | [
"NumPy implements the concept of \"action over a particular axis\". The general function is numpy.apply_along_axis():\n>>> numpy.apply_along_axis(sum, 1, X)\narray([15, 30])\n\n(where sum can of course be replaced by anything).\n",
"Does it have to be something provided by numpy? Because I just see a list compre... | [
8,
0,
0
] | [] | [] | [
"numpy",
"python",
"vectorization"
] | stackoverflow_0005941420_numpy_python_vectorization.txt |
Q:
Good semantics, Subclass or emulate?
I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantage... | Good semantics, Subclass or emulate? | I have been using python for a while now and Im happy using it in most forms but I am wondering which form is more pythonic. Is it right to emulate objects and types or is it better to subclass or inherit from these types. I can see advantages for both and also the disadvantages. Whats the correct method to be doing th... | [
"Key question you have to ask yourself here is: \n\n\"How should my class change if the 'parent' class changes?\" \n\nImagine new methods are added to dict which you don't override in your UniqueDict. If you want to express that UniqueDict is simply a small derivation in behaviour from dict's behaviour, then you'd ... | [
3,
1,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0005948110_coding_style_python.txt |
Q:
Google Appengine large amount of index data (python)
We've just outgrown our free data usage quota in AppEngine which is great but looking at our data breakup, only 200M of the 1G is actual data / meta-data (still can't believe they pin you for that one) and the rest I assume is indexes from reading the help forum... | Google Appengine large amount of index data (python) | We've just outgrown our free data usage quota in AppEngine which is great but looking at our data breakup, only 200M of the 1G is actual data / meta-data (still can't believe they pin you for that one) and the rest I assume is indexes from reading the help forums. Does anyone know if this is normal and if not are there... | [
"Depends on what you are storing in it. We've got 32GB of String/Integer/Text data, 181GB of indexes/meta-data and 812GB of blobs (we are storing a lot of small images). So it really depends on your queries and settings.\nYou can run\n appcfg.py vacuum_indexes .\n\nto vacum indexes (remove unused stuff).\nGAE aut... | [
3
] | [] | [] | [
"bigtable",
"google_app_engine",
"indexing",
"python"
] | stackoverflow_0005948068_bigtable_google_app_engine_indexing_python.txt |
Q:
Django Models Group By
I have this simple SQL query -
SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid='2' GROUP BY pid;
How do I get this using Django ORM (i.e. django models). Basically I am not getting how to do GROUP BY?
A:
XML_table.objects.filter(suid='2').values('pid').annotate(docs=Count('pid')).... | Django Models Group By | I have this simple SQL query -
SELECT pid, COUNT(*) AS docs FROM xml_table WHERE suid='2' GROUP BY pid;
How do I get this using Django ORM (i.e. django models). Basically I am not getting how to do GROUP BY?
| [
"XML_table.objects.filter(suid='2').values('pid').annotate(docs=Count('pid')).order_by()\nDocs\n",
"This works very nicely.\nfrom collections import defaultdict\ncount = defaultdict( int )\nfor doc in XML_Table.objects.filter(suid='2'):\n count[doc.pid] += 1\n\nIt's not SQL. Often it's faster than SQL because... | [
6,
1
] | [] | [] | [
"django",
"django_models",
"django_orm",
"group_by",
"python"
] | stackoverflow_0005947475_django_django_models_django_orm_group_by_python.txt |
Q:
python regular expression
I am newbie to python. I have an array of words and each word has to be checked to see whether it contains any special characters or digits. If it contains so then i have to skip that word. How should i do this?
A:
Does it have to be a regular expression? If not, you can use the isalph... | python regular expression | I am newbie to python. I have an array of words and each word has to be checked to see whether it contains any special characters or digits. If it contains so then i have to skip that word. How should i do this?
| [
"Does it have to be a regular expression? If not, you can use the isalpha() string method.\n",
"My reading of the problem is that you want to discard any words that contain non-alphabetical characters. Try the following:\n>>> array = ['hello', 'hello2', '?hello', '?hello2']\n>>> filtered = filter(str.isalpha, ar... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005948528_python.txt |
Q:
Python - update configuration while running script
I have a python script which is constantly polling data. The script is constantly running and should never stop.
The script polls data from a track of keywords which are passed to it when the script is first run.
What would be the best way to update this track w... | Python - update configuration while running script | I have a python script which is constantly polling data. The script is constantly running and should never stop.
The script polls data from a track of keywords which are passed to it when the script is first run.
What would be the best way to update this track without stopping the script from another python script?
T... | [
"It's better to encapsulate this settings file in a database. A simple SQLite DB file is enough - SQLite support is built-in with Python so no extra effort is required.\nThe advantage of a DB is that you won't run into race conditions of partially-written files, etc. The \"configuration-adding\" script adds keyword... | [
5,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005949242_python.txt |
Q:
Problems with multiple panels in a single notebook page
I am creating a program to calculate D&D scores. I have all the backend done, and I want to get the GUI done now.
What I am trying to do here is have a static panel for certain buttons (next, previous, ok, cancel, etc.). The panel is not cooperating.
I want t... | Problems with multiple panels in a single notebook page | I am creating a program to calculate D&D scores. I have all the backend done, and I want to get the GUI done now.
What I am trying to do here is have a static panel for certain buttons (next, previous, ok, cancel, etc.). The panel is not cooperating.
I want to try to get it on the bottom right (where next/previous butt... | [
"You've got parenting problems!\nFor example, you want the widget self.lblRoll1 to be on the panelControl therefore you should make it a child of it.\ne.g.\nself.lblRoll1 = wx.StaticText(panelControl,label = \"0\")\n\nThis is your problem -it occurs throughout your code.\nAn indispensable tool for solving these typ... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005945299_python_wxpython.txt |
Q:
label every decade in colorbar for log imshow
I want to plot some data in a matrix. The colors = z-values are logarithmic. My Problem is that only some of the ticks are labeled. To be precise "1e1, 1e10, ...". If those values are outside the data range there are no labels at all (but ticks). I want to have labels ... | label every decade in colorbar for log imshow | I want to plot some data in a matrix. The colors = z-values are logarithmic. My Problem is that only some of the ticks are labeled. To be precise "1e1, 1e10, ...". If those values are outside the data range there are no labels at all (but ticks). I want to have labels for every decade ie "1e1, 1e2, 1e3, ..." and also "... | [] | [] | [
"Take a look at the set_ticks method of matplotlib.axis.Axis. It's documented here.\n"
] | [
-1
] | [
"logging",
"matplotlib",
"python"
] | stackoverflow_0005948412_logging_matplotlib_python.txt |
Q:
Print to UTF-8 encoded file, with platform-dependent newlines?
In Python, what is the best way to write to a UTF-8 encoded file with platform-dependent newlines? the solution would ideally work quite transparently in a program that does a lot of printing in Python 2. (Information about Python 3 is welcome too!)
... | Print to UTF-8 encoded file, with platform-dependent newlines? | In Python, what is the best way to write to a UTF-8 encoded file with platform-dependent newlines? the solution would ideally work quite transparently in a program that does a lot of printing in Python 2. (Information about Python 3 is welcome too!)
In fact, the standard way of writing to a UTF-8 file seems to be cod... | [
"Presuming Python 2.7.1 (that's the docs that you quoted): The 'wt' mode is not documented (the ONLY mode documented is 'r'), and does not work -- the codecs module appends 'b' to the mode, which causes it to fail:\n>>> f = codecs.open('bar.txt', 'wt', encoding='utf8')\nTraceback (most recent call last):\n File \"... | [
11,
4,
0
] | [] | [] | [
"codec",
"newline",
"python",
"text",
"utf_8"
] | stackoverflow_0005941988_codec_newline_python_text_utf_8.txt |
Q:
Send Data From Flex to Python (GAE)
I'm working on a project that runs off Google App Engine (Python) which stores various user details inside GAE's datastore. I have Flex content which users can use and once done the Flex app needs to send data to the Python backend to 'mark' the user off for that task. Any sugge... | Send Data From Flex to Python (GAE) | I'm working on a project that runs off Google App Engine (Python) which stores various user details inside GAE's datastore. I have Flex content which users can use and once done the Flex app needs to send data to the Python backend to 'mark' the user off for that task. Any suggestions?
| [
"Have flex send a request to the Python server. COuld be a form post or JSON data or whatever.\n",
"Have a look on the following:\nhttp://fernandoacorreia.wordpress.com/2008/07/15/flex-and-python-project/\nIt may help.\n",
"You can use pyamf gateway for django and tipfy. I have a similar open source project wit... | [
1,
0,
0
] | [] | [] | [
"apache_flex",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005947727_apache_flex_google_app_engine_google_cloud_datastore_python.txt |
Q:
PyCharm and filters for external tools
I'm trying out PyCharm for Django development and so far am extremely happy. My team strictly follows PEP8 formatting and we use the pep8 command line program to check to make sure our code conforms.
I've configured an external tool command to run pep8 and it works good. I se... | PyCharm and filters for external tools | I'm trying out PyCharm for Django development and so far am extremely happy. My team strictly follows PEP8 formatting and we use the pep8 command line program to check to make sure our code conforms.
I've configured an external tool command to run pep8 and it works good. I see the capability to create filters that will... | [
"You've missed a $ off the end of COLUMN. I followed your steps and I have it working perfectly. Your filter should be:\n$FILE_PATH$:$LINE$:$COLUMN$:.*\n\nUpdate: To have it work for PyCharm 1.5 use:\n$FILE_PATH$\\:$LINE$\\:$COLUMN$\\:.*\n\n",
"PyCharm expects full file path for the links to work, not just the na... | [
16,
5
] | [] | [] | [
"pep8",
"pycharm",
"python",
"regex"
] | stackoverflow_0005436540_pep8_pycharm_python_regex.txt |
Q:
determining URL that forwarded
I have a series of different domain names that I would like to all point (via URL forwarding from my domain host) to a google app engine application that reads what the forwarding URL is. So if the domain typed in was original XYZ.com, then when I am forwarded to my application, I ca... | determining URL that forwarded | I have a series of different domain names that I would like to all point (via URL forwarding from my domain host) to a google app engine application that reads what the forwarding URL is. So if the domain typed in was original XYZ.com, then when I am forwarded to my application, I can return what that original domain n... | [
"Generally, the target of a 301/302 redirect can't determine what URL issued the redirect. If the user is redirected by client-side code, the referring page should be present in the \"Referer\" request header. For server-side redirects, I don't believe it's standard for user agents to populate (or override) the Ref... | [
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python",
"url"
] | stackoverflow_0005951035_google_app_engine_python_url.txt |
Q:
Integrating Boost.Python with Visual Studio 8
I'm having a bit of trouble finding a guide that allows me to integrate the Boost.Python compilation into VS 8. It seems like it depends heavily on this bjam utility to build the source, but there isn't any mention of how this can integrate into VS 8 interface.
I can ... | Integrating Boost.Python with Visual Studio 8 | I'm having a bit of trouble finding a guide that allows me to integrate the Boost.Python compilation into VS 8. It seems like it depends heavily on this bjam utility to build the source, but there isn't any mention of how this can integrate into VS 8 interface.
I can see that the bjam program calls VS 8 to do much of ... | [
"bjam is used for compiling boost itself (although your can use it as configuration tool for your code aswell). Running the utility should compile the library and does not require any further work, afaik.\nThe include and library paths you have listed in your second post are correct, as far as I can tell (assuming ... | [
3,
0
] | [] | [] | [
"boost",
"c++",
"python"
] | stackoverflow_0005553798_boost_c++_python.txt |
Q:
Why is Pip looking for download cache if the same exact package is already installed, when doing an --upgrade
This is on windows. In the Global Site packages I have installed lxml binary(.egg file) . And now I am creating a virtualenv and trying to get the same egg from the global environment.
virtualenv.exe mynew... | Why is Pip looking for download cache if the same exact package is already installed, when doing an --upgrade | This is on windows. In the Global Site packages I have installed lxml binary(.egg file) . And now I am creating a virtualenv and trying to get the same egg from the global environment.
virtualenv.exe mynewvenv
call mynewvenv\Scripts\activate.bat
So "pip freeze" gives me the egg which I installed in my global environme... | [
"When you use pip install --upgrade, it always (re)install the package and its dependencies.\nIIRC it is the only way to force reinstallation.\n"
] | [
1
] | [] | [] | [
"easy_install",
"installation",
"pip",
"python"
] | stackoverflow_0005937756_easy_install_installation_pip_python.txt |
Q:
Is there a more efficient one liner to initialize a variable based on a condition?
Can the atype variable be initialized via a one liner ?
def detect(dt,result):
""" prints the type of date """
atype = 'unknown'
if 'greg' in result:
atype = 'Gregorian'
elif 'eth' in result:
atype = ... | Is there a more efficient one liner to initialize a variable based on a condition? | Can the atype variable be initialized via a one liner ?
def detect(dt,result):
""" prints the type of date """
atype = 'unknown'
if 'greg' in result:
atype = 'Gregorian'
elif 'eth' in result:
atype = 'Ethiopian'
print '%s is in %s format.' % (dt,atype)
| [
"You could use a pair of conditional expressions — and no parenthesis are necessary at all; just like Python knows that 1 + 2 + 3 should be done reasonably from left-to-right, so conditional expressions can be written with one clause after another without any fear of the interpreter getting confused. Line breaks an... | [
4,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005949180_python.txt |
Q:
Presenting REST web-service interface to clients
One of resources in my RESTfull web-service, which performs a search operation, has a lot of criteria/parameters.
In the current implementation this search criteria is passed like a dictionary with option mnemonics as keys. E.g.
{'fieldl_greater_equal' : <value>,
'... | Presenting REST web-service interface to clients | One of resources in my RESTfull web-service, which performs a search operation, has a lot of criteria/parameters.
In the current implementation this search criteria is passed like a dictionary with option mnemonics as keys. E.g.
{'fieldl_greater_equal' : <value>,
'field2_like' : <value>,
...}
The questions are:
Wha... | [
"First. \"search\" can mean almost anything. It helps to be very, very clear on what the use case is for your GET request.\nYou have three essential choices for \"search\". \n\nQuery String. ?param1=this¶m2=that\nFragment. #param1=this¶m2=that\nURL path element. /this/that\n\nThe Path Element is someth... | [
3,
0
] | [] | [] | [
"architecture",
"interface",
"python",
"rest"
] | stackoverflow_0005949996_architecture_interface_python_rest.txt |
Q:
Conditional for negative integer
I'm defining a function that calculates the standard deviation of a list. Sometimes the mean of this list is negative and so my function can't take the square root of a negative, returning me with an error.
This seems simple, I just can't think of it. I want to write a conditional... | Conditional for negative integer | I'm defining a function that calculates the standard deviation of a list. Sometimes the mean of this list is negative and so my function can't take the square root of a negative, returning me with an error.
This seems simple, I just can't think of it. I want to write a conditional for my function saying that if there ... | [
"You appear to have misapplied the formula for standard deviation. You shouldn't need to handle the case of square root of negative numbers at all. You need to square each difference between the value and the mean before summing, like this:\ndef stdevValue(lst):\n m = meanValue(x) # wherever this comes from\n ... | [
16,
2
] | [
"If you want to really get creative, you can square and square-root:\n>>> import math\n>>> x = -5\n>>> math.sqrt((-5)**2)\n5.0\n\nCheers\n"
] | [
-1
] | [
"bioinformatics",
"conditional",
"math",
"python"
] | stackoverflow_0005943651_bioinformatics_conditional_math_python.txt |
Q:
How to know the system is Debian or CentOS in Python?
I want to write some install scripts by python, it should know the OS to choose either apt command or yum command.
It seems sys.platform can tell 'win32' or the others, but how to know it is working on Debian or CentOS in Python?
A:
The platform module in th... | How to know the system is Debian or CentOS in Python? | I want to write some install scripts by python, it should know the OS to choose either apt command or yum command.
It seems sys.platform can tell 'win32' or the others, but how to know it is working on Debian or CentOS in Python?
| [
"The platform module in the standard library has what you want.\nimport platform\nprint platform.linux_distribution()\n\n",
"If you just need to know whether to use yum or apt, one approach is simply to pick one of those commands and try it. If it works, it works; if not, catch the exception and try the other co... | [
11,
3
] | [] | [] | [
"apt",
"centos",
"debian",
"python",
"yum"
] | stackoverflow_0005951930_apt_centos_debian_python_yum.txt |
Q:
How to do a safe binary comparison in Python?
I have the following piece of code that is throwing a warning:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
try:
f = open_old(filename, "rb")
aBuf = f.read(4)
f.close()
except:
... | How to do a safe binary comparison in Python? | I have the following piece of code that is throwing a warning:
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
try:
f = open_old(filename, "rb")
aBuf = f.read(4)
f.close()
except:
aBuf=b''
if aBuf[:3] == b'\xEF\xBB\xBF':
print... | [
"The solution is to convert the string to bytes after you read it: aBuf = bytes(f.read(4)).\n"
] | [
1
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0005950553_python_unicode.txt |
Q:
calling a process from python
I am calling a perl script from python. The perl script retrieves a large data set in batches from a webserver which takes time. This perl script is executed in the loop. It does the job fairly well but during the last run of the loop, while the script is still downloading, it execute... | calling a process from python | I am calling a perl script from python. The perl script retrieves a large data set in batches from a webserver which takes time. This perl script is executed in the loop. It does the job fairly well but during the last run of the loop, while the script is still downloading, it executes the rest of the python code.
I wa... | [
"Use subprocess.Popen(). Check out this blog post:\nhttp://trifoliummedium.blogspot.com/2010/12/running-command-line-with-python-and.html\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005952386_python.txt |
Q:
Simulating a simple physics related scenario
I am a total beginner in both simulations so this question might be silly. If so, please feel free to edit it. I am trying to simulate the following scenario in Python. I randomly place a few small particles in a 2D field with fixed dimentions. Each particle has a radiu... | Simulating a simple physics related scenario | I am a total beginner in both simulations so this question might be silly. If so, please feel free to edit it. I am trying to simulate the following scenario in Python. I randomly place a few small particles in a 2D field with fixed dimentions. Each particle has a radius of effect r. If the first particle has the secon... | [
"Googling for python library vector 2d returned http://www.supereffective.org/pages/Vector-2d-Vector-Library as the top hit, which seems like a competent library (containing projection-and-perpendicularization, normalization, rotation, scaling, etc.)\nAs long as the number of particles isn't too large, this should ... | [
2,
1
] | [] | [] | [
"physics",
"python"
] | stackoverflow_0005720000_physics_python.txt |
Q:
how to communicate two separate python processes?
I have two python programs and I want to communicate them.
Both of them are system services and none of them is forked by parent process.
Is there any way to do this without using sockets?
(eg by crating some Queue -> serialize it -> deserialize by other process ... | how to communicate two separate python processes? | I have two python programs and I want to communicate them.
Both of them are system services and none of them is forked by parent process.
Is there any way to do this without using sockets?
(eg by crating some Queue -> serialize it -> deserialize by other process and perform communication; or write on file process id ... | [
"Your best bet is ZeroMQ, which is designed for, and extremely fast at IPC (also supports TCP/multicast messaging as well). The Python bindings are really nice, and easy to work with. There is a nice introduction to ZeroMQ with Python here: http://nichol.as/zeromq-an-introduction. If you were planning to expand thi... | [
5,
1
] | [] | [] | [
"multiprocessing",
"parallel_processing",
"process",
"python"
] | stackoverflow_0005952408_multiprocessing_parallel_processing_process_python.txt |
Q:
Cant iterate database for building treectrl in WxPython
import wx
import sqlite3 as lite
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 350))
vbox = wx.BoxSizer(wx.VERTICAL)
self.tree = wx.Tr... | Cant iterate database for building treectrl in WxPython | import wx
import sqlite3 as lite
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 350))
vbox = wx.BoxSizer(wx.VERTICAL)
self.tree = wx.TreeCtrl( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, ... | [
"Are you sure that the gruplar and noktalar variables are iterable? Add some lines to print those and make sure you're iterating over something. Otherwise, the code looks right to me.\n"
] | [
0
] | [] | [] | [
"python",
"sqlite",
"wxpython"
] | stackoverflow_0005951544_python_sqlite_wxpython.txt |
Q:
How to convert a script in Python to C++?
I need to convert python script How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup to c++ code. Is there any conversion tool for that? Can anyone provide C++ code for Manifest.mbdb parser?
A:
Try ShedSkin
From the website:
Shed Skin is an experimental compi... | How to convert a script in Python to C++? | I need to convert python script How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup to c++ code. Is there any conversion tool for that? Can anyone provide C++ code for Manifest.mbdb parser?
| [
"Try ShedSkin\nFrom the website:\n\nShed Skin is an experimental compiler, that can translate pure, but implicitly statically typed Python programs into optimized C++. It can generate stand-alone programs or extension modules that can be imported and used in larger Python programs. \n\n"
] | [
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0005949803_c++_python.txt |
Q:
Problem running pylon webtests. ImportError and TestController is not defined errror
I have directory structure as follow:
gnukhata/tests/functional.
In functional folder I have web tests files. Following is the sample test.
from gnukhata.tests import *
class TestVendorController(TestController):
def test_index(... | Problem running pylon webtests. ImportError and TestController is not defined errror | I have directory structure as follow:
gnukhata/tests/functional.
In functional folder I have web tests files. Following is the sample test.
from gnukhata.tests import *
class TestVendorController(TestController):
def test_index(self):
response = self.app.get(url(controller='vendor', action='index'))
After runnin... | [
"Try my most simple configuration and let me know if it work:\nimport logging\n\nfrom pylons import request, response, session, tmpl_context as c, url\nfrom pylons.controllers.util import abort, redirect\n\nfrom gnukhata.lib.base import BaseController, render\nfrom gnukhata import model\nimport gnukhata.model.meta ... | [
0,
0
] | [] | [] | [
"nosetests",
"pylons",
"python",
"unit_testing"
] | stackoverflow_0005945583_nosetests_pylons_python_unit_testing.txt |
Q:
Python eigenvectors
eigenvalues, eigenvectors = linalg.eig(K)
How can I print just eigenvectors of len(K). So if there is K, 2x2 matrix, I get 4 eigenvectors, how can I print just 2 of them if there is len(K)=2....
Many thanks
A:
You are getting two vectors of length two, not four vectors. For example:
In [1]: ... | Python eigenvectors | eigenvalues, eigenvectors = linalg.eig(K)
How can I print just eigenvectors of len(K). So if there is K, 2x2 matrix, I get 4 eigenvectors, how can I print just 2 of them if there is len(K)=2....
Many thanks
| [
"You are getting two vectors of length two, not four vectors. For example:\nIn [1]: import numpy as np\n\nIn [2]: K=np.random.normal(size=(2,2))\n\nIn [3]: eigenvalues, eigenvectors = np.linalg.eig(K)\n\nIn [4]: eigenvectors\nOut[4]: \narray([[ 0.83022467+0.j , 0.83022467+0.j ],\n [ 0.09133956+... | [
12,
0
] | [] | [] | [
"eigenvector",
"python"
] | stackoverflow_0005953297_eigenvector_python.txt |
Q:
Error while transforming .py to .exe
When I try to transform my script in an executable, I get this error after it's done:
Traceback (most recent call last):
File "shd-WinResize.py", line 4, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading win32api.py... | Error while transforming .py to .exe | When I try to transform my script in an executable, I get this error after it's done:
Traceback (most recent call last):
File "shd-WinResize.py", line 4, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading win32api.pyd
I'm using this script to convert:
from ... | [
"PY2EXE in Windows Vista and Windows 7 apparantly gets confused by some of the DLLs it needs to import. Here's the solution, which was inspired by another post:\nfrom distutils.core import setup\nimport py2exe, sys, os\n\nsys.argv.append('py2exe')\n\nsetup(\n options={\n \"py2exe\":{\n \"dll_ex... | [
0
] | [] | [] | [
"py2exe",
"python",
"winapi"
] | stackoverflow_0002339583_py2exe_python_winapi.txt |
Q:
sqlalchemy: referencing label()'d column in a filter or clauselement
I'm trying to perform a query that works across a many->many relation ship between bmarks and tags with a secondary table of bmarks_tags. The query involves several subqueries and I have a need to DISTINCT a column. I later want to join that to a... | sqlalchemy: referencing label()'d column in a filter or clauselement | I'm trying to perform a query that works across a many->many relation ship between bmarks and tags with a secondary table of bmarks_tags. The query involves several subqueries and I have a need to DISTINCT a column. I later want to join that to another table via the DISTINCT'd ids.
I've tried it a few ways and this se... | [
"Something like this should work:\nt = DBSession.query(Tag.tid.distinct().label('tid')).subquery('t')\ntest = select([bmarks_tags.c.bmark_id], bmarks_tags.c.tag_id == t.c.tid)\nreturn DBSession.execute(test)\n\n",
"It is hard to tell what you are trying to accomplish, but since you are using orm anyways (and ther... | [
4,
0
] | [] | [] | [
"join",
"python",
"sqlalchemy"
] | stackoverflow_0005916446_join_python_sqlalchemy.txt |
Q:
Looking for a self-contained equation rendering library
Is there such a thing as a small, self-contained library that will render an equation written in a text-based format (e.g. LaTeX or MathML) to an image (either vector or raster)?
It would be preferable if it's in Python or Python-friendly.
(One possibility t... | Looking for a self-contained equation rendering library | Is there such a thing as a small, self-contained library that will render an equation written in a text-based format (e.g. LaTeX or MathML) to an image (either vector or raster)?
It would be preferable if it's in Python or Python-friendly.
(One possibility that I've found: Matplotlib has Python code to parse and displ... | [
"You can try to convert MathML to SVG.\n",
"There's mimetex a stand alone program for rendering latex math... it's not a library however\nhttp://www.forkosh.com/mimetex.html\n",
"A versatile program and Python module to allow conversion of LaTeX math equations in to PNG images: http://code.google.com/p/latexmat... | [
5,
1,
0,
0,
0
] | [] | [] | [
"equation",
"latex",
"mathml",
"parsing",
"python"
] | stackoverflow_0000617668_equation_latex_mathml_parsing_python.txt |
Q:
Python path help
how can i run my program using test files on my desktop without typing in the specific pathname. I just want to be able to type the file name and continue on with my program. Since i want to be able to send it to a friend and not needing for him to change the path rather just read the exact same f... | Python path help | how can i run my program using test files on my desktop without typing in the specific pathname. I just want to be able to type the file name and continue on with my program. Since i want to be able to send it to a friend and not needing for him to change the path rather just read the exact same file that he has on his... | [
"If you are on Unix/Mac you can add a shebang at the top of your script and set it as executable. Usually you'd do:\n#!/usr/bin/env python\n\nAnd then to make it executable, from a terminal use chmod:\nchmod +x script.py\n\nNow you can run the script (if you are in the same directory) like:\n./script.py\n\nIf you a... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005953657_python.txt |
Q:
Programatically transferring mysql data between separate servers
Looks like there are several options:
mysqldump + rsync - can this be done for only specific data from an existing table, and not a whole table?
An insert to a federated table - this seems pretty untested and unknown at this point...
A Python script... | Programatically transferring mysql data between separate servers | Looks like there are several options:
mysqldump + rsync - can this be done for only specific data from an existing table, and not a whole table?
An insert to a federated table - this seems pretty untested and unknown at this point...
A Python script (pull into memory from A, then insert into B) - this would probably b... | [
"You also have another option -- mysql replication!\nCan you not extract that single table into its own database and replicate just that to the second server (or as many servers as you like)?\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0005953992_mysql_python.txt |
Q:
Crawler in python
I have a website (my college website) for which each student has a username/password to login into his account. The website consists of many files uploaded in different formats. I want to programmatically enter my credentials and login to my account and download all files that have been uploaded ... | Crawler in python | I have a website (my college website) for which each student has a username/password to login into his account. The website consists of many files uploaded in different formats. I want to programmatically enter my credentials and login to my account and download all files that have been uploaded in the site.
Is there a... | [
"I would look at http://scrapy.org. It's python based crawler/scraper that you can customize to perform any workflow you want. Here's an example of how user authentication is handled: http://doc.scrapy.org/topics/request-response.html?highlight=username#request-usage-examples\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005953911_python.txt |
Q:
Feeding a List of Lists into a function
I have a multi-dimensional array that I am trying to feed into difflib.get_close_matches().
My array looks like this: array[(ORIGINAL, FILTERED)]. ORIGINAL is a string, and FILTERED is the ORIGINAL string with common words filtered out.
I currently have a new array being cre... | Feeding a List of Lists into a function | I have a multi-dimensional array that I am trying to feed into difflib.get_close_matches().
My array looks like this: array[(ORIGINAL, FILTERED)]. ORIGINAL is a string, and FILTERED is the ORIGINAL string with common words filtered out.
I currently have a new array being created with only the FILTERED words being fed i... | [
"Since you're already using SequenceMatcher directly to get the match ratio, your most straightforward change would probably be to do the get_close_matches operation yourself.\nCompare the source for get_close_matches() [e.g., http://svn.python.org/view/python/tags/r271/Lib/difflib.py?revision=86833&view=markup nea... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005885263_python.txt |
Q:
Python 3.2 File I/O. Generating & Spliting a file based on preset size limit. How?
I'm working on some code that generates all permutations of a given set of characters. Although my code works in Python 2.7 it no longer does in Python 3.x due to many changes in Strings. I'd like to adapt and since I'm new to Pytho... | Python 3.2 File I/O. Generating & Spliting a file based on preset size limit. How? | I'm working on some code that generates all permutations of a given set of characters. Although my code works in Python 2.7 it no longer does in Python 3.x due to many changes in Strings. I'd like to adapt and since I'm new to Python, I was hoping you could give me a little push. =)
My question is, as Python generates ... | [
"I think the best solution would be to write a class that acts like a file, but provides the chunking capability. Your program just writes to this object as though it were a regular file.\nThe implementation below won't split strings (if you call f.write(\"this is a test\") the entire message is guaranteed to go in... | [
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0005953269_python_python_3.x.txt |
Q:
What's in your python mode hook?
I'm starting to look at python, trying to bootstrap myself here.
What's in your python mode hook?
I have some experience with emacs, but I'm not familiar with python.
what's the preferred python mode? I have emacs 23.2 on Windows.
Is there a flymake-for-python? (how do I set... | What's in your python mode hook? | I'm starting to look at python, trying to bootstrap myself here.
What's in your python mode hook?
I have some experience with emacs, but I'm not familiar with python.
what's the preferred python mode? I have emacs 23.2 on Windows.
Is there a flymake-for-python? (how do I set it up?)
does autopair work with pytho... | [
"Re: autopair. Yes, it works. I have autopair.el version 0.3. The docs at the top of autopair.el have an extension that makes triple quotes work. \nMy setup:\n(require 'autopair)\n(autopair-global-mode) ;; enable autopair in all buffers \n(setq autopair-autowrap t) ;; attempt to wrap selection\n\n;; this mode-hook ... | [
2
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0005936928_emacs_python.txt |
Q:
Default substituting %s in python scripts
Sometimes in Python scripts I see lines like:
cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\""
Where is the %s in the above line substituted? Does Python have some stack of strings and it pops them and replaces %s?
A:
Basics of python string formatting
Not a specific... | Default substituting %s in python scripts | Sometimes in Python scripts I see lines like:
cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\""
Where is the %s in the above line substituted? Does Python have some stack of strings and it pops them and replaces %s?
| [
"Basics of python string formatting\nNot a specific answer to your line of code, but since you said you're new to python I thought I'd use this as an example to share some joy ;)\nSimple Example Inline With a List: \n>>> print '%s %s %s'%('python','is','fun')\npython is fun\n\nSimple Example Using a Dictionary:\n>... | [
22,
21,
20
] | [] | [] | [
"python",
"string",
"substitution"
] | stackoverflow_0005954260_python_string_substitution.txt |
Q:
Calling inet_pton through Cython
I want to call inet_pton in Cython for IPv6 addresses. Basically I want to do the equivalent of the following C code:
char str[16];
inet_pton(AF_INET6, "12:212::122", &str);
I tried the following:
cdef char buff[16]
inet_pton(AF_INET6, address, &buff):
But this gives an error: "T... | Calling inet_pton through Cython | I want to call inet_pton in Cython for IPv6 addresses. Basically I want to do the equivalent of the following C code:
char str[16];
inet_pton(AF_INET6, "12:212::122", &str);
I tried the following:
cdef char buff[16]
inet_pton(AF_INET6, address, &buff):
But this gives an error: "Taking address of non-lvalue".
What is ... | [
"Use buff or &buff[0] instead of &buff.\n"
] | [
3
] | [] | [] | [
"cython",
"ipv6",
"posix",
"python"
] | stackoverflow_0005887493_cython_ipv6_posix_python.txt |
Q:
In Python difference in __dict__ between object() and class myClass(object)
I was messing around with dynamic attributes and I noticed I could not use the __dict__ attribute if I created the object directly from the object() class but if I create a new class that is a direct descendent of object I can access the _... | In Python difference in __dict__ between object() and class myClass(object) | I was messing around with dynamic attributes and I noticed I could not use the __dict__ attribute if I created the object directly from the object() class but if I create a new class that is a direct descendent of object I can access the __dict__ attribute. Why the difference?
Examples:
# This gives an AttributeError ... | [
"object is implemented in C and doesn't have a __dict__ attribute. (Not all Python objects have it either; look up __slots__).\n",
"I'm not entirely sure why it works for your class but not the original object class. I'd assume that when your class get initialized, it creates __dict__.\nUsing this code:\nclass Te... | [
10,
2
] | [] | [] | [
"python"
] | stackoverflow_0005954717_python.txt |
Q:
python functions returning certain number of characters?
I have to create a function that when a string is inputted, the function checks to see if there are 160 character. If there are less than or equal to 160, then print the message. If not, it has to only print the first 160. This is what i have so far:
def me... | python functions returning certain number of characters? | I have to create a function that when a string is inputted, the function checks to see if there are 160 character. If there are less than or equal to 160, then print the message. If not, it has to only print the first 160. This is what i have so far:
def message():
message1=raw_input('input a message')
if ((... | [
"A string is just a list of characters... so you can do something like this:\ndef message():\n message1=raw_input('input a message')\n return message1[:160]\n\n",
"You can use python's slicing syntax for that:\n def message():\n message1=raw_input('input a message')\n return message1[:160]\n\nthat... | [
3,
2,
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0005954894_function_python.txt |
Q:
How to represent dbus type b(oss) in python?
I'm working on a Mpris V2.1 interface with python.
The interfaces are described in the document:
http://www.mpris.org/2.1/spec/Playlists.html#Property:ActivePlaylist
The signature shows it's complex type contains boolean, object and strings. I just wonder how to repre... | How to represent dbus type b(oss) in python? | I'm working on a Mpris V2.1 interface with python.
The interfaces are described in the document:
http://www.mpris.org/2.1/spec/Playlists.html#Property:ActivePlaylist
The signature shows it's complex type contains boolean, object and strings. I just wonder how to represent the type in python. Do I have a provider a li... | [
"According to D-Bus specification, (b(oss)) is a struct of two elements, first is a boolean, second is a struct of three elements: an object path and two strings. In python this maps to something like:\ndbus.Struct((dbus.Boolean(a_boolean),\n dbus.Struct((dbus.ObjectPath(s1),\n ... | [
4
] | [] | [] | [
"dbus",
"python"
] | stackoverflow_0005909816_dbus_python.txt |
Q:
Can someone please edit this i keep getting a syntax error on line 13
class Tux(gtk.Window):
def __init__(self):
super(Tux, self).__init__()
combobox = gtk.combo_box_new_text()
combobox.connect("changed", self.on_changed)
for choice in choices:
combobox.append_text(c... | Can someone please edit this i keep getting a syntax error on line 13 | class Tux(gtk.Window):
def __init__(self):
super(Tux, self).__init__()
combobox = gtk.combo_box_new_text()
combobox.connect("changed", self.on_changed)
for choice in choices:
combobox.append_text(choice)
self.add(combobox)
self.label = gtk.Label("No select... | [
"img.set_from_file(“Tux image.png”)\n\nPython, like most programming languages, does not support fancy quotes (likely inserted by a word processor). Instead, use \" or '.\n",
"On line:\nimg.set_from_file(“Tux image.png”)\n\nYou should use (\") or (') sign, not (”). \n",
"class Tux(gtk.Window):\n def __init__... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005955197_python.txt |
Q:
How do I mark an item as read with google reader api (using python)
I use the following python function to mark an item as read in google reader, but it always returns error HTTPErrors: HTTP 401: Unauthorized:
def mark_as_read(SID, entryid):
token = get_token(SID)
mark_as_read_url = 'http://www.google.... | How do I mark an item as read with google reader api (using python) | I use the following python function to mark an item as read in google reader, but it always returns error HTTPErrors: HTTP 401: Unauthorized:
def mark_as_read(SID, entryid):
token = get_token(SID)
mark_as_read_url = 'http://www.google.com/reader/api/0/edit-tag'
header = {'Content-type': 'application/x... | [
"It seems you are missing the authentication header:\nheader = {\n 'Content-type': 'application/x-www-form-urlencoded',\n 'Authorization': 'GoogleLogin auth=YOUR_AUTH_TOKEN'\n}\n\n",
"When i compare this to the request I'm making in Firefox (inspected with liveheaders), it looks ok. I only have the extra pa... | [
2,
0
] | [] | [] | [
"google_reader",
"python"
] | stackoverflow_0001695556_google_reader_python.txt |
Q:
Python error: list indices must be integers, not unicode
there is my problem:
i'm trying to get all numbers from a Tkinter's text widget(get's the text from a file) this way:
text = self.text_field.get(1.0, 'end')
s = re.findall("\d+", text)
s returns something like this:
[u'0', u'15', u'320', u'235', u'1', u... | Python error: list indices must be integers, not unicode | there is my problem:
i'm trying to get all numbers from a Tkinter's text widget(get's the text from a file) this way:
text = self.text_field.get(1.0, 'end')
s = re.findall("\d+", text)
s returns something like this:
[u'0', u'15', u'320', u'235', u'1', u'1', u'150', u'50', u'2', u'2', u'20']
than i try to add tags... | [
"In Python when you do\nfor x in L:\n ...\n\ninside the body loop x is already the list element, not the index.\nIn your case the correction needed is simply to use % i instead of % s[i].\nIf in other cases you need both the list element and the index number the common Python idiom is:\nfor index, element in enu... | [
13,
2
] | [] | [] | [
"file_io",
"python",
"tkinter"
] | stackoverflow_0005955516_file_io_python_tkinter.txt |
Q:
Need Assistance in Python Thread programming
I'm developing a UI which has a Run button to run a certain tests on command prompt.I tried implementing threads here for invoking the command prompt and thought of monitoring the thread. Till the tests are run (on command prompt), I want the run button to be disabled a... | Need Assistance in Python Thread programming | I'm developing a UI which has a Run button to run a certain tests on command prompt.I tried implementing threads here for invoking the command prompt and thought of monitoring the thread. Till the tests are run (on command prompt), I want the run button to be disabled and want to enable it only when the command prompt ... | [
"The problem is how you're monitoring the thread. runscript blocks the program by executing in a loop as long as the thread is alive, thus blocking the GUI event system from processing user events - this creates the appearance of \"hanging\" you're experiencing.\nThere are many techniques for interacting with threa... | [
2,
2
] | [] | [] | [
"multithreading",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0005948971_multithreading_pyqt_pyqt4_python.txt |
Q:
Please suggest how to write a text from webpage text box to clipboard
I have a text box in the webpage, a text in that text box i need that to be sent to the clipboard of ubuntu how do i do that? I'm using python CGI, Please suggest me a link or Idea to proceed.
Thank you :)
A:
Python and cgi run on the server, ... | Please suggest how to write a text from webpage text box to clipboard | I have a text box in the webpage, a text in that text box i need that to be sent to the clipboard of ubuntu how do i do that? I'm using python CGI, Please suggest me a link or Idea to proceed.
Thank you :)
| [
"Python and cgi run on the server, but you want to copy text from the webpage that a client is viewing to the client's clipboard.\nHence you have to do your solution client-side with javascript or a javascript library like jQuery. This used to be do-able using jQuery clipboard, though this was a security problem a... | [
1
] | [] | [] | [
"cgi",
"clipboard",
"python"
] | stackoverflow_0005955525_cgi_clipboard_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.