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: Optimize PDF conversion in Django / Python I have a webapp that export reports in PDF. Everything is fine when the query returns less than 100 values. When the number of records raise above 100 the server raise a 502 Proxy Error. The report outputs fine in HTML. The process that hangs up the server is the conversi...
Optimize PDF conversion in Django / Python
I have a webapp that export reports in PDF. Everything is fine when the query returns less than 100 values. When the number of records raise above 100 the server raise a 502 Proxy Error. The report outputs fine in HTML. The process that hangs up the server is the conversion from html to PDF. I'm using xhtml2pdf (AKA pi...
[ "I can't tell you exactly what causes your problem - it could be caused by buffering problems in StringIO. \nHowever, you are wrong if you assume that this code would actually stream the generated PDF data: StringIO.getvalue() returns the content of the string buffer at the time this method is called, not an output...
[ 3 ]
[]
[]
[ "django", "pdf", "pisa", "python" ]
stackoverflow_0003397965_django_pdf_pisa_python.txt
Q: How should I write very long lines of code? if i have a very long line of a code, is it possible to continue it on the next line for example: url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,67676...
How should I write very long lines of code?
if i have a very long line of a code, is it possible to continue it on the next line for example: url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&ch...
[ "I would write it like this\nurl=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'\n '100,000|1,000,000&chxp=1,0&chxr=0,0,%(max_freq)s300|1,0,3&chxs=0,676767'\n ',13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465'\n '&cht=bvs&chco=A2C180&chds=0,300&chd=t:'%{'max...
[ 21, 17, 2, 1 ]
[]
[]
[ "pep8", "python" ]
stackoverflow_0003401468_pep8_python.txt
Q: wrapping boost::ublas with swig I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexi...
wrapping boost::ublas with swig
I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #i...
[ "You may be interested in looking at the pyublas module. It does the conversion between numpy arrays and ublas data types seamlessly and without copying. \n", "You may want to replace \ncopy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); \nby \ncopy(ptr, ptr+size, &(dv::data()[0])); \nRemember that in C/C++...
[ 3, 1 ]
[]
[]
[ "boost", "c++", "python", "swig" ]
stackoverflow_0002755352_boost_c++_python_swig.txt
Q: Decorating a method In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event):...
Decorating a method
In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event): ... I have first tr...
[ "The decorator approach isn't working because the decorator is being called when the class is constructed, not when the instance is constructed. When you say\nclass Foo(object):\n @some_decorator\n def bar(self, *args, **kwargs):\n # etc etc\n\nthen some_decorator will be called when the class Foo is construct...
[ 4, 3 ]
[]
[]
[ "decorator", "methods", "python" ]
stackoverflow_0003401421_decorator_methods_python.txt
Q: python c extension for standard deviation I'm writing a c extension to calculate he standard deviation. Performance is important because it will be performed over large data sets. I'm having a hard time figuring out how to get the value of pyobject once I get the item from a list. This is my first time writing ...
python c extension for standard deviation
I'm writing a c extension to calculate he standard deviation. Performance is important because it will be performed over large data sets. I'm having a hard time figuring out how to get the value of pyobject once I get the item from a list. This is my first time writing a c extension for python and any help is apprec...
[ "You may be reinventing the wheel. There are several scientific computing libraries for Python, such as SciPy and Numpy, which are mostly wrappers around C libraries, that implement functions such as standard deviation.\n", "Once you have item, you can get its float value with PyNumber_Float:\nPyObject* floatite...
[ 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "c", "performance", "python", "standard_deviation" ]
stackoverflow_0003401521_c_performance_python_standard_deviation.txt
Q: need help with splitting a string in python I am trying to tokenize a string using the pattern as below. >>> splitter = re.compile(r'((\w*)(\d*)\-\s?(\w*)(\d*)|(?x)\$?\d+(\.\d+)?(\,\d+)?|([A-Z]\.)+|(Mr)\.|(Sen)\.|(Miss)\.|.$|\w+|[^\w\s])') >>> splitter.split("Hello! Hi, I am debating this predicament called life. ...
need help with splitting a string in python
I am trying to tokenize a string using the pattern as below. >>> splitter = re.compile(r'((\w*)(\d*)\-\s?(\w*)(\d*)|(?x)\$?\d+(\.\d+)?(\,\d+)?|([A-Z]\.)+|(Mr)\.|(Sen)\.|(Miss)\.|.$|\w+|[^\w\s])') >>> splitter.split("Hello! Hi, I am debating this predicament called life. Can you help me?") I get the following output. C...
[ "re.split rapidly runs out of puff when used as a tokeniser. Preferable is findall (or match in a loop) with a pattern of alternatives this|that|another|more\n>>> s = \"Hello! Hi, I am debating this predicament called life. Can you help me?\"\n>>> import re\n>>> re.findall(r\"\\w+|\\S\", s)\n['Hello', '!', 'Hi', ',...
[ 4, 4, 2, 1, 0 ]
[]
[]
[ "python", "regex", "string_split" ]
stackoverflow_0003392947_python_regex_string_split.txt
Q: having to run multiple instances of a web service for ruby/python seems like a hack to me Is it just me or is having to run multiple instances of a web server to scale a hack? Am I wrong in this? Clarification I am referring to how I read people run multiple instances of a web service on a single server. I am not...
having to run multiple instances of a web service for ruby/python seems like a hack to me
Is it just me or is having to run multiple instances of a web server to scale a hack? Am I wrong in this? Clarification I am referring to how I read people run multiple instances of a web service on a single server. I am not talking about a cluster of servers.
[ "Not really, people were running multiple frontends across a cluster of servers before multicore cpus became widespread\nSo there has been all the infrastructure for supporting sessions properly across multiple frontends for quite some time before it became really advantageous to run a bunch of threads on one machi...
[ 4, 4, 1, 1, 1, 0 ]
[]
[]
[ "python", "ruby_on_rails" ]
stackoverflow_0003399367_python_ruby_on_rails.txt
Q: best way to download large files with python Which library/module is the best to use for downloading large 500mb+ files in terms of speed, memory, cpu? I was also contemplating using pycurl. A: At sizes of 500MB+ one has to worry about data integrity, and HTTP is not designed with data integrity in mind. I'd rat...
best way to download large files with python
Which library/module is the best to use for downloading large 500mb+ files in terms of speed, memory, cpu? I was also contemplating using pycurl.
[ "At sizes of 500MB+ one has to worry about data integrity, and HTTP is not designed with data integrity in mind.\nI'd rather use python bindings for rsync (if they exist) or even bittorrent, which was initially implemented in python. Both rsync and bittorrent address the data integrity issue.\n" ]
[ 0 ]
[]
[]
[ "curl", "python", "urllib2" ]
stackoverflow_0003402271_curl_python_urllib2.txt
Q: python dict remove duplicate values by key's value? A dict dic = { 1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'} I want to remove duplicate values just keep one K/V pair, Regarding the "key" selection of those duplicated values, it may be max or min or by random select o...
python dict remove duplicate values by key's value?
A dict dic = { 1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'} I want to remove duplicate values just keep one K/V pair, Regarding the "key" selection of those duplicated values, it may be max or min or by random select one of those duplicated item's key. I do not want to use a...
[ "You could build a reverse dictionary where the values are lists of all the keys from your initial dictionary. Using this you could then do what you want, min, max, random, alternate min and max, or whatever.\nfrom collections import defaultdict\n\nd = defaultdict(list)\nfor k,v in dic.iteritems():\n d[v].appen...
[ 5, 2, 1 ]
[]
[]
[ "dictionary", "duplicates", "python" ]
stackoverflow_0003402346_dictionary_duplicates_python.txt
Q: How to reverse django feed url? I've been searching for hours to try and figure this out, and it seems like no one has ever put an example online - I've just created a Django 1.2 rss feed view object and attached it to a url. When I visit the url, everything works great, so I know my implementation of the feed cla...
How to reverse django feed url?
I've been searching for hours to try and figure this out, and it seems like no one has ever put an example online - I've just created a Django 1.2 rss feed view object and attached it to a url. When I visit the url, everything works great, so I know my implementation of the feed class is OK. The hitch is, I can't figur...
[ "You can name your url pattern, which requires the use of the url helper function:\nfrom django.conf.urls.defaults import url, patterns\n\nurlpatterns = patterns('app.blog.views',\n url(r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts(), name='latest-posts'),\n #snip...\n)\n\nThen, you can simply use {% url...
[ 6 ]
[]
[]
[ "django", "django_syndication", "python", "rss" ]
stackoverflow_0003402362_django_django_syndication_python_rss.txt
Q: Fibonacci sequence Possible Duplicate: How to write the Fibonacci Sequence in Python Hi. I'm also a learning programmer and I've been asked the same question you were asked for Fibonacci numbers and I can't figure it out. Can you please show me the code you used to generate these numbers asking the user to give ...
Fibonacci sequence
Possible Duplicate: How to write the Fibonacci Sequence in Python Hi. I'm also a learning programmer and I've been asked the same question you were asked for Fibonacci numbers and I can't figure it out. Can you please show me the code you used to generate these numbers asking the user to give numbers and find only t...
[ "I'm not going to give you the code - you should be able to write it yourself. Here are some things you may need to know when writing it however (Not using recursion):\n\nCreate 3 variables equal to -1 (n1), 1 (n2), and n1 + n2 sumn.\nCreate a loop using for i in range(amount_of_numbers), where amount_of_numbers i...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003402584_python.txt
Q: How can I select and delete all (ctrl + shift + left arrow + del) with shell.SendKeys? Hey, I'm having some trouble here... How can I delete an entire text from a field with the sendkeys ? How can I send the ctrl+shift pressed with the left arrow and delete key after? edit: for example, I have this part of the cod...
How can I select and delete all (ctrl + shift + left arrow + del) with shell.SendKeys?
Hey, I'm having some trouble here... How can I delete an entire text from a field with the sendkeys ? How can I send the ctrl+shift pressed with the left arrow and delete key after? edit: for example, I have this part of the code ctypes.windll.user32.SetCursorPos(910,475) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTD...
[ "I don't know with Sendkeys but I know that you can send keystrokes with ctypes.\nHere is how to remove a text by sending CTRL+A and BACK:\nctypes.windll.user32.keybd_event(0x11, 0, 0, 0) #CTRL is down\nctypes.windll.user32.keybd_event(ord(\"A\"), 0, 0, 0) #A is down\nctypes.windll.user32.keybd_event(ord(\"A\"), 0,...
[ 4, 3 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0003401149_python_sendkeys.txt
Q: Multi choice form field in Django I'am developing application on app-engine-path. I would like to make form with multichoice (acceptably languages for user). Code look like this: Language settings: settings.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English")) Form model: class UserForm(forms.ModelForm): ...
Multi choice form field in Django
I'am developing application on app-engine-path. I would like to make form with multichoice (acceptably languages for user). Code look like this: Language settings: settings.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English")) Form model: class UserForm(forms.ModelForm): first_name = forms.CharField(max_lengt...
[ "I solved it this way:\nsome_view(request):\n ...\n form = UserForm(instance=user, initial={\"languages\":user.languages}) \n ...\n\n" ]
[ 0 ]
[]
[]
[ "app_engine_patch", "django_forms", "python" ]
stackoverflow_0002522332_app_engine_patch_django_forms_python.txt
Q: Find max length word from arbitrary letters I have 10 arbitrary letters and need to check the max length match from words file I started to learn RE just some time ago, and can't seem to find suitable pattern first idea that came was using set: [10 chars] but it also repeats included chars and I don't know how t...
Find max length word from arbitrary letters
I have 10 arbitrary letters and need to check the max length match from words file I started to learn RE just some time ago, and can't seem to find suitable pattern first idea that came was using set: [10 chars] but it also repeats included chars and I don't know how to avoid that I stared to learn Python recently b...
[ "I'm guessing this is something like finding possible words given a set of Scrabble tiles, so that a character can be repeated only as many times as it is repeated in the original list.\nThe trick is to efficiently test each character of each word in your word file against a set containing your source letters. For...
[ 2, 0, 0 ]
[]
[]
[ "iterator", "puzzle", "python" ]
stackoverflow_0003402574_iterator_puzzle_python.txt
Q: Creating Instances of IronPython Classes From C# I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed. This is my current code: ConstructorInfo[] ci = type.GetConstructors(); foreach (ConstructorInfo t in from t in ci where t.Ge...
Creating Instances of IronPython Classes From C#
I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed. This is my current code: ConstructorInfo[] ci = type.GetConstructors(); foreach (ConstructorInfo t in from t in ci where t.GetParameters().Length == 1 ...
[ "This code works with IronPython 2.6.1\n static void Main(string[] args)\n {\n const string script = @\"\nclass A(object) :\n def __init__(self) :\n self.a = 100\n\nclass B(object) : \n def __init__(self, a, v) : \n self.a = a\n self.v = v\n def run(self) :\n return...
[ 10, 2, 0 ]
[]
[]
[ ".net", "c#", "dynamic_language_runtime", "ironpython", "python" ]
stackoverflow_0003402713_.net_c#_dynamic_language_runtime_ironpython_python.txt
Q: Comparing strings using '==' and 'is' Possible Duplicates: Types for which “is” keyword may be equivalent to equality operator in Python Python “is” operator behaves unexpectedly with integers Hi. I have a question which perhaps might enlighten me on more than what I am asking. Consider this: >>> x = 'Hello' >>>...
Comparing strings using '==' and 'is'
Possible Duplicates: Types for which “is” keyword may be equivalent to equality operator in Python Python “is” operator behaves unexpectedly with integers Hi. I have a question which perhaps might enlighten me on more than what I am asking. Consider this: >>> x = 'Hello' >>> y = 'Hello' >>> x == y True >>> x is y Tr...
[ "This is an implementation detail and absolutely not to be relied upon. is compares identities, not values. Short strings are interned, so they map to the same memory address, but this doesn't mean you should compare them with is. Stick to ==.\n", "There are two ways to check for equality in Python: == and is. ==...
[ 12, 10, 8, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003403964_python.txt
Q: djangoproject access fields of object dynamically Can anyone help me? I have list of fields called 'allowed_fields' and I have object called 'individual'. allowed_fields is sub set of individual. Now I want to run loop like this for field in allowed_fields: obj.field = individual.field obj have same...
djangoproject access fields of object dynamically
Can anyone help me? I have list of fields called 'allowed_fields' and I have object called 'individual'. allowed_fields is sub set of individual. Now I want to run loop like this for field in allowed_fields: obj.field = individual.field obj have same fields like individual. Do you have solution of my pro...
[ "If each field is actually a string, you could try the following.\nI renamed field to fieldname to better indicate that it is a string.\nfor fieldname in allowed_fields:\n setattr(obj, fieldname, getattr(individual, fieldname))\n\n", "setattr(obj, fieldname, fieldvalue)\n(see also getattr to retrieve at runtim...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003404055_django_python.txt
Q: Updating an object in a for loop using SqlAlchemy, should this work in theory? So first I am fetching the rows: q = session.query(products) for p in q: p.someproperty = 23 session.commit() Should the above work in theory? Or is that the wrong pattern? I am getting an error saying can't modify the prope...
Updating an object in a for loop using SqlAlchemy, should this work in theory?
So first I am fetching the rows: q = session.query(products) for p in q: p.someproperty = 23 session.commit() Should the above work in theory? Or is that the wrong pattern? I am getting an error saying can't modify the property, which is strange so I figured I was doing something fundamentally wrong.
[ "2 things:\nNumber one, you shouldn't have to commit() after every change. You should be able to:\nfor p in session.query (query):\n p.someproperty = somevalue\nsession.commit()\n\nand number two, see this thread here: Efficiently updating database using SQLAlchemy ORM. This gives another example of the syntax...
[ 3, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003393102_python_sqlalchemy.txt
Q: urllib.urlopen to open page on same port just hangs I am trying to use urllib.urlopen to open a web page running on the same host and port as the page I am loading it from and it is just hanging. For example I have a page at: "http://mydevserver.com:8001/readpage.html" and I have the following code in it: data = u...
urllib.urlopen to open page on same port just hangs
I am trying to use urllib.urlopen to open a web page running on the same host and port as the page I am loading it from and it is just hanging. For example I have a page at: "http://mydevserver.com:8001/readpage.html" and I have the following code in it: data = urllib.urlopen("http://mydevserver.com:8001/testpage.html"...
[ "A firewall perhaps? Try opening the page from the command line with wget/curl (assuming you're on Linux) or on the browser, with both ports on settings. Furthermore, you could try a packet sniffer to find out what's going on and where the connection gets stuck. Also, if testpage.html is dynamically generated, see ...
[ 0, 0, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0003404003_python_urllib.txt
Q: How to tell if item in list contains certain characters I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, ...
How to tell if item in list contains certain characters
I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, and as a result i cant tell them apart from numbers with anyt...
[ "You're performing an integer division, so your results will all be integers anyway.\nEven if you'd divide by float(z) instead, you'd run the risk of getting rounding errors, so checking for .0 wouldn't be a good idea anyway.\nMaybe what you want is\nif 600851475143 % z == 0:\n mylist.append(600851475143/z)\n\nI...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003404382_python.txt
Q: Hyperlink in Tkinter Text widget? I am re designing a portion of my current software project, and want to use hyperlinks instead of Buttons. I really didn't want to use a Text widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error: TclError...
Hyperlink in Tkinter Text widget?
I am re designing a portion of my current software project, and want to use hyperlinks instead of Buttons. I really didn't want to use a Text widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error: TclError: bitmap "blue" not defined When I add...
[ "If you don't want to use a text widget, you don't need to. An alternative is to use a label and bind mouse clicks to it. Even though it's a label it still responds to events.\nFor example:\nimport tkinter as tk\n\nclass App:\n def __init__(self, root):\n self.root = root\n for text in (\"link1\", ...
[ 13, 1 ]
[]
[]
[ "hyperlink", "python", "tkinter", "windows" ]
stackoverflow_0003402110_hyperlink_python_tkinter_windows.txt
Q: Finding the user who uses my django web application I have developed a small django web application. It still runs in the django development web server. It has been decided that if more than 'n' number of users like the application, it will be approved. I want to find out all the users who view my application. How...
Finding the user who uses my django web application
I have developed a small django web application. It still runs in the django development web server. It has been decided that if more than 'n' number of users like the application, it will be approved. I want to find out all the users who view my application. How can find the user who views my application? Since I was ...
[ "You can look in the admin to see how many usernames are there, assuming everyone who likes it creates one. Or you can look at your server logs and count the unique IPs.\n", "You can keep track of your visitors by adding a call to google analytics in your web pages. Or, if you do not wish to use a Google product,...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003404759_django_python.txt
Q: Changing the encoding of a table with django+south migrations Django and south newbie here I need to change the encoding of a table I created, does anyone know a way to do so using a migration? A: I think the solution will be database-specific. For example, for a MySQL database: from south.db import db from sout...
Changing the encoding of a table with django+south migrations
Django and south newbie here I need to change the encoding of a table I created, does anyone know a way to do so using a migration?
[ "I think the solution will be database-specific. For example, for a MySQL database:\nfrom south.db import db\nfrom south.v2 import SchemaMigration\n\nclass Migration(SchemaMigration):\n def forwards(self, orm):\n db.execute('alter table appname_modelname charset=utf8')\n db.execute('alter table app...
[ 8 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0003404737_django_django_south_python.txt
Q: Generating dictionary keys on the fly Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: mydict[key][subkey][subkey2]="value" without having to check that mydict[key] etc. are actually set to be a dict, e.g. using if not key in mydict: mydict[...
Generating dictionary keys on the fly
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: mydict[key][subkey][subkey2]="value" without having to check that mydict[key] etc. are actually set to be a dict, e.g. using if not key in mydict: mydict[key]={} The creation of subdictionaries sh...
[ "class D(dict):\n def __missing__(self, key):\n self[key] = D()\n return self[key]\n\nd = D()\nd['a']['b']['c'] = 3\n\n", "You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all:\nmydict[(key,subkey,subkey2)] = \"value\"\n\nAlternatively, if yo...
[ 28, 14, 3 ]
[]
[]
[ "decorator", "dictionary", "python" ]
stackoverflow_0003405073_decorator_dictionary_python.txt
Q: Execute raw SQL after connect to database How can I execute raw SQL after connect to database? I need to run script once, after connect to DB. Thanks. UPD: question is not how to run raw SQL. A: Just visit the docs here. It was I think the second match on google with "Django ORM". EDIT See comments If you look ...
Execute raw SQL after connect to database
How can I execute raw SQL after connect to database? I need to run script once, after connect to DB. Thanks. UPD: question is not how to run raw SQL.
[ "Just visit the docs here.\nIt was I think the second match on google with \"Django ORM\".\nEDIT See comments\nIf you look at this Django page you see that MySQLdb (the underlying layer) also accepts an init_command option which is run immediately after a connection is established. That's a feature of MySQLdb, and ...
[ 1, 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0003405166_database_django_python.txt
Q: How can I run gtk.main() asynchronsly in pygtk? The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously? import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to di...
How can I run gtk.main() asynchronsly in pygtk?
The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously? import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVE...
[ "Just put the gtk.main call after everything else.\nIf you need to have the controller in a separate thread, make sure you do all gtk related function/methods by doing gobject.idle_add(widget.method).\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\n\nclass Display(object):\n\n def __init__(self):\n sel...
[ 0, 0 ]
[]
[]
[ "multithreading", "pygtk", "python" ]
stackoverflow_0001391680_multithreading_pygtk_python.txt
Q: Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work I don't understand why this simple code # file: mp.py from multiprocessing import Process import sys def func(x): print 'works ', x + 2 sys.stdout.flush() p = Process(target= func, args= (2, )) p.start() p.join...
Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work
I don't understand why this simple code # file: mp.py from multiprocessing import Process import sys def func(x): print 'works ', x + 2 sys.stdout.flush() p = Process(target= func, args= (2, )) p.start() p.join() p.terminate() print 'done' sys.stdout.flush() creates "pythonw.exe" processes continuously and i...
[ "You need to protect then entry point of the program by using if __name__ == '__main__':.\nThis is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't stop this new interpreter running the start up code it wil...
[ 32, 2, 1 ]
[]
[]
[ "multiprocessing", "process", "python", "windows" ]
stackoverflow_0003405397_multiprocessing_process_python_windows.txt
Q: need to selectively escape html entities (&) I'm scraping a html page, then using xml.dom.minidom.parseString() to create a dom object. however, the html page has a '&'. I can use cgi.escape to convert this into &amp; but it also converts all my html <> tags into &lt;&gt; which makes parseString() unhappy. how do...
need to selectively escape html entities (&)
I'm scraping a html page, then using xml.dom.minidom.parseString() to create a dom object. however, the html page has a '&'. I can use cgi.escape to convert this into &amp; but it also converts all my html <> tags into &lt;&gt; which makes parseString() unhappy. how do i go about this? i would rather not just hack it...
[ "\ni would rather not just hack it and\n straight replace the \"&\"s\n\nEr, why? That's what cgi.escape is doing - effectively just a search and replace operation for certain characters that have to be escaped.\nIf you only want to replace a single character, just replace the single character:\nyourstring.replace(...
[ 1, 1, 0, 0 ]
[]
[]
[ "escaping", "html_entities", "python" ]
stackoverflow_0003403168_escaping_html_entities_python.txt
Q: remove everything between 2 tags that span branches of an xml tree I'm trying to remove everything in an XML Document between 2 tags, using python & lxml. the problem is that the tags can be in different branches of the tree (but always at the same depth) an example document might look like this. <root> <p> H...
remove everything between 2 tags that span branches of an xml tree
I'm trying to remove everything in an XML Document between 2 tags, using python & lxml. the problem is that the tags can be in different branches of the tree (but always at the same depth) an example document might look like this. <root> <p> Hello world <start />this is a paragraph </p> <p> Goodbye world. <end...
[ "You've got a mess on your hands and should slap the person who wrote an intentional perversion of the XML nesting rule. \nYou are probably best of using something like SAX to recognize the <start/> tag and begin discarding input until you hit an <end/>. SAX has the advantage over lxml here because it allows you to...
[ 1, 1, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003401922_lxml_python_xml.txt
Q: fuse & gstreamer transcoding I'm trying to create a FUSE fs which transcodes all sound files to mp3. My first idea is to use gstreamer as the backend for transcoding. I thought about using this pipeline: gst-launch -v filesrc location=01\ New\ Born.flac ! decodebin ! audioconvert ! lame vbr=4 vbr-quality=9 ! id3v2...
fuse & gstreamer transcoding
I'm trying to create a FUSE fs which transcodes all sound files to mp3. My first idea is to use gstreamer as the backend for transcoding. I thought about using this pipeline: gst-launch -v filesrc location=01\ New\ Born.flac ! decodebin ! audioconvert ! lame vbr=4 vbr-quality=9 ! id3v2mux ! appsink The python bindings...
[ "I don't think you need to bother with appsink. My gut feeling is that the further you can separate the transcoding part from the filesystem part the better. Transcode in a separate thread or process into a filesink and pass messages to tell the FUSE daemon how far transcoding has progressed.\nInstead of appsink, I...
[ 0, 0 ]
[]
[]
[ "fuse", "gstreamer", "python" ]
stackoverflow_0003387506_fuse_gstreamer_python.txt
Q: Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting? I wrote a simple script to solve a "logic puzzle", the type of puzzle from school where you are given a number of rules and then must be able to find the solution for problems like "There are five musicians named A, B, C,...
Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?
I wrote a simple script to solve a "logic puzzle", the type of puzzle from school where you are given a number of rules and then must be able to find the solution for problems like "There are five musicians named A, B, C, D, and E playing in a concert, each plays one after the other... if A goes before B, and D is not ...
[ "Use a generator expression:\nrules = [ rule1, rule2, rule3, rule4, ... ]\nrules_generator = ( r( solution ) for r in rules )\nreturn all( rules_generator )\n\nSyntactic sugar: you can omit the extra parentheses: \nrules = [ rule1, rule2, rule3, rule4, ... ]\nreturn all( r( solution ) for r in rules )\n\nA generato...
[ 13 ]
[]
[]
[ "functional_programming", "list_comprehension", "python", "short_circuiting" ]
stackoverflow_0003405794_functional_programming_list_comprehension_python_short_circuiting.txt
Q: Django - Limit users who view the items My Models: class PromoNotification(models.Model): title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) users = models.ManyToManyField(User, blank=True, null=True) groups = models.ManyToManyField(Group, blank=True, null...
Django - Limit users who view the items
My Models: class PromoNotification(models.Model): title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) users = models.ManyToManyField(User, blank=True, null=True) groups = models.ManyToManyField(Group, blank=True, null=True) I want to publish there items to temp...
[ "You might use a custom manager, which makes it easier to do this user filtering in multiple views.\nclass PromoNotificationManager(models.Manager):\n def get_for_user(self, user)\n \"\"\"Retrieve the notifications that are visible to the specified user\"\"\"\n # untested, but should be close to wh...
[ 4 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0003404843_django_django_models_django_templates_python.txt
Q: Django from Java developer perspective I'm a long time Java programmer and I'm digging into Django recently to see what it offers. It looks to me that Django doesn't fit Java web developers taste. I mean in MVC Java web frameworks we have usually a controller class that receives the request, do the logic and then ...
Django from Java developer perspective
I'm a long time Java programmer and I'm digging into Django recently to see what it offers. It looks to me that Django doesn't fit Java web developers taste. I mean in MVC Java web frameworks we have usually a controller class that receives the request, do the logic and then forwards the request to another destination....
[ "\nDjango on the other hand looks a little bit procedural, you map requests in a file, write your handlers in another, write your domain classes in another ...\n\nAs a Java developer, how is this any different than a traditional Java MVC pattern? It's just different names: Django uses \"view\" for what is tradition...
[ 4 ]
[]
[]
[ "django", "java", "python" ]
stackoverflow_0003405626_django_java_python.txt
Q: wx.TextCtrl and wx.Validator I need to validate the textboxes with wx.Textvalidator. Any please help me to do this? How can i use wx.FILTER_ALPHA with validators and if the user is giving a wrong input how can i give them a message? i need to validate all the inputs when clicking on the save button? can any one pr...
wx.TextCtrl and wx.Validator
I need to validate the textboxes with wx.Textvalidator. Any please help me to do this? How can i use wx.FILTER_ALPHA with validators and if the user is giving a wrong input how can i give them a message? i need to validate all the inputs when clicking on the save button? can any one provide me a sample code for this?
[ "This is a feature of wxWidgets, and is not implemented in wxPython.\nhttp://www.wxpython.org/docs/api/wx.TextValidator-class.html - not found\nwhile:\nhttp://docs.wxwidgets.org/trunk/classwx_text_validator.html\nhttp://docs.wxwidgets.org/stable/wx_wxtextvalidator.html\nThere is a demo of the Validators in the wxPy...
[ 5, 4, 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002198903_python_wxpython.txt
Q: List web url dir contents I wanna list a external webpage's ulr's content. like i wanna list the content of this website example.com/dir/dir/images/ currently i can download an image from a page with: urllib.urlretrieve(page_url,save_url ) But I want to list all images in a directory, or anything ells for that ma...
List web url dir contents
I wanna list a external webpage's ulr's content. like i wanna list the content of this website example.com/dir/dir/images/ currently i can download an image from a page with: urllib.urlretrieve(page_url,save_url ) But I want to list all images in a directory, or anything ells for that matter I wanna use python
[ "Unfortunately this can only work if the web server in question will serve you a directory listing when you navigate to that directory's URI.\nIf it does, typical directory listings have very simple markup, making them a prime candidate for various forms of web scraping. Otherwise, you're out of luck.\n" ]
[ 2 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0003405953_python_urllib.txt
Q: A thread pool that lets me know when at least 1 has finished? I need to use a thread pool in python, and I want to be able to know when at least 1 thead out or "maximum threads allowed" has finished, so I can start it again if I still need to do something. I has been using something like this: def doSomethingWith(...
A thread pool that lets me know when at least 1 has finished?
I need to use a thread pool in python, and I want to be able to know when at least 1 thead out or "maximum threads allowed" has finished, so I can start it again if I still need to do something. I has been using something like this: def doSomethingWith(dataforthread): dostuff() i = i-1 #thread has finished i =...
[ "As the article author mentions, and @getekha highlights, thread pools in Python don't accomplish exactly the same thing as they do in other languages. If you need parallelism, you should look into the multiprocessing module. Among other things, it has these handy Queue and Pool constructs. Also, there's an accepte...
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "threadpool" ]
stackoverflow_0003405840_multithreading_python_threadpool.txt
Q: Twisted Web Proxy I have been running this code (from: http://blog.somethingaboutcode.com/?p=155 ): from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class ...
Twisted Web Proxy
I have been running this code (from: http://blog.somethingaboutcode.com/?p=155 ): from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class InterceptingProxyClient...
[ "The KeyError exception you see when you connect directly is caused by the fact that requests to a proxy must include an absolute URL, not a relative one. If your browser doesn't know it's talking to a proxy, it will request a URL like /foo/bar. If it does know it is talking to a proxy, it will instead request so...
[ 1 ]
[]
[]
[ "python", "twisted", "twisted.web" ]
stackoverflow_0003402694_python_twisted_twisted.web.txt
Q: Pattern matching using python In the code below how match the pattern after "answer" and "nonanswer" in the dictionary opt_dict=( {'answer1':1, 'answer14':1, 'answer13':12, 'answer11':6, 'answer5':5, 'nonanswer12':1, 'nonanswer11':1, 'nonanswer4':1, 'nonanswer5':1,}) A...
Pattern matching using python
In the code below how match the pattern after "answer" and "nonanswer" in the dictionary opt_dict=( {'answer1':1, 'answer14':1, 'answer13':12, 'answer11':6, 'answer5':5, 'nonanswer12':1, 'nonanswer11':1, 'nonanswer4':1, 'nonanswer5':1,}) And if opt_dict: for ii in opt_...
[ "I didn't keep all your logging, but this should work:\nif opt_dict:\n for key, value in opt_dict.items():\n if \"nonanswer\" in key:\n print \"nonanswer\", value\n elif \"answer\" in key:\n print \"answer\", value\n else:\n raise Exception( \"invalid key\" )...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003406034_python.txt
Q: How to understand the sample from python minimock? How to understand this line? >>> smtplib.SMTP.mock_returns = Mock('smtp_connection')? What is smtp_connection? It seems I can modify it to any name. following is from minimock Here's an example ...
How to understand the sample from python minimock?
How to understand this line? >>> smtplib.SMTP.mock_returns = Mock('smtp_connection')? What is smtp_connection? It seems I can modify it to any name. following is from minimock Here's an example of something we might test, a simple email sender:: ...
[ "If you read the rest of the docs you'll see the following:\n\nMock objects have several attributes,\n all of which you can set when\n instantiating the object. To avoid\n name collision, all the attributes\n start with mock_, while the\n constructor arguments don't.\nname:\n The name of the object, used ...
[ 2 ]
[]
[]
[ "mocking", "python" ]
stackoverflow_0003406068_mocking_python.txt
Q: Iteration order of sets in Python If I have two identical sets, meaning a == b gives me True, will they have the same iteration order? I tried it, and it works: >>> foo = set("abc") >>> bar = set("abc") >>> zip(foo, bar) [('a', 'a'), ('c', 'c'), ('b', 'b')] My question is, was I lucky, or is this behavior guarant...
Iteration order of sets in Python
If I have two identical sets, meaning a == b gives me True, will they have the same iteration order? I tried it, and it works: >>> foo = set("abc") >>> bar = set("abc") >>> zip(foo, bar) [('a', 'a'), ('c', 'c'), ('b', 'b')] My question is, was I lucky, or is this behavior guaranteed?
[ "It wasn't just a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that.\nIf you create the same set in two different ways:\nn = set(\"abc\")\nprint n\n\nm = set(\"kabc\")\nm.remove(\"k\"...
[ 21, 4, 4, 1, 0 ]
[]
[]
[ "iteration", "python", "set" ]
stackoverflow_0003406341_iteration_python_set.txt
Q: How to make python window run as "Always On Top"? I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME? [Update - Solution for Windows] Lovely, I think I got it working. I am us...
How to make python window run as "Always On Top"?
I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME? [Update - Solution for Windows] Lovely, I think I got it working. I am using Python 2.5.4 with Pygame 1.9.1 in Eclipse on Vista ...
[ "The question is more like which windowing toolkit are you using ? PyGTK and similar educated googling gave me this:\n\ngtk.Window.set_keep_above\n\nAs mentioned previously it is upto the window manager to respect this setting or not.\nEdited to include SDL specific stuff\nPygame uses SDL to do display work and app...
[ 8, 0, 0 ]
[]
[]
[ "always_on_top", "gnome", "linux", "pygame", "python" ]
stackoverflow_0001482565_always_on_top_gnome_linux_pygame_python.txt
Q: How to write a server using existing version and wireshark? I decided to improve my knowledge about python network programming and here is the deal: I have a simple server for Windows, which interacts with a client from a mobile device using wi-fi. Also I have a packet sniffer (Wireshark). Now I want to ask, what ...
How to write a server using existing version and wireshark?
I decided to improve my knowledge about python network programming and here is the deal: I have a simple server for Windows, which interacts with a client from a mobile device using wi-fi. Also I have a packet sniffer (Wireshark). Now I want to ask, what do I need to write the Linux version of this server? How to deter...
[ "Start with the SocketServer module and build from there.\nNote that this will take a lot of guesswork if there is no documentation about the protocol. If you're lucky, they are using XML or HTML. If not, you will have to make the existing server send a lot of test data which you have to manipulate in some way (by ...
[ 1 ]
[]
[]
[ "networking", "python", "tcp", "wireshark" ]
stackoverflow_0003406665_networking_python_tcp_wireshark.txt
Q: Python modules for visualization of C++ code I'm looking for python modules that can help with grepping C++ code. I have a large code base that I would like to do some analysis on. Ultimately I would like to come up with a graphical map of the software. There is lots of message passing going on amongst apps so ...
Python modules for visualization of C++ code
I'm looking for python modules that can help with grepping C++ code. I have a large code base that I would like to do some analysis on. Ultimately I would like to come up with a graphical map of the software. There is lots of message passing going on amongst apps so I would like to be able to capture that informatio...
[ "Your best tool for the job is Graphviz. If you look at their gallery you'll find the sort of thing that you're interested in along with links to projects.\nUnder the language bindings section here there are a few python entries. Personally I don't use them as the dot language format is simple enough that you can b...
[ 1, 1 ]
[]
[]
[ "c++", "data_visualization", "grep", "python" ]
stackoverflow_0003405177_c++_data_visualization_grep_python.txt
Q: How to make a Django passthrough view? I want to make a Django view that does the following: Receive an HttpRequest on api/some/url/or/other Passes this through to another server at some/url/or/other (rewrite the URL, basically) Adding a cookie based on session data in Django Using the same method, data, params,...
How to make a Django passthrough view?
I want to make a Django view that does the following: Receive an HttpRequest on api/some/url/or/other Passes this through to another server at some/url/or/other (rewrite the URL, basically) Adding a cookie based on session data in Django Using the same method, data, params, et al, that were in the original request ...
[ "None.\nYou'll have to code your own wrapper utility, using one of httplib / urllib / urllib2 libs to connect to the other server.\nMost likely you will have to extract all the relevant info from the HttpRequest object and use that to manually construct your own request in said util function.\nRegarding receiving t...
[ 1 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0003406800_ajax_django_python.txt
Q: Removing things from Python list during for loop Here is my code: toBe =[] #Check if there is any get request if request.GET.items() != []: for x in DB: try: #This is removing the PMT that is spcific to the name if request.GET['pmtName'] != "None": if not reques...
Removing things from Python list during for loop
Here is my code: toBe =[] #Check if there is any get request if request.GET.items() != []: for x in DB: try: #This is removing the PMT that is spcific to the name if request.GET['pmtName'] != "None": if not request.GET['pmtName'] in x['tags']: pri...
[ "for x in DB[:]: makes a copy of the list DB, so you can iterate over it while modifying the original. Care -- memory-intensive and slow.\nA nicer way would be to make another layer over the list which yields only some of the values, and then iterate over that when you need it later. You can do that with a generato...
[ 1, 0, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003406783_list_loops_python.txt
Q: Parsing Snort Logs with PyParsing Having a problem with parsing Snort logs using the pyparsing module. The problem is with separating the Snort log (which has multiline entries, separated by a blank line) and getting pyparsing to parse each entry as a whole chunk, rather than read in line by line and expecting the...
Parsing Snort Logs with PyParsing
Having a problem with parsing Snort logs using the pyparsing module. The problem is with separating the Snort log (which has multiline entries, separated by a blank line) and getting pyparsing to parse each entry as a whole chunk, rather than read in line by line and expecting the grammar to work with each line (obviou...
[ "import pyparsing as pyp\nimport itertools\n\ninteger = pyp.Word(pyp.nums)\nip_addr = pyp.Combine(integer+'.'+integer+'.'+integer+'.'+integer)\n\ndef snort_parse(logfile):\n header = (pyp.Suppress(\"[**] [\")\n + pyp.Combine(integer + \":\" + integer + \":\" + integer)\n + pyp.Suppress(...
[ 14, 4, 0 ]
[]
[]
[ "pyparsing", "python", "snort" ]
stackoverflow_0003406544_pyparsing_python_snort.txt
Q: Paranoia, excessive logging and exception handling on simple scripts dealing with files. Is this normal? I find myself using python for a lot of file management scripts as the one below. While looking for examples on the net I am surprised about how little logging and exception handling is featured on the examples...
Paranoia, excessive logging and exception handling on simple scripts dealing with files. Is this normal?
I find myself using python for a lot of file management scripts as the one below. While looking for examples on the net I am surprised about how little logging and exception handling is featured on the examples. Every time I write a new script my intention is not to end up as the one below but if it deals with files th...
[ "Learning to let go (or how I learned to live with the bomb)...\nAsk yourself this: what exactly are you afraid of, and how will you handle it if it happens? In the example that you provide you want to avoid data-loss. The way that you've handled it is by looking for every combination of conditions that you think i...
[ 8, 3, 2, 1, 0 ]
[]
[]
[ "exception", "logging", "python" ]
stackoverflow_0003406627_exception_logging_python.txt
Q: Android app uploading data to a python server via post I have successfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send...
Android app uploading data to a python server via post
I have successfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send posts from my android app to the server. I'd also like to ...
[ "I know it's been a long time. But I did solve this so I'll post the solution. \nAndroid code:\n url = new URL(SERVER_URL);\n URLConnection connection = url.openConnection();\n connection.setDoOutput(true);\n\n OutputStreamWriter out = new OutputStreamWriter(\n ...
[ 4 ]
[]
[]
[ "google_app_engine", "http", "java", "post", "python" ]
stackoverflow_0002331862_google_app_engine_http_java_post_python.txt
Q: SPSS Python Error Getting the following error when trying to run SPSS from an external Python IDE. import spss yields the following error Traceback (most recent call last): File "C:\Documents and Settings\USER\workspace\SPSS\src\NE ASQ 2010.py", line 6, in <module> import spss File "C:\Python26\Lib\site-p...
SPSS Python Error
Getting the following error when trying to run SPSS from an external Python IDE. import spss yields the following error Traceback (most recent call last): File "C:\Documents and Settings\USER\workspace\SPSS\src\NE ASQ 2010.py", line 6, in <module> import spss File "C:\Python26\Lib\site-packages\spss180\spss\sp...
[ "I believe I figured out the issue. I needed to configure Eclipse to see the external python modules that are created when you install the SPSS/Python plugin. I had to set a reference to the modules when configuring the project. \nOnce I did that, it looks like I am up and running!\n" ]
[ 1 ]
[]
[]
[ "python", "spss" ]
stackoverflow_0003259753_python_spss.txt
Q: python: what happens to opened file if i quit before it is closed? i am opening a csv file: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) header=data[0] counter=collections.defaultdict(int) for row in data: counte...
python: what happens to opened file if i quit before it is closed?
i am opening a csv file: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) header=data[0] counter=collections.defaultdict(int) for row in data: counter[row[10]]+=1 return (data,counter,header) does the file stay in memo...
[ "The operating system will automatically close any open file descriptors when your process terminates.\nFile data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel...
[ 9, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003407522_python.txt
Q: using xpath to tell selenium where to click? I'm new to all of this but I've learned a few things about python not long time ago, could you help me specify the correct the XPath for selenium to click? I've tried this way, but didn't work, obviously :( self.selenium.click("xpath=//html/body/div/div/div/div[4]/ul/li...
using xpath to tell selenium where to click?
I'm new to all of this but I've learned a few things about python not long time ago, could you help me specify the correct the XPath for selenium to click? I've tried this way, but didn't work, obviously :( self.selenium.click("xpath=//html/body/div/div/div/div[4]/ul/li[3]/a") If you're wandering where did i get that ...
[ "Below are a few example locators you could use to click the Administration link (based on your XPath and HTML snippet). The correct Selenium command is click.\n\nlink=Administration\ncss=a:contains(Administration)\ncss=#menunav a:nth-child(3)\nxpath=id('menunav')/descendant::a[3]\n//a[text()='Administration']\n//a...
[ 6 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0003406103_python_selenium_xpath.txt
Q: python sort without lambda expressions I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me. I have a list of numbers, e.g., x = [12, 101, 4, 56, ...] I have a separate list of in...
python sort without lambda expressions
I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me. I have a list of numbers, e.g., x = [12, 101, 4, 56, ...] I have a separate list of indices: y = range(len(x)) I want to sort y ba...
[ "You can use the __getitem__ method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function:\n>>> x = [12, 101, 4, 56]\n>>> y = range(len(x))\n>>> sorted(y, key=x.__getitem__)\n[2, 0, 3, 1]\n\n", "Not elegantly, but:\n[a for...
[ 12, 7, 4, 0 ]
[]
[]
[ "lambda", "python", "sorting" ]
stackoverflow_0003407414_lambda_python_sorting.txt
Q: Python subprocess + mencoder not working, same command works in terminal I am having a problem using mencoder (SVN-r30531-4.2.1) through a python (2.6.1) subprocess. I am trying to join two mp4 files which are exactly the same size, codec, etc. Both have no audio. The code I am using to test is: import subprocess ...
Python subprocess + mencoder not working, same command works in terminal
I am having a problem using mencoder (SVN-r30531-4.2.1) through a python (2.6.1) subprocess. I am trying to join two mp4 files which are exactly the same size, codec, etc. Both have no audio. The code I am using to test is: import subprocess mp4merge = [ "mencoder", "in1.mp4", "in2.mp4", "-ovc", "copy", "-oac", "copy"...
[ "The problem here is that pMerge.stderr.readlines() blocks forever until the process is over. It reads all lines before continuing.\nSince mencoder writes a lot to the stdout, the stdout buffer is filled and mencoder is waiting for it to empty before it can continue. So the process never ends.\nHere's a way to do t...
[ 2 ]
[]
[]
[ "mencoder", "mp4", "python", "subprocess", "video" ]
stackoverflow_0003407742_mencoder_mp4_python_subprocess_video.txt
Q: Python Pickle Help I'm not sure why this Pickle example is not showing both of the dictionary definitions. As I understand it, "ab+" should mean that the pickle.dat file is being appended to and can be read from. I'm new to the whole pickle concept, but the tutorials on the net don't seem to go beyond just the ini...
Python Pickle Help
I'm not sure why this Pickle example is not showing both of the dictionary definitions. As I understand it, "ab+" should mean that the pickle.dat file is being appended to and can be read from. I'm new to the whole pickle concept, but the tutorials on the net don't seem to go beyond just the initial storage. import cPi...
[ "Don't use pickle for that. Use a database.\nPython dbm module seems to fit what you want perfectly. It presents you with a dictionary-like interface, but data is saved to disk.\nExample usage:\n>>> import dbm\n>>> x = dbm.open('/tmp/foo.dat', 'c')\n>>> x['Mouse'] = 'Mickey'\n>>> x['Bird'] = 'Tweety'\n\nTomorrow yo...
[ 5, 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0003407646_pickle_python.txt
Q: Genshi: TemplateSyntaxError: not well-formed (invalid token) with ampersands in I'm using Pylons/Genshi, and trying to show 'all recent comments' on my site with a Disqus javascript widget (Disqus is installed on the site, and I can post comments OK). However, the code below produces a nasty 500 error: Template...
Genshi: TemplateSyntaxError: not well-formed (invalid token) with ampersands in
I'm using Pylons/Genshi, and trying to show 'all recent comments' on my site with a Disqus javascript widget (Disqus is installed on the site, and I can post comments OK). However, the code below produces a nasty 500 error: TemplateSyntaxError: not well-formed (invalid token): line 25, column 121 (line 25 is the <scr...
[ "In XML, you should encode your ampersands, since they have special meaning.\nCorrect way to use them in urls is recent_comments_widget.js?num_items=5&amp;hide_avatars=0&amp;avatar_size=32&amp;excerpt_length=200\n", "In the first snippet you don't have ? before num_items and in the second you do. Try adding it to...
[ 4, 1 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0003408248_genshi_pylons_python.txt
Q: How to assert that zero or only one of N given arguments is passed I have a definition like this def bar(self, foo=None, bar=None, baz=None): pass I want to make sure a maximum of one of foo, bar, baz is passed. I can do if foo and bar: raise Ex() if foo and baz: raise Ex() .... But there got be so...
How to assert that zero or only one of N given arguments is passed
I have a definition like this def bar(self, foo=None, bar=None, baz=None): pass I want to make sure a maximum of one of foo, bar, baz is passed. I can do if foo and bar: raise Ex() if foo and baz: raise Ex() .... But there got be something simpler.
[ "How about:\n initialisers = [foo, bar, baz]\n if initialisers.count(None) < len(initialisers) - 1:\n raise Ex()\n\nIt simply counts how many None are present. If they're all None or only one isn't then fine, otherwise it raises the exception.\n", "x!=None returns True (whose numeric value is 1!) for non-None...
[ 9, 6, 4, 2, 1 ]
[ "Like this.\ndef func( self, **kw ):\n assert len(kw) == 1, \"Too Many Arguments\"\n assert kw.keys[0] in ( 'foo', 'bar', 'baz' ), \"Argument not foo, bar or baz\"\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001648956_python.txt
Q: Writing binary data to middle of a sparse file I need to compile a binary file in pieces with pieces arriving in random order (yes, its a P2P project) def write(filename, offset, data) file.open(filename, "ab") file.seek(offset) file.write(data) file.close() Say I have a 32KB write(f, o, d) at...
Writing binary data to middle of a sparse file
I need to compile a binary file in pieces with pieces arriving in random order (yes, its a P2P project) def write(filename, offset, data) file.open(filename, "ab") file.seek(offset) file.write(data) file.close() Say I have a 32KB write(f, o, d) at offset 1MB into file and then another 32KB write(f,...
[ ">>> import os\n>>> filename = 'tempfile'\n>>> def write(filename,data,offset):\n... try:\n... f = open(filename,'r+b')\n... except IOError:\n... f = open(filename,'wb')\n... f.seek(offset)\n... f.write(data)\n... f.close()\n...\n>>> write(filename,'1' * (1024*32),1024*1024)\n>>>...
[ 7, 4, 0, 0 ]
[]
[]
[ "binary", "file_io", "p2p", "python", "sparse_matrix" ]
stackoverflow_0003407505_binary_file_io_p2p_python_sparse_matrix.txt
Q: How to rewrite this Dictionary For Loop in Python? I have a Dictionary of Classes where the classes hold attributes that are lists of strings. I made this function to find out the max number of items are in one of those lists for a particular person. def find_max_var_amt(some_person) #pass in a patient id number, ...
How to rewrite this Dictionary For Loop in Python?
I have a Dictionary of Classes where the classes hold attributes that are lists of strings. I made this function to find out the max number of items are in one of those lists for a particular person. def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of var...
[ "Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like\nfor key in patients[some_person].__dict__:\n value = patients[some_person].__dict__[key]\n # then continue as before\n\nI think a bigger issue, though, will be the...
[ 2 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0003408725_dictionary_for_loop_python.txt
Q: Grid of clickable images in wxPython So I need to be able to open several images in a grid layout and click on the images to perform various actions. Right now I am adding the images to a grid sizer. How do I capture mouse events from a sizer? Or should I display the images in another way to make it easy to respon...
Grid of clickable images in wxPython
So I need to be able to open several images in a grid layout and click on the images to perform various actions. Right now I am adding the images to a grid sizer. How do I capture mouse events from a sizer? Or should I display the images in another way to make it easy to respond to mouse events?
[ "Bind one of the mouse events to your images\neg. \nyour_staticBitmap_object.bind(wx.EVT_LEFT_UP, self.onImageClick, your_staticBitmap_object)\n\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003408759_python_wxpython.txt
Q: Python UTF-8 comparison a = {"a":"çö"} b = "çö" a['a'] >>> '\xc3\xa7\xc3\xb6' b.decode('utf-8') == a['a'] >>> False What is going in there? edit= I'm sorry, it was my mistake. It is still False. I'm using Python 2.6 on Ubuntu 10.04. A: Possible solutions Either write like this: a = {"a": u"çö"} b = "çö" b.dec...
Python UTF-8 comparison
a = {"a":"çö"} b = "çö" a['a'] >>> '\xc3\xa7\xc3\xb6' b.decode('utf-8') == a['a'] >>> False What is going in there? edit= I'm sorry, it was my mistake. It is still False. I'm using Python 2.6 on Ubuntu 10.04.
[ "Possible solutions\nEither write like this:\na = {\"a\": u\"çö\"}\nb = \"çö\"\nb.decode('utf-8') == a['a']\n\nOr like this (you may also skip the .decode('utf-8') on both sides):\na = {\"a\": \"çö\"}\nb = \"çö\"\nb.decode('utf-8') == a['a'].decode('utf-8')\n\nOr like this (my recommendation):\na = {\"a\": u\"çö\"}...
[ 30, 5, 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "python_2.x", "unicode", "utf_8" ]
stackoverflow_0003400171_python_python_2.x_unicode_utf_8.txt
Q: How do I edit the url in python and open a new page without having a new window or tab opened? I am trying to create a python script that opens a single page at a time, however python + mozilla make it so everytime I do this, it opens up a new tab. I want it to keep just a single window open so that it can loop f...
How do I edit the url in python and open a new page without having a new window or tab opened?
I am trying to create a python script that opens a single page at a time, however python + mozilla make it so everytime I do this, it opens up a new tab. I want it to keep just a single window open so that it can loop forever without crashing due to too many windows or tabs. It will be going to about 6-7 websites and...
[ "In firefox, if you go to about:config and set browser.link.open_newwindow to \"1\", that will cause a clicked link that would open in a new window or tab to stay in the current tab. I'm not sure if this applies to calls from 3rd-party apps, but it might be worth a try.\nOf course, this will now apply to everything...
[ 1 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0003408891_browser_python.txt
Q: How to rotate a polygon on a Tkinter Canvas? I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the trian...
How to rotate a polygon on a Tkinter Canvas?
I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the triangle. I believe it has something to do with sin and...
[ "First of all, you need to rotate around a center of the triangle. The centroid would probably work best for that. To find that, you can use the formula C = (1/3*(x0 + x1 + x2), 1/3*(y0 + y1 + y2)), as it's the average of all points in the triangle. Then you have to apply the rotation with that point as the center....
[ 12 ]
[]
[]
[ "python", "tkinter", "vector" ]
stackoverflow_0003408779_python_tkinter_vector.txt
Q: Python regex string to list of words (including words with hyphens) I would like to parse a string to obtain a list including all words (hyphenated words, too). Current code is: s = '-this is. A - sentence;one-word' re.compile("\W+",re.UNICODE).split(s) returns: ['', 'this', 'is', 'A', 'sentence', 'one', 'word'] ...
Python regex string to list of words (including words with hyphens)
I would like to parse a string to obtain a list including all words (hyphenated words, too). Current code is: s = '-this is. A - sentence;one-word' re.compile("\W+",re.UNICODE).split(s) returns: ['', 'this', 'is', 'A', 'sentence', 'one', 'word'] and I would like it to return: ['', 'this', 'is', 'A', 'sentence', 'one-...
[ "If you don't need the leading empty string, you could use the pattern \\w(?:[-\\w]*\\w)? for matching:\n>>> import re\n>>> s = '-this is. A - sentence;one-word'\n>>> rx = re.compile(r'\\w(?:[-\\w]*\\w)?')\n>>> rx.findall(s)\n['this', 'is', 'A', 'sentence', 'one-word']\n\nNote that it won't match words with apostro...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003406771_python_regex.txt
Q: Python: saving image from web to disk Can I save images to disk using python? An example of an image would be: A: Easiest is to use urllib.urlretrieve. Python 2: import urllib urllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png') Python 3: import urllib.request urllib.request.urlretrieve('http:/...
Python: saving image from web to disk
Can I save images to disk using python? An example of an image would be:
[ "Easiest is to use urllib.urlretrieve.\nPython 2:\nimport urllib\nurllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')\n\nPython 3:\nimport urllib.request\nurllib.request.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')\n\n", "If your goal is to download a png to disk, you can do so...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003409104_python.txt
Q: Replacing a blank i am building a URL and replacing all the spaces with + url.replace(' ','+') for some reason it is not replacing any of the white spaces! anyone know what is wrong? A: The replace function doesn't replace anything in-place - you need to assign it: url = url.replace(' ','+') A: You are probbl...
Replacing a blank
i am building a URL and replacing all the spaces with + url.replace(' ','+') for some reason it is not replacing any of the white spaces! anyone know what is wrong?
[ "The replace function doesn't replace anything in-place - you need to assign it:\nurl = url.replace(' ','+')\n\n", "You are probbly still looking at the old url. replace returns new string with replaced values. Try:\nurl = url.replace(' ', '+')\n\n", "Aside:\nIf you are encoding a query or path component for in...
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003408772_python.txt
Q: Pythonistas, please help convert this to utilize Python Threading concepts Update : For anyone wondering what I went with at the end - I divided the result-set into 4 and ran 4 instances of the same program with one argument each indicating what set to process. It did the trick for me. I also consider PP module. T...
Pythonistas, please help convert this to utilize Python Threading concepts
Update : For anyone wondering what I went with at the end - I divided the result-set into 4 and ran 4 instances of the same program with one argument each indicating what set to process. It did the trick for me. I also consider PP module. Though it worked, it prefer the same program. Please pitch in if this is a horrib...
[ "Python threads can't run at the same time due to the Global Interpreter Lock; you want new processes instead. Look at the multiprocessing module.\n(I was instructed to post this as an answer =p.)\n" ]
[ 1 ]
[]
[]
[ "multithreading", "parallel_processing", "python" ]
stackoverflow_0003406654_multithreading_parallel_processing_python.txt
Q: Why am I getting this simplejson exception? Why does Django give me this exception [(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable When I try data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name') return HttpResponse(simplejson.dumps(data, ...
Why am I getting this simplejson exception?
Why does Django give me this exception [(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable When I try data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name') return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json')...
[ "This seems to work fine:\nIn [28]: a = [(7, u'Acura'), (18, u'Alfa Romeo'),]\n\nIn [29]: simplejson.dumps(a, ensure_ascii=False)\nOut[29]: u'[[7, \"Acura\"], [18, \"Alfa Romeo\"]]'\n\nSo it's not the first couple of tuples. You'll need to dig deeper in the records list to narrow down the issue. If it's large, pe...
[ 2, 1, 0 ]
[]
[]
[ "django", "exception", "python", "simplejson" ]
stackoverflow_0003269541_django_exception_python_simplejson.txt
Q: Appengine Blobstore - Video Streaming I'm trying to setup a video streaming app via the Google Appengine Blobstore. Just wanted to know if this was possible, as there isn't too much regarding this in the Appengine Documentation. Basically I want to serve these videos through a flash player. Thanks A: I would s...
Appengine Blobstore - Video Streaming
I'm trying to setup a video streaming app via the Google Appengine Blobstore. Just wanted to know if this was possible, as there isn't too much regarding this in the Appengine Documentation. Basically I want to serve these videos through a flash player. Thanks
[ "I would say the blobstore is suitable for this. While datastore entities are limited to 1MB and standard HTTP responses are limited to 10MB, with the blobstore you can upload, store, and serve files up to 2GB. The 30 second limit refers to how long your handler can execute; time spent downloading (or uploading) do...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003409549_google_app_engine_python.txt
Q: Limiting the searching of a large file So here is my program with some new modifications: datafile = open('C:\\text2.txt', 'r') completedataset = open('C:\\bigfile.txt', 'r') smallerdataset = open('C:\\smallerdataset.txt', 'w') matchedLines = [] for line in datafile: splitline = line.split() for item in sp...
Limiting the searching of a large file
So here is my program with some new modifications: datafile = open('C:\\text2.txt', 'r') completedataset = open('C:\\bigfile.txt', 'r') smallerdataset = open('C:\\smallerdataset.txt', 'w') matchedLines = [] for line in datafile: splitline = line.split() for item in splitline: if not item.endswith("NOVA"...
[ "For your splitting issue you can just limit the number of times it splits the line:\nfirst_item = str.split(\",\",maxsplit=1)[0]\n\n", "You could change\nif t in line:\n\nto\nif t in line[:line.find(',')]:\n\nThis may make the program faster if line is very very long and the comma appears near the beginning. Or ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003408871_python.txt
Q: Accessing Dictionaries VS Accessing Shelves Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so: dictionary[str(instantiated_class_id_number)].attribute1 Due to memory issues, I want to use the shelve module. I am wondering if doing...
Accessing Dictionaries VS Accessing Shelves
Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so: dictionary[str(instantiated_class_id_number)].attribute1 Due to memory issues, I want to use the shelve module. I am wondering if doing so is plausible. Does a shelve dictionary act th...
[ "Shelve doesn't act extactly the same as dictionary, notably when modifying objects that are already in the dictionary.\nThe difference is that when you add a class to a dictionary a reference is stored, but shelve keeps a pickled (serialized) copy of the object. If you then modify the object you will\nmodify the i...
[ 3, 0 ]
[]
[]
[ "dictionary", "python", "shelve" ]
stackoverflow_0003409856_dictionary_python_shelve.txt
Q: Getting started with Pylons and MVC - Need some guidance on design I've been getting more and more interested in using Pylons as my Python web framework and I like the idea of MVC but, coming from a background of never using 'frameworks/design patterns/ what ever it\'s called', I don't really know how to approach ...
Getting started with Pylons and MVC - Need some guidance on design
I've been getting more and more interested in using Pylons as my Python web framework and I like the idea of MVC but, coming from a background of never using 'frameworks/design patterns/ what ever it\'s called', I don't really know how to approach it. From what I've read in the Pylons Book, so far, it seems I do the fo...
[ "there is a book about pylons 0.9.7 [http://pylonsbook.com/].\nand after that see the updated docs to understand pylons 1 at [http://bitbucket.org/bbangert/quickwiki]\nand [http://bitbucket.org/bbangert/pylons].\nif you have a question go to the google groups for pylons [http://groups.google.com/group/pylons-discus...
[ 0, 0 ]
[]
[]
[ "design_patterns", "model_view_controller", "pylons", "python" ]
stackoverflow_0003350972_design_patterns_model_view_controller_pylons_python.txt
Q: python, svn, deploy applications with shared code I have a few related applications that I want to deploy to different computers. They each share a large body of common code, and have some things unique to them. For example, I have a server and a client which use a lot of common classes to communicate to each othe...
python, svn, deploy applications with shared code
I have a few related applications that I want to deploy to different computers. They each share a large body of common code, and have some things unique to them. For example, I have a server and a client which use a lot of common classes to communicate to each other. I have yet more servers and clients which use some o...
[ "When it can be broken up in modules, go for a repo / branch with all the 'base' code, and in the actual project, include them as svn:externals (same repository or another one doesn't matter). That way you can independently update / work on modules, pin certain projects to certain revisions of that module or keep t...
[ 2 ]
[]
[]
[ "deployment", "python", "svn", "version_control" ]
stackoverflow_0003410228_deployment_python_svn_version_control.txt
Q: Subversion python bindings could not be loaded This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one command is: hg convert file://c:/svnrepository but, the output I get is: assuming destination svnrepository-hg initializing destination svnrepository-hg repository file://c:/svnreposi...
Subversion python bindings could not be loaded
This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one command is: hg convert file://c:/svnrepository but, the output I get is: assuming destination svnrepository-hg initializing destination svnrepository-hg repository file://c:/svnrepository does not look like a CVS checkout file://c:/svn...
[ "I just wanted to bring the actual solution out of the comments to Alex Martelli's answer:\n\nAccording to https://www.mercurial-scm.org/pipermail/mercurial/2009-May/026015.html the subversion bindings are included in tortoisehg. So you just need to enable the convert extension in tortoisehg. – tonfa\nAh ha! Anoth...
[ 21, 14, 5 ]
[]
[]
[ "mercurial", "python", "svn", "windows" ]
stackoverflow_0001657918_mercurial_python_svn_windows.txt
Q: python: unhashable type error Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> do_work() File "C:\pythonwork\readthefile080410.py", line 14, in do_work populate_frequency5(e,data) File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5 data=medicatio...
python: unhashable type error
Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> do_work() File "C:\pythonwork\readthefile080410.py", line 14, in do_work populate_frequency5(e,data) File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5 data=medications_minimum3(data,[drug.upper()],1) ...
[ "counter[row[11]]+=1\n\nYou don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashab...
[ 16, 10, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003410206_python.txt
Q: Approaches to embedded vector images/charts into PDF How have people from the Linux world embedded vector images into PDF? I am attempting to create automated reports from data that I currently render as SVG images. Ideally, I would like to use the same XML in PostScript, PDF or DjVu format. To what degree are tho...
Approaches to embedded vector images/charts into PDF
How have people from the Linux world embedded vector images into PDF? I am attempting to create automated reports from data that I currently render as SVG images. Ideally, I would like to use the same XML in PostScript, PDF or DjVu format. To what degree are those formats able to handle SVG natively? More broadly, what...
[ "Investigate Apache FOP, its main purpose is to convert XML to PDF.\nUpsides (for this project):\n\nfull Apache project (=> reliable)\n\nDownsides (for this project):\n\nWill need to learn XSL-FO\nNot Python\n\n", "Batik is a nice Java SVG library. It has a utility library called batik-rasterizer.jar which can co...
[ 0, 0 ]
[]
[]
[ "linux", "pdf_generation", "python" ]
stackoverflow_0003402576_linux_pdf_generation_python.txt
Q: Working on Dictionary of Classes in Python For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed. #import shelve class Pokemon(): """Each pokemon's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var...
Working on Dictionary of Classes in Python
For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed. #import shelve class Pokemon(): """Each pokemon's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var5=[] def __str__(self): showList=['id','va...
[ "dict1=shelve.open(\"shelve.dat\", writeback=True)\n\nyou can also specify the protocol which should improve performance\ndict1=shelve.open(\"shelve.dat\", protocol=2, writeback=True)\n\n\nBecause of Python semantics, a shelf\n cannot know when a mutable\n persistent-dictionary entry is\n modified. By default mo...
[ 1 ]
[]
[]
[ "dictionary", "python", "shelve" ]
stackoverflow_0003410452_dictionary_python_shelve.txt
Q: Unit Testing / Eclipse / Command Line I have project with the following layout (Python 2.4.3) root +--- src +--- xyz +--- __init__.py +--- C1.py +--- C2.py +--- test +--- xyz +--- __init__.py +--- CXMock.py +---...
Unit Testing / Eclipse / Command Line
I have project with the following layout (Python 2.4.3) root +--- src +--- xyz +--- __init__.py +--- C1.py +--- C2.py +--- test +--- xyz +--- __init__.py +--- CXMock.py +--- C1Test.py +--- C2Test.py So...
[ "You don't include the \".py\" on your imports. Try:\nfrom xyz.CXMock import CXMock\n\n" ]
[ 2 ]
[]
[]
[ "eclipse", "pydev", "python", "unit_testing" ]
stackoverflow_0003203082_eclipse_pydev_python_unit_testing.txt
Q: urllib2 connection timed out error I am trying to open a page using urllib2 but i keep getting connection timed out errors. The line which i am using is: f = urllib2.urlopen(url) exact error is: URLError: <urlopen error [Errno 110] Connection timed out> A: urllib2 respects robots.txt. Many sites block the def...
urllib2 connection timed out error
I am trying to open a page using urllib2 but i keep getting connection timed out errors. The line which i am using is: f = urllib2.urlopen(url) exact error is: URLError: <urlopen error [Errno 110] Connection timed out>
[ "urllib2 respects robots.txt. Many sites block the default User-Agent.\nTry adding a new User-Agent, by creating Request objects & using them as arguments for urlopen:\nimport urllib2\n\nrequest = urllib2.Request('http://www.example.com/')\nrequest.add_header('User-agent', 'Mozilla/5.0 (Linux i686)')\n\nresponse = ...
[ 4, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003197299_python_urllib2.txt
Q: how to calculate timedelta python What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for e...
how to calculate timedelta python
What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for ease: from datetime import datetime dt ...
[ "\nWhat is the timedelta line doing? How does it work?\n\nIt creates a timedelta object.\nThere are two meanings of \"time\". \n\n\"Point in Time\" (i.e, date or datetime)\n\"Duration\" or interval or \"time delta\"\n\nA time delta is an interval, a duration, a span of time. You provided 3 values.\n\n0 days.\n2...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003410439_python.txt
Q: Python's join() won't join the string representation (__str__) of my object I'm not sure what I'm doing wrong here: >>> class Stringy(object): ... def __str__(self): ... return "taco" ... def __repr__(self): ... return "taco" ... >>> lunch = Stringy() >>> lunch taco >>> str(lunch) ...
Python's join() won't join the string representation (__str__) of my object
I'm not sure what I'm doing wrong here: >>> class Stringy(object): ... def __str__(self): ... return "taco" ... def __repr__(self): ... return "taco" ... >>> lunch = Stringy() >>> lunch taco >>> str(lunch) 'taco' >>> '-'.join(('carnitas',lunch)) Traceback (most recent call last): Fi...
[ "no you have to convert it to str yourself\n'-'.join(('carnitas',str(lunch)))\n\nif you have to do it for a whole sequence of items\n'-'.join(str(x) for x in seq)\n\nor \n'-'.join(map(str, seq))\n\nfor your particular case you can just write \n'carnitas-'+str(lunch)\n\n", "''.join does not call __str__ on the ite...
[ 14, 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003410647_python.txt
Q: Calling cgi.FieldStorage for an arbitrary url I'd like to get field values corresponding to an arbitrary URL. I.e. given "http://example.com/hello?q=1&b=1" I want a dictionary {'q':1, 'b':1}. How do I use cgi.FieldStorage for that? Thanks! A: You can use urlparse to do that from urlparse import urlparse, parse_q...
Calling cgi.FieldStorage for an arbitrary url
I'd like to get field values corresponding to an arbitrary URL. I.e. given "http://example.com/hello?q=1&b=1" I want a dictionary {'q':1, 'b':1}. How do I use cgi.FieldStorage for that? Thanks!
[ "You can use urlparse to do that\nfrom urlparse import urlparse, parse_qs\nqs = urlparse(\"http://example.com/hello?q=1&b=1\").query\nparse_qs(qs)\n\nif you must use FieldStorage\ncgi.FieldStorage(environ={'REQUEST_METHOD':'GET', 'QUERY_STRING':qs})\n\n", "You don't -- you use cgi.parse_qs in 2.5 or earlier, urlp...
[ 3, 2 ]
[]
[]
[ "html", "http", "python", "url" ]
stackoverflow_0003410713_html_http_python_url.txt
Q: objective C and python - pyobjc Is it possible for an objective c application to run python files and read their data, etc? If so, can someone post code? or lead me in the right direction? Thanks, Elijah A: Sure, see the tutorial -- it's very dated but should still apply today. (Apple's tutorial is good, but it...
objective C and python - pyobjc
Is it possible for an objective c application to run python files and read their data, etc? If so, can someone post code? or lead me in the right direction? Thanks, Elijah
[ "Sure, see the tutorial -- it's very dated but should still apply today. (Apple's tutorial is good, but it only shows how to call ObjC from Python, while pyobjc's own tutorial, while extremely short, focuses on the opposite direction -- calling Python from ObjC -- which appears to be what you want).\n" ]
[ 1 ]
[]
[]
[ "objective_c", "pyobjc", "python" ]
stackoverflow_0003410480_objective_c_pyobjc_python.txt
Q: How do I use SQL parameters with python? I am using python 2.7 and pymssql 1.9.908. In .net to query the database I would do something like this: using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection)) { com.Parameters.AddWithValue("@CustomerID", CustomerID)...
How do I use SQL parameters with python?
I am using python 2.7 and pymssql 1.9.908. In .net to query the database I would do something like this: using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection)) { com.Parameters.AddWithValue("@CustomerID", CustomerID); //Do something with the command } I am ...
[ "After creating a connection object db:\ncursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])\n\nthen use any of the fetch... methods of the resulting cursor object.\nDon't be fooled by the %s part: this is NOT string formatting, it's parameter substitution (different DB API modules us...
[ 24 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0003410455_pymssql_python.txt
Q: How to upload pdf and pptx files to google docs via the gdata python client? I'm using the gdata python client for the google docs api for a project. I use oauth authentication and all the dance, and have successfully uploaded .doc, .xls and every file type in Their FAQ. but I cannot seem to upload pdf files, eve...
How to upload pdf and pptx files to google docs via the gdata python client?
I'm using the gdata python client for the google docs api for a project. I use oauth authentication and all the dance, and have successfully uploaded .doc, .xls and every file type in Their FAQ. but I cannot seem to upload pdf files, even though is right there, listed on the supported filetypes. I tried with the lates...
[]
[]
[ "Done.\nFirst did this\nhttp://code.google.com/p/gdata-issues/issues/detail?id=591#c77\nbut now I was getting a bad request error \"invalid request uri\". So I then discovered in another google thread that the uri for the v3.0 apis was no longer http://docs.google.com/feeds/folders/private/full/<resource-id> but ht...
[ -1 ]
[ "gdata", "gdata_python_client", "google_docs", "python" ]
stackoverflow_0003401623_gdata_gdata_python_client_google_docs_python.txt
Q: Define dtypes in NumPy using a list? I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv): name1 name2 name3 . . . name1 # # # name2 # # # name2 # # # . . . The matrix (n...
Define dtypes in NumPy using a list?
I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv): name1 name2 name3 . . . name1 # # # name2 # # # name2 # # # . . . The matrix (numerical array in the center), is already ...
[ "The following code might help:\nimport numpy as np\n\ndt = np.dtype([('name1', '|S10'), ('name2', '<f8')])\ntuplelist=[\n ('n1', 1.2),\n ('n2', 3.4), \n ]\narr = np.array(tuplelist, dtype=dt)\n\nprint(arr['name1'])\n# ['n1' 'n2']\nprint(arr['name2'])\n# [ 1.2 3.4]\n\nYour immediate problem was that n...
[ 12 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003410147_numpy_python.txt
Q: Summarizing a dictionary of arrays in Python I got the following dictionary: mydict = { 'foo': [1,19,2,3,24,52,2,6], # sum: 109 'bar': [50,5,9,7,66,3,2,44], # sum: 186 'another': [1,2,3,4,5,6,7,8], # sum: 36 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'onemore': [21,22,23,...
Summarizing a dictionary of arrays in Python
I got the following dictionary: mydict = { 'foo': [1,19,2,3,24,52,2,6], # sum: 109 'bar': [50,5,9,7,66,3,2,44], # sum: 186 'another': [1,2,3,4,5,6,7,8], # sum: 36 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'onemore': [21,22,23,24,25,26,27,28] # sum: 196 } I need to efficient...
[ "It's easy to do with a sort:\nsorted(mydict.iteritems(), key=lambda tup: sum(tup[1]), reverse=True)[:3]\n\nThis is reasonable if the ratio is similar to this one (3 / 5). If it's larger, you'll want to avoid the sort (O(n log n)), since top 3 can be done in O(n). For instance, using heapq, the heap module:\nheap...
[ 7, 2 ]
[]
[]
[ "algorithm", "arrays", "dictionary", "python" ]
stackoverflow_0003411025_algorithm_arrays_dictionary_python.txt
Q: Why does the Python 2.7 AMD 64 installer seem to run Python in 32 bit mode? I've installed Python 2.7 from the python-2.7.amd64.msi package from python.org. It installs and runs correctly, but seems to be in 32-bit mode, despite the fact that the installer was a 64 bit installer. Python 2.7 (r27:82525, Jul 4 201...
Why does the Python 2.7 AMD 64 installer seem to run Python in 32 bit mode?
I've installed Python 2.7 from the python-2.7.amd64.msi package from python.org. It installs and runs correctly, but seems to be in 32-bit mode, despite the fact that the installer was a 64 bit installer. Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "cred...
[ "See the discussion here. It's from 2.6.1, but it seems to still apply. I haven't seen evidence to the contrary anywhere, at least. The gist of the matter (quoted from that link) is:\n\nThis is by design. In their infinitive wisdom Microsoft has decided to\n make the 'long' C type always a 32 bit signed integer - ...
[ 14, 3 ]
[]
[]
[ "64_bit", "python", "windows" ]
stackoverflow_0003411079_64_bit_python_windows.txt
Q: Things to consider when creating a web framework I am not trying to create yet another web framework. For one of the applications I am working on, I want to create a custom framework. I don't want to use any already available framework. What are the common things to consider? What should be the architecture? Thank...
Things to consider when creating a web framework
I am not trying to create yet another web framework. For one of the applications I am working on, I want to create a custom framework. I don't want to use any already available framework. What are the common things to consider? What should be the architecture? Thanks :)
[ "If the point of a framework is to make tedious things easy, a good start would be to consider what is tedious.\n", "What are the common things to consider?\nPurpose. Usually, when you start building a piece of software, you have a purpose in mind. What will it do that other programs can't?\nIf you can't answer t...
[ 2, 1, 0 ]
[]
[]
[ "frameworks", "php", "python", "ruby" ]
stackoverflow_0003411176_frameworks_php_python_ruby.txt
Q: wxPython: Window and Event Id's I have a Panel on which I display a StaticBitmap initialised with an id of 2. When I bind a mouse event to the image and call GetId() on the event, it returns -202. Why? import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1): wx.Frame.__init__(self,paren...
wxPython: Window and Event Id's
I have a Panel on which I display a StaticBitmap initialised with an id of 2. When I bind a mouse event to the image and call GetId() on the event, it returns -202. Why? import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1): wx.Frame.__init__(self,parent,id) self.panel = wx.Panel(...
[ "You're printing the event's ID, not the bitmap's ID.\nTry print event.GetEventObject().GetId()\nGetEventObject returns the widget associated with the event, in this case, the StaticBitmap.\nFWIW, I've never needed to assign ID's to any widgets, and you probably shouldn't need to either.\nEdit: I saw some other que...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003411361_python_wxpython.txt
Q: How to use simplejson to decode following data? I grab some data from a URL, and search online to find out the data is in in Jason data format, but when I tried to use simplejson.loads(data), it will raise exception. First time deal with jason data, any suggestion how to decode the data? Thanks ================= ...
How to use simplejson to decode following data?
I grab some data from a URL, and search online to find out the data is in in Jason data format, but when I tried to use simplejson.loads(data), it will raise exception. First time deal with jason data, any suggestion how to decode the data? Thanks ================= result = simplejson.loads(data, encoding="utf-8") ...
[ "You're using simplejson correctly, but the site that gave you that data isn't using JSON format properly. Look at json.org, which uses simple syntax diagrams to show what is JSON: in the object diagram, after { (unless the object is empty, in which case a } immediately follows), JSON always has a string -- and as...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003411469_python.txt
Q: Python permutation generator puzzle I am writing a permutation function that generate all permutations of a list in Python. My question is why this works: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outp...
Python permutation generator puzzle
I am writing a permutation function that generate all permutations of a list in Python. My question is why this works: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): ...
[ "You must also yield the results of the recursive call(s):\ndef permute(inputData, outputSoFar):\n for a in inputData:\n if a not in outputSoFar:\n if len(outputSoFar) == len(inputData) - 1:\n yield outputSoFar + [a]\n else:\n for b in permute(inputData,...
[ 3, 0 ]
[]
[]
[ "generator", "permutation", "puzzle", "python", "recursion" ]
stackoverflow_0003411612_generator_permutation_puzzle_python_recursion.txt
Q: Python logging for non-trivial uses? I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a ...
Python logging for non-trivial uses?
I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a collection of other loggers that go to dif...
[ "First off, I get a different output on my machine (running Python 2.6):\nROOT\nBOTTOM HANDLER\nTOP HANDLER\nROOT\n\nFiltering is only applied on the logger that the message is issued to, and if it passes the filters, it's then propagated to all the handlers of the parent loggers (and not the loggers themselves) - ...
[ 7, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001580828_logging_python.txt
Q: Simple Twisted server won't write with Timer I'm just learning Python and Twisted and I can't figure out for the life of me why this simple server won't work. The self.transport.write doesn't work when called from a timer. I get no error at all. Any help appreciated. Thank you very much! from twisted.internet.prot...
Simple Twisted server won't write with Timer
I'm just learning Python and Twisted and I can't figure out for the life of me why this simple server won't work. The self.transport.write doesn't work when called from a timer. I get no error at all. Any help appreciated. Thank you very much! from twisted.internet.protocol import Factory, Protocol from twisted.interne...
[ "I figured it out myself.\nFrom http://twistedmatrix.com/documents/current/core/howto/threading.html:\n\nMost code in Twisted is not thread-safe. For example, writing data to a transport from a protocol is not thread-safe.\n\nThanks anyways folks!\n" ]
[ 2 ]
[]
[]
[ "python", "timer", "twisted" ]
stackoverflow_0003411511_python_timer_twisted.txt
Q: How can I get the installed GDAL/OGR version from python? How can I get the installed GDAL/OGR version from python? I aware of the gdal-config program and are currently using the following: In [3]: import commands In [4]: commands.getoutput('gdal-config --version') Out[4]: '1.7.2' However, I suspect there is a w...
How can I get the installed GDAL/OGR version from python?
How can I get the installed GDAL/OGR version from python? I aware of the gdal-config program and are currently using the following: In [3]: import commands In [4]: commands.getoutput('gdal-config --version') Out[4]: '1.7.2' However, I suspect there is a way to do this using the python API itself. Any dice?
[ "gdal.VersionInfo() does what I want:\n>>> osgeo.gdal.VersionInfo()\n'1604'\n\nThis works on both my Windows box and Ubuntu install. gdal.__version__ gives an error on my Windows installation, although it works on my Ubuntu installation:\n>>> import osgeo.gdal\n>>> print osgeo.gdal.__version__\nTraceback (most rec...
[ 25, 16 ]
[]
[]
[ "gdal", "geospatial", "gis", "ogr", "python" ]
stackoverflow_0003233674_gdal_geospatial_gis_ogr_python.txt
Q: Simple "Hello-World" program for python-evince I'm trying to write a simple "hello-world"-type program using the python-evince package for lucid-lynx gnome, that embeds Evince in a python-gtk window. The samples I've found on the web go like this: import evince import gtk w = gtk.Window() w.show() e = evince.Vi...
Simple "Hello-World" program for python-evince
I'm trying to write a simple "hello-world"-type program using the python-evince package for lucid-lynx gnome, that embeds Evince in a python-gtk window. The samples I've found on the web go like this: import evince import gtk w = gtk.Window() w.show() e = evince.View() w.add(e) e.show() document = evince.document_fa...
[ "The API has changed, with an extra step added. These instructions should help:\n>>> e = evince.View()\n>>> docmodel = evince.DocumentModel()\n>>> doc = evince.document_factory_get_document('file:///path/to/file/example.pdf')\n>>> docmodel.set_document(doc)\n>>> e.set_model(model)\n\n" ]
[ 1 ]
[]
[]
[ "gnome", "gtk", "python" ]
stackoverflow_0003411929_gnome_gtk_python.txt
Q: Pattern matching in dictionary using python In the following dictionary,can the elements be sorted according the last prefix in the key opt_dict=( {'option1':1, 'nonoption2':1, 'nonoption3':12, 'option4':6, 'nonoption5':5, 'option6':1, 'option7':1, }) for key,val in opt_dict.items(): if "an...
Pattern matching in dictionary using python
In the following dictionary,can the elements be sorted according the last prefix in the key opt_dict=( {'option1':1, 'nonoption2':1, 'nonoption3':12, 'option4':6, 'nonoption5':5, 'option6':1, 'option7':1, }) for key,val in opt_dict.items(): if "answer" in key: //match keys last prefix and print...
[ "for k,v in sorted(opt_dict.items(),\n key = lambda item: int(item[0][len(\"option\"):])\n if item[0].startswith(\"option\")\n else int(item[0][len(\"nonoption\"):])\n ):\n print k,v\n\nPrints:\noption1 1\nnonoption2 1\nnon...
[ -2 ]
[]
[]
[ "python" ]
stackoverflow_0003412310_python.txt
Q: Printing the values of a tuple Accessing tuple values How to access the value of a and b in the following >> t=[] >> t.append(("a" , 1)) >> t.append(("b" , 2)) >> print t[0][0] a >> print t[1][0] b How to print the values of a and b A: Just do print t[0][1] ...
Printing the values of a tuple
Accessing tuple values How to access the value of a and b in the following >> t=[] >> t.append(("a" , 1)) >> t.append(("b" , 2)) >> print t[0][0] a >> print t[1][0] b How to print the values of a and b
[ "Just do\nprint t[0][1]\nprint t[1][1]\n\nBut of course if you really want to look up for a or b, this is not the best construct, then you need a dict:\nt = {}\nt[\"a\"] = 1\nt[\"b\"] = 2\nprint t[\"a\"]\nprint t[\"b\"]\n\n", "It's simpler than expected: \n>> t=[]\n>> t.append((\"a\" , 1))\n>> t.append((\"b\" , 2...
[ 5, 2, 1 ]
[ "print t[0][1]\nprint t[1][1]\n\n??\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0003412576_python.txt
Q: Python cut a string after Xth sentence I have to cut a unicode string which is actually an article (contains sentences) I want to cut this article string after Xth sentence in python. A good indicator of a sentence ending is that it ends with full stop (".") and the word after start with capital name. Such as myar...
Python cut a string after Xth sentence
I have to cut a unicode string which is actually an article (contains sentences) I want to cut this article string after Xth sentence in python. A good indicator of a sentence ending is that it ends with full stop (".") and the word after start with capital name. Such as myarticle == "Hi, this is my first sentence. And...
[ "Consider downloading the Natural Language Toolkit (NLTK). Then you can create sentences that will not break for things like \"U.S.A.\" or fail to split sentences that end in \"?!\". \n>>> import nltk\n>>> paragraph = u\"Hi, this is my first sentence. And this is my second. Yet this is my third.\"\n>>> sentences = ...
[ 15, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003412316_python_string.txt
Q: Threading in Python I have two definitions or methods in python. I'd like to run them at the same exact time. Originally I tried to use forking but since the child retained the memory from the parent, it's writing multiple things that I don't need in a file. So I switched to threading. I have something similar to...
Threading in Python
I have two definitions or methods in python. I'd like to run them at the same exact time. Originally I tried to use forking but since the child retained the memory from the parent, it's writing multiple things that I don't need in a file. So I switched to threading. I have something similar to import threading class t...
[ "The __list and __numA won't be visible from makelist and makelist2 if they are not also members of the same class. The double underscore will make things like this fail:\n>>> class A(object):\n... def __init__(self):\n... self.__a = 2\n...\n>>> def f(x):\n... print x.__a\n...\n>>> a = A()\n>>> f(a)\nT...
[ 1, 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003412283_multithreading_python.txt
Q: Monitor Global keyboard input on a Mac with python Trying to write a program that allows users to control a program via global shortcuts. I already have a working version on windows using pyHook but can't figure out how to capture global input on a Mac. The other questions I have read here so far mostly seemed to ...
Monitor Global keyboard input on a Mac with python
Trying to write a program that allows users to control a program via global shortcuts. I already have a working version on windows using pyHook but can't figure out how to capture global input on a Mac. The other questions I have read here so far mostly seemed to be about Linux not Mac. (which is why I'm asking) Is the...
[ "I believe you could use PyObjC to handle the API hooks; look at this explanation for what to do.\n" ]
[ 0 ]
[]
[]
[ "input", "keyboard", "macos", "python" ]
stackoverflow_0003412329_input_keyboard_macos_python.txt