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: How do I make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window? I'm just getting started with Tk and using it in python. I set up a button that does a ton (like two minutes worth) of stuff behind the scenes when you press it. I also set up a status text...
How do I make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window?
I'm just getting started with Tk and using it in python. I set up a button that does a ton (like two minutes worth) of stuff behind the scenes when you press it. I also set up a status text to show what's going on while this is happening. I set it up like this: status_text = Tkinter.StringVar() ttk.Button(mainframe,...
[ "It's time to learn multithreading!\nWhat's happening is that the GUI (main thread) is waiting for the method to return so that it can continue updating the interface.\nYou'll want to cause the action of a button to spawn a threading.Thread instead of running the heavy code in the main thread. You'll also want to c...
[ 1, 1 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0006713675_python_tkinter_user_interface.txt
Q: Problems loading JSON code in Python I've been tyring to figure out how to load JSON objects in Python. I'm able to send a JSON string to the server, but there it fails. This is what I'm sending through a websocket with JavaScript: ws.send('{"test":"test"}'); The server receives it without a problem, but can't va...
Problems loading JSON code in Python
I've been tyring to figure out how to load JSON objects in Python. I'm able to send a JSON string to the server, but there it fails. This is what I'm sending through a websocket with JavaScript: ws.send('{"test":"test"}'); The server receives it without a problem, but can't validate it: {"test":"test"} This is not a J...
[ "import traceback\ntry:\n d = json.loads(data[data.index('{'):-1])\nexcept:\n traceback.print_exc()\nelse:\n print(d)\n\nThis way only the dictionary part of the data-string is parsed to json.loads(). \n" ]
[ 1 ]
[]
[]
[ "javascript", "json", "python", "websocket" ]
stackoverflow_0003337447_javascript_json_python_websocket.txt
Q: Django - Trouble Loading JQuery I cannot load JQuery no matter what I do! I did exactly what was suggested in this Question --> Load jQuery into Django but I dont want to use dynamic directories in my settings.py. Static directories are fine as this is just a personal project. From Settings.py: MEDIA_ROOT = '/usr/...
Django - Trouble Loading JQuery
I cannot load JQuery no matter what I do! I did exactly what was suggested in this Question --> Load jQuery into Django but I dont want to use dynamic directories in my settings.py. Static directories are fine as this is just a personal project. From Settings.py: MEDIA_ROOT = '/usr/local/djcode/mysite/media/' MEDIA_UR...
[ "If your media url is \"http://127.0.0.1/django/media\" then the path of the file would be \"http://127.0.0.1/django/media/jquery-1.2.6.js\" Try just using your media url in the template:\n<script type=\"text/javascript\" src=\"{{ MEDIA_URL }}jquery-1.2.6.js\"></script>\n\n" ]
[ 1 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0006714919_django_javascript_jquery_python.txt
Q: Python program to transfer gmail between accounts (including labels) The problem, transfer all emails including labels, sent, drafts... from one google apps account to another using python. This seems possible using imap. A complete program would be great :-) but if anyone has some suggestions or examples of how t...
Python program to transfer gmail between accounts (including labels)
The problem, transfer all emails including labels, sent, drafts... from one google apps account to another using python. This seems possible using imap. A complete program would be great :-) but if anyone has some suggestions or examples of how to go about this specific to gmail that would be great.
[ "I used this tool, which can preserve labels:\nhttp://www.gmail-backup.com/\nIt's written in python.\n" ]
[ 2 ]
[]
[]
[ "gmail", "gmail_imap", "google_apps", "python" ]
stackoverflow_0006715176_gmail_gmail_imap_google_apps_python.txt
Q: Call stored procedure from SQLAlchemy In SQLAlchemy, what is the preferred way to call a stored database procedure? (including set arguments and receive exit status and outputted variables) I've seen some examples that use execute() to execute a raw database string, but this could contain vendor specific syntax, r...
Call stored procedure from SQLAlchemy
In SQLAlchemy, what is the preferred way to call a stored database procedure? (including set arguments and receive exit status and outputted variables) I've seen some examples that use execute() to execute a raw database string, but this could contain vendor specific syntax, right?
[ "Yes you can use execute and it can indeed contain vendor specific syntax. \nYou should also consider using outparam. \nFrom SQLAlchemy Docs :\n\nsqlalchemy.sql.expression.outparam(key, type_=None) Create an ‘OUT’\n parameter for usage in functions (stored procedures), for databases\n which support them.\nThe o...
[ 5 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006713430_python_sqlalchemy.txt
Q: Python Regex - getting file name I'm having trouble with the following I need to use a regex to get the file name, after a 'Name: ' Name: somefile.something.0001.bla Name: somestuff.0212.somethat.hah I need everything but 'Name: ' A: if you're sure that it is always "Name: " that you want to remove, you can do...
Python Regex - getting file name
I'm having trouble with the following I need to use a regex to get the file name, after a 'Name: ' Name: somefile.something.0001.bla Name: somestuff.0212.somethat.hah I need everything but 'Name: '
[ "if you're sure that it is always \"Name: \" that you want to remove, you can do\nmy_string[6:]\n\n", "You don't need regex for that... But, if you really want:\nre.sub(r'^Name: ', '', string)\n\nOr something more useful to remove extra spaces\nre.sub(r'^Name:\\s+', '', string)\n\n", "There is probably more tha...
[ 2, 1, 0 ]
[ "index = mystring.find(\"Name:\")\nnewstring = mystring[:index]+mystring[index+5:]\n\n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0006715322_python_regex.txt
Q: Is it possible to create a python documentation when there are no classes? I have many python files. Each file has functions. That's it. I don't do anything with classes. Will Sphinx (or another documentation software) still create the documentation for it, and if so, what will it look like? A: Yes, of course. ...
Is it possible to create a python documentation when there are no classes?
I have many python files. Each file has functions. That's it. I don't do anything with classes. Will Sphinx (or another documentation software) still create the documentation for it, and if so, what will it look like?
[ "Yes, of course. That's one of the many normal ways to program in Python. You don't have to use classes -- in fact, many of the modules that come with Python are just collections of functions. Any Python documentation tool will be prepared to deal with this.\n", "Ideally, Python functions and classes are all docu...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006715436_python.txt
Q: On passing arguments to super class, an error flags: "module.__init__() takes at most 2 arguments (3 given)"? class info: def __init__(self, **kwargs): self._variables = kwargs class waybill(info): def __init__(self, **kwargs): super(waybill, self).__init__(**kwargs) Error -: module.__ini...
On passing arguments to super class, an error flags: "module.__init__() takes at most 2 arguments (3 given)"?
class info: def __init__(self, **kwargs): self._variables = kwargs class waybill(info): def __init__(self, **kwargs): super(waybill, self).__init__(**kwargs) Error -: module.__init__() takes at most 2 arguments (3 given) What could probably the reason why this error is flagging? I am using Py...
[ "Is info defined in the same file? Or is it info.info from info.py? If you're importing info, trying changing it to the following:\nfrom info import info\n\nAdditional information: If you simply import info then info is a module, and waybill is subclassing module.\n", "super(waybill, self).__init__(kwargs)\n\nsho...
[ 9, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006715404_python_python_3.x.txt
Q: Python removing similar urls from a list So I am fairly new to python. But would like your help solving this minor issue I having removing similar duplicates out of a list. So I have a list of urls: myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/'] I wan...
Python removing similar urls from a list
So I am fairly new to python. But would like your help solving this minor issue I having removing similar duplicates out of a list. So I have a list of urls: myList = ['http://www.mywebsite.com/shoes', 'http://wwww.yourwebsite.com/', 'http://www.mywebsite.com/shoes/'] I want to remove similar url's as you can see http:...
[ "If similarity for you is difference in '\\' thab you can use sets(read tutorial here) and here to remove duplicates from your list since:\n\nA set object is an unordered collection of distinct hashable objects.\n Common uses include membership testing, removing duplicates from a\n sequence, and computing mathema...
[ 2, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006715486_list_python.txt
Q: Is it possible to extend SQLAlchemy to add the ability to lock the database? I'm beginning to develop a site in Pyramid and, before I commit to using SQLAlchemy, would like to know if it's possible to wrap/extend it to add in 'database lock' functionality. One quick example as to why I'd like this functionality is...
Is it possible to extend SQLAlchemy to add the ability to lock the database?
I'm beginning to develop a site in Pyramid and, before I commit to using SQLAlchemy, would like to know if it's possible to wrap/extend it to add in 'database lock' functionality. One quick example as to why I'd like this functionality is for write throttling. My wrapper will be able to detect if a user is flooding the...
[ "Detecting excessive network traffic from particular clients is something you might be doing outside the ORM, even outside the Python app, like at the network or database client configuration level. \nIf within the Python app, definitely not in the ORM. add() doesn't correspond very cleanly to a SQL statement i...
[ 1 ]
[]
[]
[ "database", "python", "sqlalchemy" ]
stackoverflow_0006692085_database_python_sqlalchemy.txt
Q: Python integer * float = NotImplemented So I was messing around writing a vector class when I discovered this interesting fact. >>> e = int(3) >>> e.__mul__(3.0) NotImplemented Can anyone explain why this is and subsequently, how to fix my vector class? class Vector(tuple): '''A vector representation.''' ...
Python integer * float = NotImplemented
So I was messing around writing a vector class when I discovered this interesting fact. >>> e = int(3) >>> e.__mul__(3.0) NotImplemented Can anyone explain why this is and subsequently, how to fix my vector class? class Vector(tuple): '''A vector representation.''' def __init__(self, iterable): super(V...
[ "That's because when you do 3 * 3.0 the interpreter is calling (3.0).__rmul__(3) after realizing that (3).__mul__(3.0) is not implemented\nFloat's __mul__ and __rmul__ functions do cast integers to float but that should not happen with the int class.\nOtherwise 3 * 3.5 would be 9 instead of 10.5 \nThe second quest...
[ 12 ]
[]
[]
[ "operator_keyword", "python" ]
stackoverflow_0006715493_operator_keyword_python.txt
Q: Mocking functions with FlexMock in Python? I know how to mock methods in Python using flexmock, like flexmock(subprocess).should_receive('call').replace_with(my_func) How does one mock functions outside objects, or for example glob, which was imported via from glob import glob instead of import glob? I have foun...
Mocking functions with FlexMock in Python?
I know how to mock methods in Python using flexmock, like flexmock(subprocess).should_receive('call').replace_with(my_func) How does one mock functions outside objects, or for example glob, which was imported via from glob import glob instead of import glob? I have found mocking functions using python mock as a simil...
[ "Since you're importing the glob() function directly into the local namespace you have to get a handle on the current module.\nfrom flexmock import flexmock\nfrom glob import glob\nimport sys\n\nflexmock(sys.modules[__name__]).should_receive('glob')\n\nYou could also do an \"import glob as glob_module\" or somethin...
[ 8 ]
[]
[]
[ "mocking", "python" ]
stackoverflow_0006664499_mocking_python.txt
Q: In Memory Database Acessible From Multiple Python Scripts? I'm searching for a fast, in-memory database that allows one to define, initialize & manipulate a large matrix of floats (of approx. size 10,000,000 x 10). This in-memory database must meet the following requirements: (1) be open source, and easy to setup...
In Memory Database Acessible From Multiple Python Scripts?
I'm searching for a fast, in-memory database that allows one to define, initialize & manipulate a large matrix of floats (of approx. size 10,000,000 x 10). This in-memory database must meet the following requirements: (1) be open source, and easy to setup in a Linux environment (2) have an existing, easy to use python...
[ "A rather different approach based on a message queuing system. Probably the Ventilator and Sink roles will be folded into one for your purpose, and of course it will only work if the ventilator can decide what data need to be sent off to the workers, unless you supplement it with a shared memory solution.\nEDIT: ...
[ 2, 1 ]
[]
[]
[ "database", "python" ]
stackoverflow_0006701080_database_python.txt
Q: String formatting in Python In a django app I am writing,I have created a MyEntry and MyCategory ,and given unicode() implementations for them.To represent an entry ,I am using a string built from an entry's category name,starttime and entry's creation date. However ,when I try to list the entries,I am getting ['c...
String formatting in Python
In a django app I am writing,I have created a MyEntry and MyCategory ,and given unicode() implementations for them.To represent an entry ,I am using a string built from an entry's category name,starttime and entry's creation date. However ,when I try to list the entries,I am getting ['category1']13:02:542011-07-16 ['c...
[ "You want to replace \"%s%s%s\"%([str(x.name) for x in self.categories.all()],…) with \"%s-%s%s\" % (','.join(str(x.name) for x in self.categories.all()),…).\n" ]
[ 1 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0006716265_python_string_formatting.txt
Q: Perl to Python Regex How could one convert this to Python? The regex is used to match ipv4 addresses, but is there a better way to match this? if ($line =~ m{\s+id\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+data\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+Type Transit\s+(\d{1,2})}) { $id = "$1.$2.$3...
Perl to Python Regex
How could one convert this to Python? The regex is used to match ipv4 addresses, but is there a better way to match this? if ($line =~ m{\s+id\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+data\s+(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}),\s+Type Transit\s+(\d{1,2})}) { $id = "$1.$2.$3.$4"; $data = "$5.$6.$...
[ "match = re.search(r\"\\s+id\\s+(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}),\\s+data\\s+(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}),\\s+Type Transit\\s+(\\d{1,2})\", subject)\nif match:\n id = \".\".join(match.group(1,2,3,4))\n data = \".\".join(match.group(5,6,7,8))\nelse:\n # Match attempt ...
[ 5, 2, 1, 1 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0006716214_perl_python_regex.txt
Q: appengine: how can I check if a property from an entity exists in the datastore? I know it is not possible to query the datastore for missing values (see this question). What about from python code? Is it possible to check if the value from an entity property comes from the datastore or from the default value? Use...
appengine: how can I check if a property from an entity exists in the datastore?
I know it is not possible to query the datastore for missing values (see this question). What about from python code? Is it possible to check if the value from an entity property comes from the datastore or from the default value? Use case: Model Kind_X has 1000 entities. For the property Kind_X.my_property. 500 enti...
[ "You could iterate over all the entities of a given kind and check it programmatically with:\nentities = Model.all()\nfor entity in entities :\n if not entity.newproperty :\n print \"Hey, this entity is missing something\"\n\nIf the number of entities is big, you should use the mapreduce library to avoid timeou...
[ 0, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006598727_google_app_engine_google_cloud_datastore_python.txt
Q: how to import the new installed module whie an old same module exists everybody! the built-in pycurl module doesn't define Curl object conn = pycurl.Curl() Error message: "pycurl" module has no attribute Curl so I download the latest pycurl and install it,but it only works when I ran the code in interactive pyth...
how to import the new installed module whie an old same module exists
everybody! the built-in pycurl module doesn't define Curl object conn = pycurl.Curl() Error message: "pycurl" module has no attribute Curl so I download the latest pycurl and install it,but it only works when I ran the code in interactive python interpreter,and I got the same error when I ran it as a script file. It...
[ "It's a matter of when it is found. The basic import handler used in Python looks at the paths specified in sys.path in order to find a module, and after it has found something matching pycurl it will use it and not look further.\nSo, you need to either put your own copy of pycurl higher in the module search path, ...
[ 2 ]
[]
[]
[ "pycurl", "python", "python_import", "python_module" ]
stackoverflow_0006716069_pycurl_python_python_import_python_module.txt
Q: Text indexers (for python) with inbuilt support for doc, docx and pdf files I am currently on the lookout for a text indexer for my python program. I shortlisted Solr, a Lucene project and Whoosh, which is native to python. I searched a lot of documentation on support for doc, docx and pdf files, and Solr kept poi...
Text indexers (for python) with inbuilt support for doc, docx and pdf files
I am currently on the lookout for a text indexer for my python program. I shortlisted Solr, a Lucene project and Whoosh, which is native to python. I searched a lot of documentation on support for doc, docx and pdf files, and Solr kept pointing me to the Tika package, a version of which is integrated with Solr. The res...
[ "With Solr 1.4 or later you can have Word and PDF files uploaded and indexed on the fly; see: http://wiki.apache.org/solr/ExtractingRequestHandler\n\nSolr's ExtractingRequestHandler uses Tika to allow users to upload binary files to Solr and have Solr extract text from it and then index it.\n\n" ]
[ 3 ]
[]
[]
[ "full_text_search", "python", "solr", "solr_cell", "whoosh" ]
stackoverflow_0006716934_full_text_search_python_solr_solr_cell_whoosh.txt
Q: Python threads with urllib I use python to request a web service with many requests in the same time. To do so I create threads and use urllib (first version, I use python 2.6). When I start the threads, all goes well until one reach the ulllib.urlopen(). The second thread has to wait until the first one end befor...
Python threads with urllib
I use python to request a web service with many requests in the same time. To do so I create threads and use urllib (first version, I use python 2.6). When I start the threads, all goes well until one reach the ulllib.urlopen(). The second thread has to wait until the first one end before passing through the ulllib.url...
[ "This does not sounds intended behavior as two parallel urllib request should be possible. Are you sure your remote server can handle two paraller requests (e.g. it is not in debug mode with a single thread)?\nAny case: threading is not a preferred approach for parallel programming with Python. Either use processes...
[ 1 ]
[]
[]
[ "multithreading", "python", "python_2.6", "urllib" ]
stackoverflow_0006713837_multithreading_python_python_2.6_urllib.txt
Q: Understanding how Django Apps system works After some months of using Django, I feel the need to create the first my Django application. In this way I can really take the advantages of the Django's power. Someone can give me hints and directions for learning well about it? How Django's apps system works? And how c...
Understanding how Django Apps system works
After some months of using Django, I feel the need to create the first my Django application. In this way I can really take the advantages of the Django's power. Someone can give me hints and directions for learning well about it? How Django's apps system works? And how can I create my first reusable app? I think Djang...
[ "In addition to the official Django documentation and tutorial, which are excellent, I would recommend two books you should check out:\nAyman Hourieh's Django Web Development 1.0:\nhttp://www.amazon.com/gp/aw/d/1847196780/ref=redir_mdp_mobile/191-3941588-1909500\nAn awesome book that will take you step by step thro...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_apps", "python" ]
stackoverflow_0006715332_django_django_apps_python.txt
Q: Best way transform custom XML like syntax Using Python. So basically I have a XML like tag syntax but the tags don't have attributes. So <a> but not <a value='t'>. They close regularly with </a>. Here is my question. I have something that looks like this: <al> 1. test 2. test2 test with new line 3. test3 <al> ...
Best way transform custom XML like syntax
Using Python. So basically I have a XML like tag syntax but the tags don't have attributes. So <a> but not <a value='t'>. They close regularly with </a>. Here is my question. I have something that looks like this: <al> 1. test 2. test2 test with new line 3. test3 <al> 1. test 4 <al> 2. test 5 ...
[ "I'd recommend start with the following: \nfrom xml.dom.minidom import parse, parseString\n\nxml = parse(...)\nl = xml.getElementsByTagName('al')\n\nthen traverse all elements in l, examining their text subnodes (as well as <al> nodes recursively). \nYou may start playing with this right away in the Python console....
[ 2, 2, 1, 0 ]
[]
[]
[ "parsing", "python", "tags", "xml" ]
stackoverflow_0006711424_parsing_python_tags_xml.txt
Q: Correct Django models relationship Preface: I have two models (Product and UserProfile) and I would to implement a mine comments system. The comment is related to an object, Product or UserProfile. class Product(models.Model): name = models.CharField(max_length = 40) comments = models.ManyToMany(Comment) ...
Correct Django models relationship
Preface: I have two models (Product and UserProfile) and I would to implement a mine comments system. The comment is related to an object, Product or UserProfile. class Product(models.Model): name = models.CharField(max_length = 40) comments = models.ManyToMany(Comment) class UserProfile(models.Model): use...
[ "Your comment should have have a ForeignKey to the UserProfile or Product i.e. A single comment can only belong to a single product or user profile, but a user profile/product can have many different comments\ndef Comment(models.Model):\n profile = models.ForeignKey(UserProfile)\n product = models.ForeignKey(...
[ 3 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0006717135_django_django_models_django_orm_python.txt
Q: python: how to share an sqlite connection among threads with queues? I'm using Python 3.2.1 on Arch Linux x86_64. I'm trying to update an sqlite database in a threaded, timed loop with some code similar to the following: import sqlite3 from threading import Timer from queue import Queue class DBQueue(Queue): ...
python: how to share an sqlite connection among threads with queues?
I'm using Python 3.2.1 on Arch Linux x86_64. I'm trying to update an sqlite database in a threaded, timed loop with some code similar to the following: import sqlite3 from threading import Timer from queue import Queue class DBQueue(Queue): def give(self, item): self.task_done() self.join() ...
[ "You don't need the Queue - just use separate connections to the same database from the two threads. Keep in mind that you shouldn't expect much in terms of ordering when separate connections commit data into the DB. Treat it as if you had two different instances of your program accessing the DB simultaneously.\n\n...
[ 5 ]
[]
[]
[ "multithreading", "python", "queue", "sqlite", "timer" ]
stackoverflow_0006717221_multithreading_python_queue_sqlite_timer.txt
Q: Implementing a timer to stop abuse in a socket IRC bot? Code: while True: data = irc.recv(4096) if data.find('PING') != -1: irc.send('PONG '+ data.split() [1] +' \r\n') if data.find('!latest') != -1: irc.send('PRIVMSG #PwnMyI :\x02Latest Article:\x02 %s, \x02written by\x02 %s \r\n' % (a...
Implementing a timer to stop abuse in a socket IRC bot?
Code: while True: data = irc.recv(4096) if data.find('PING') != -1: irc.send('PONG '+ data.split() [1] +' \r\n') if data.find('!latest') != -1: irc.send('PRIVMSG #PwnMyI :\x02Latest Article:\x02 %s, \x02written by\x02 %s \r\n' % (art_name, art_auth)) irc.send('PRIVMSG #PwnMyI :\x02De...
[ "Create a last sent timestamp variable. When you post, check to see if the last sent timestamp is within a certain time period. If it is, don't post. If it isn't, post and update it with the current time.\n" ]
[ 0 ]
[]
[]
[ "bots", "irc", "python", "timer" ]
stackoverflow_0006717526_bots_irc_python_timer.txt
Q: Conditionally show and hide a form field and set the field value I have a form in my Django that looks something like this: class PersonnelForm(forms.Form): """ Form for creating a new personnel. """ username = forms.RegexField( required=True, max_length=30, label=_("Name") ) is_man...
Conditionally show and hide a form field and set the field value
I have a form in my Django that looks something like this: class PersonnelForm(forms.Form): """ Form for creating a new personnel. """ username = forms.RegexField( required=True, max_length=30, label=_("Name") ) is_manager = forms.BooleanField( required=True, label=_("Is Manager"...
[ "You could use the form's __init__ method to hide (or delete) the field, i.e.\nclass PersonnelForm(forms.Form):\n \"\"\"\n Form for creating a new personnel.\n \"\"\"\n username = forms.RegexField(\n required=True, max_length=30, label=_(\"Name\")\n )\n is_manager = forms.BooleanField(\n ...
[ 14, 1 ]
[]
[]
[ "django", "django_forms", "form_fields", "python" ]
stackoverflow_0006717249_django_django_forms_form_fields_python.txt
Q: Python: Error in online console python I am using a online console of python: http://shell.appspot.com/ I am trying to write this code: class tree: def __init__(self, charge, left=None, right=None): self.charge = charge self.left = left self.right = right When I wrote the first line class tree: I push ent...
Python: Error in online console python
I am using a online console of python: http://shell.appspot.com/ I am trying to write this code: class tree: def __init__(self, charge, left=None, right=None): self.charge = charge self.left = left self.right = right When I wrote the first line class tree: I push enter and I get this error from the console Tra...
[ "Do not use ENTER.\n As indicated at the bottom of the online shell page use:\n\nShift-Enter for newline\n\n", "You have to enter the entire class into the text box in that application. It is different from the usual Python shell, I know. :)\nPaste in your code; it will work.\n", "You need to enter all the con...
[ 4, 0, 0, 0 ]
[]
[]
[ "console_application", "python" ]
stackoverflow_0006718581_console_application_python.txt
Q: Python: Question about encoding I'm trying to understand the encoding stuff in python and I think I nearly managed it to understand. So here is some code which I will explain and I would like you to verify my thoughts :) text = line.decode( encoding ) print "type(text) = %s" % type(text) iso_8859_1 = text.encode('...
Python: Question about encoding
I'm trying to understand the encoding stuff in python and I think I nearly managed it to understand. So here is some code which I will explain and I would like you to verify my thoughts :) text = line.decode( encoding ) print "type(text) = %s" % type(text) iso_8859_1 = text.encode('latin1') print "type(iso_8859_1) = %s...
[ "First, utf8 != unicode.\nstr is basically a sequence of bytes and encoding is method of interpreting those sequence, and unicode is, well - unicode.\nJoel had great post on this subject http://www.joelonsoftware.com/articles/Unicode.html\n" ]
[ 1 ]
[]
[]
[ "encoding", "mysql", "python" ]
stackoverflow_0006718560_encoding_mysql_python.txt
Q: PyGTK Hide Cursor The question is simple how can I hide the cursor on an active window using PyGTK??? Here's a basic app I made to learn this... #!/usr/bin/env python import gtk class app: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("TestApp") window.set_default_s...
PyGTK Hide Cursor
The question is simple how can I hide the cursor on an active window using PyGTK??? Here's a basic app I made to learn this... #!/usr/bin/env python import gtk class app: def __init__(self): window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_title("TestApp") window.set_default_size(400,200) pixmap...
[ "As stated in the PyGTK FAQ, you should set the cursor on the realize signal. If you don't wait for the realize signal, the gtk.gdk.window hasn't been created yet, so you can't change the cursor.\nSo, you can do something like:\n#!/usr/bin/env python\n\nimport gtk\n\nclass app:\n\n def __init__(self):\n window ...
[ 5 ]
[]
[]
[ "cursor", "hide", "linux", "pygtk", "python" ]
stackoverflow_0006718586_cursor_hide_linux_pygtk_python.txt
Q: Non-blocking socket in Python? Is it me, or can I not find a good tutorial on non-blocking sockets in python? I'm not sure how to exactly work the .recv and the .send in it. According to the python docs, (my understanding of it, at least) the recv'ed or send'ed data might be only partial data. So does that mean I ...
Non-blocking socket in Python?
Is it me, or can I not find a good tutorial on non-blocking sockets in python? I'm not sure how to exactly work the .recv and the .send in it. According to the python docs, (my understanding of it, at least) the recv'ed or send'ed data might be only partial data. So does that mean I have to somehow concatenate the data...
[ "It doesn't really matter if your socket is in non-blocking mode or not, recv/send work pretty much the same; the only difference is that non-blocking socket throws 'Resource temporarily unavailable' error instead of waiting for data/socket.\nrecv method returns numbers of bytes received, which is told to be less o...
[ 10, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0006715944_python_sockets.txt
Q: Python & RabbitMQ -- Communicate Between Parent & Children? I'd like to write a python script (call it parent) that does the following: (1) defines a multi-dimensional numpy array (2) forks 10 different python scripts (call them children). Each of them must be able to read the contents of the numpy array from (1) ...
Python & RabbitMQ -- Communicate Between Parent & Children?
I'd like to write a python script (call it parent) that does the following: (1) defines a multi-dimensional numpy array (2) forks 10 different python scripts (call them children). Each of them must be able to read the contents of the numpy array from (1) at any single point in time (as long as they are alive). (3) each...
[ "'Global Arrays' might be what you need.\nCheck it out, second talk: http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2011-friday-afternoon-lightning-talks-4902699\n" ]
[ 0 ]
[]
[]
[ "python", "rabbitmq" ]
stackoverflow_0006711084_python_rabbitmq.txt
Q: SQLAlchemy (ORM, declarative): How to build query from key/values in a dict? Using the SQLAlchemy ORM (declarative form), how do you programatically create a query from a set of conditions in a dictionary? I wish to search for those records in a users table that match some criteria previously collected in a dict. ...
SQLAlchemy (ORM, declarative): How to build query from key/values in a dict?
Using the SQLAlchemy ORM (declarative form), how do you programatically create a query from a set of conditions in a dictionary? I wish to search for those records in a users table that match some criteria previously collected in a dict. I can not know in advance which fields will be used, and must be able to handle th...
[ "Try the following, references here: Query, filter_by \nsession.query(User).filter_by(**q1_dict)\n\n", "Some example code:\n100 COND = and_()\n.....\n216 if hidxs_sg:$\n217 clause = [AM.hidx == hidx for hidx in hidxs_sg]$\n218 COND.append(or_(*clause))$\n....\n300 q...
[ 1, 0 ]
[]
[]
[ "declarative", "python", "sqlalchemy" ]
stackoverflow_0006718480_declarative_python_sqlalchemy.txt
Q: Django and Django CMS Error I've just done a fresh install of Django and Django-CMS from the ground up (including a brand new virtualenv and python build). I'm getting this bizzarre error.. google has been no help. Ideas? TemplateSyntaxError at / Caught AttributeError while rendering: 'str' object has no attribute...
Django and Django CMS Error
I've just done a fresh install of Django and Django-CMS from the ground up (including a brand new virtualenv and python build). I'm getting this bizzarre error.. google has been no help. Ideas? TemplateSyntaxError at / Caught AttributeError while rendering: 'str' object has no attribute 'regex' In template /Users/bdun...
[ "Just had this error. In my case it was caused by having tripple quoted string (comment) in urls.py patterns.\nActually it was not interpreted as a comment and was passed to function!\n" ]
[ 16 ]
[]
[]
[ "django", "django_cms", "python" ]
stackoverflow_0006645661_django_django_cms_python.txt
Q: Java/Python communication via message broker What is a good solution for communication via message broker that supports both (C)Python and Java/JMS applications? My particular requirements are: open source solution Available on Linux-based systems No rendezvous between sender and receiver required (i.e. uses a m...
Java/Python communication via message broker
What is a good solution for communication via message broker that supports both (C)Python and Java/JMS applications? My particular requirements are: open source solution Available on Linux-based systems No rendezvous between sender and receiver required (i.e. uses a message broker) Multiple producers and consumers su...
[ "JMS is a specification not implementation . RabbitMQ is a really option .\nI have also happily used HornetQ http://www.jboss.org/hornetq from Jboss as with every thing it is more aligned with every thing Java EE but RabbitMQ would be choice espcially if you are using Spring as well\n", "\nI have had a surprisin...
[ 5, 4, 1, 1 ]
[]
[]
[ "java", "messagebroker", "middleware", "python", "unit_of_work" ]
stackoverflow_0006551718_java_messagebroker_middleware_python_unit_of_work.txt
Q: Changing function module I've got 2 modules A and B. module A has nothing inside and module B has a function 'f' I want to assign function 'f' to module A, but I want override this functions globals, because I want this function to use A module variables. But there I've got some problems. with this simple code: pr...
Changing function module
I've got 2 modules A and B. module A has nothing inside and module B has a function 'f' I want to assign function 'f' to module A, but I want override this functions globals, because I want this function to use A module variables. But there I've got some problems. with this simple code: print A print B print '---' from...
[ "You might try using functools.update_wrapper:\nA.f = functools.update_wrapper(wrapper=B.f, wrapped=A.f)\n\nThis will modify B.f, though (making it take on aspects of A.f, __module__, __name__, and __doc__, refer to functools module source code). As you really haven't said what you are trying to accomplish (not how...
[ 1 ]
[]
[]
[ "class", "module", "overriding", "python", "runtime" ]
stackoverflow_0006719233_class_module_overriding_python_runtime.txt
Q: Passing bash variables to a script? What's the best way to pass bash variables to a python script. I'd like to do something like the following: $cat test.sh #!/bin/bash foo="hi" python -c 'import test; test.printfoo($foo)' $cat test.py #!/bin/python def printfoo(str): print str When I try running the bash...
Passing bash variables to a script?
What's the best way to pass bash variables to a python script. I'd like to do something like the following: $cat test.sh #!/bin/bash foo="hi" python -c 'import test; test.printfoo($foo)' $cat test.py #!/bin/python def printfoo(str): print str When I try running the bash script, I get a syntax error: File "<s...
[ "You can use os.getenv to access environment variables from Python:\nimport os\nimport test\ntest.printfoo(os.getenv('foo'))\n\nHowever, in order for environment variables to be passed from Bash to any processes it creates, you need to export them with the export builtin:\nfoo=\"hi\"\nexport foo\n# Alternatively, t...
[ 14, 9, 3, 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0006719549_bash_python.txt
Q: way to add systrace handler to a python thread after it started from another thread? I am putting together a small debugger for python so I can basically attach in the middle of the program and pause the code or break when some variable changes or step one line, etc... basically pdb but with attaching (so more lik...
way to add systrace handler to a python thread after it started from another thread?
I am putting together a small debugger for python so I can basically attach in the middle of the program and pause the code or break when some variable changes or step one line, etc... basically pdb but with attaching (so more like gdb assuming pystack isn't working). For a single thread, one can do sys.settrace(), for...
[ "ok, it doesn't seem quite possible to do this.\nThe closest I got was hearing about thread2 (killable threads), which calls PyThreadState_SetAsyncExc, which raises an exception, and the constructor is called in the other thread, which is rather useless.\nMy solution is going to not use sys.settrace at all, but ins...
[ 4 ]
[]
[]
[ "debugging", "multithreading", "python" ]
stackoverflow_0006631443_debugging_multithreading_python.txt
Q: Instance of class `object` I wish to make an instance of built-in class object, and use it as container for some variables (like struct in C++): Python 3.2 (r32:88445, Mar 25 2011, 19:56:22) >>> a=object() >>> a.f=2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' ...
Instance of class `object`
I wish to make an instance of built-in class object, and use it as container for some variables (like struct in C++): Python 3.2 (r32:88445, Mar 25 2011, 19:56:22) >>> a=object() >>> a.f=2 Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'object' object has no attribute 'f' Is ...
[ "No, you have to subclass object to get a mutable object. Make sure to do so explicitly in python 2.x:\nclass Struct(object):\n pass\n\nProbably using a built-in container is better though, if only because it's clear from syntax exactly what it is. \nThe reason instances of object can't be assigned to is that th...
[ 4, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006719496_python.txt
Q: Google Maps and Google App Engine I have a Google App Engine application that launches a Web Page with Google Map. I would now like to add functionality to let user sketch on map (which I can probably use JS API for) and then create a fusion table row using python code backend. Is this possible? If so how do I tra...
Google Maps and Google App Engine
I have a Google App Engine application that launches a Web Page with Google Map. I would now like to add functionality to let user sketch on map (which I can probably use JS API for) and then create a fusion table row using python code backend. Is this possible? If so how do I transfer the sketch coords from Javascript...
[ "Here is a simple guideline:\n\nJavascript and overlays to draw stuff on the maps\nAjax to post json sketch data from the client to Google App Engine \nA well shaped rest interface on the server using appengine-rest-server \nFusion-Tables python library to access Google Fusion Tables from GAE\n\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "google_maps", "python" ]
stackoverflow_0006707975_google_app_engine_google_maps_python.txt
Q: Best-suited text indexer for handling 10000s of (formatted) documents in python I want to add a feature to search documents stored in a directory. The back end is developed in Python to additionally manipulate the search results. The documents are stored in a dedicated web server. The established technologies (Luc...
Best-suited text indexer for handling 10000s of (formatted) documents in python
I want to add a feature to search documents stored in a directory. The back end is developed in Python to additionally manipulate the search results. The documents are stored in a dedicated web server. The established technologies (Lucene, Xapian, Whoosh) have mature python bindings. My colleagues have set up Apache, L...
[ "Sphinx is pretty easy to interact with because it works via a MySQL storage engine, which is an interface most programmers have touched at one point or another. Doubly so if you already have data in MySQL because then you can munge the data together trivially. Django-sphinx is an example of a fairly mature and eas...
[ 1, 1 ]
[]
[]
[ "full_text_search", "python" ]
stackoverflow_0006716125_full_text_search_python.txt
Q: Setting exit code in Python when an exception is raised $ cat e.py raise Exception $ python e.py Traceback (most recent call last): File "e.py", line 1, in <module> raise Exception Exception $ echo $? 1 I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the be...
Setting exit code in Python when an exception is raised
$ cat e.py raise Exception $ python e.py Traceback (most recent call last): File "e.py", line 1, in <module> raise Exception Exception $ echo $? 1 I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the best way to do this?
[ "Take a look at the traceback module. You could do the following:\nimport sys, traceback\n\ntry:\n raise Exception()\nexcept:\n traceback.print_exc()\n sys.exit(3)\n\nThis will write traceback to standard error and exit with code 3.\n" ]
[ 54 ]
[]
[]
[ "exception", "exit_code", "python" ]
stackoverflow_0006720119_exception_exit_code_python.txt
Q: pyinterval with trvial floating point example doesn't seem to be working There are probably hundreds of questions on here about floating point rounding errors, and the solution is supposed to be interval arithmetic which helps keep track of them. As I'd like to experiment with this, I tried installing pyinterval. ...
pyinterval with trvial floating point example doesn't seem to be working
There are probably hundreds of questions on here about floating point rounding errors, and the solution is supposed to be interval arithmetic which helps keep track of them. As I'd like to experiment with this, I tried installing pyinterval. Unfortunately, it doesn't seem to be working. For this trivial case of floatin...
[ "It looks like the conversion of strings to floats is not respecting the rounding, but if I do it manually by entering 1.001 as 1001/1000, I get the sort of thing I am expecting:\n>>> (interval[1001]/1000)-1\ninterval([0.0009999999999996678, 0.001000000000000112])\n\n" ]
[ 1 ]
[]
[]
[ "floating_accuracy", "floating_point", "intervals", "python" ]
stackoverflow_0006719452_floating_accuracy_floating_point_intervals_python.txt
Q: Python string conversion (localization) question source = '\xe3\xc7\x9f' destination = u'\u0645\u0627\u06ba' How do I get from the source, to the destination? (The source and the destination are both the same 3 characters, in the same order, just represented differently.) Technically, the source is in Urdu and th...
Python string conversion (localization) question
source = '\xe3\xc7\x9f' destination = u'\u0645\u0627\u06ba' How do I get from the source, to the destination? (The source and the destination are both the same 3 characters, in the same order, just represented differently.) Technically, the source is in Urdu and the destination is the Unicode code points for the same ...
[ "In [129]: source = '\\xe3\\xc7\\x9f'\nIn [130]: source.decode('cp1256')\nOut[130]: u'\\u0645\\u0627\\u06ba'\n\nIn [131]: destination\nOut[131]: u'\\u0645\\u0627\\u06ba'\n\n\nPS. The question \"What codec transforms this str object into that unicode object?\" comes up from time to time on SO. Here's a little script...
[ 6 ]
[]
[]
[ "localization", "python", "unicode" ]
stackoverflow_0006720208_localization_python_unicode.txt
Q: What's the difference between a twistd plugin and a twistd service? Apparently you can create services that are run with Twisted's twistd in two different ways. On the one hand you can create services using the Twisted Application Infrastructure and in the other you can create a service using the Twisted Plugin Sy...
What's the difference between a twistd plugin and a twistd service?
Apparently you can create services that are run with Twisted's twistd in two different ways. On the one hand you can create services using the Twisted Application Infrastructure and in the other you can create a service using the Twisted Plugin System. It seems like besides some differences in how you start the the app...
[ "Looks like I found the answer:\nhttp://twistedmatrix.com/pipermail/twisted-python/2009-September/020346.html\n\n\nWhich is the recommended or preferred way to deploy an app that will\n leverage twistd: designing the app as a twistd plugin or creating a\n Service and using a .tac file?\n\nA plugin is nicer in...
[ 7 ]
[]
[]
[ "python", "twistd", "twisted" ]
stackoverflow_0006720021_python_twistd_twisted.txt
Q: Debugging python using Textmate? I'd like to use TextMate for debugging python scripts. I'm looking for suggestions on the best way to accomplish this. I found these "solutions" -- is there a better approach? http://www.libertypages.com/clarktech/?p=192 Using Python 3.1 with TextMate I'd really like to find so...
Debugging python using Textmate?
I'd like to use TextMate for debugging python scripts. I'm looking for suggestions on the best way to accomplish this. I found these "solutions" -- is there a better approach? http://www.libertypages.com/clarktech/?p=192 Using Python 3.1 with TextMate I'd really like to find something as usable as the Eclipse PyDev...
[ "TextMate is not an IDE, it's just an awsome editor.\nTherefore you'll find that these features might not be available, and that you should just debug from the provided command line.\n", "You really should consider using Eclipse and PyDev.\nI'd prefer TextMate over Eclipse too but there's no good debugger in Text...
[ 0, 0 ]
[]
[]
[ "debugging", "python", "textmate", "textmatebundles" ]
stackoverflow_0003094576_debugging_python_textmate_textmatebundles.txt
Q: How to show user a form to set username when using django with django-social-auth I've been using django-social-auth (https://github.com/omab/django-social-auth), with some success - logging in from Twitter and Facebook have been set up without difficulty. However, when I log in from some OpenID providers, I am fa...
How to show user a form to set username when using django with django-social-auth
I've been using django-social-auth (https://github.com/omab/django-social-auth), with some success - logging in from Twitter and Facebook have been set up without difficulty. However, when I log in from some OpenID providers, I am faced with an empty variable for the username, and the social-auth app allows this (despi...
[ "1 is probably the way to go. You can override the get_user_details method of the Backend class for the social providers you're having trouble with and pull the username from there.\nIt'd look something like this, for example for Facebook:\nfrom social_auth.backends.facebook import FacebookBackend\nclass CustomFac...
[ 2 ]
[]
[]
[ "django", "django_socialauth", "python", "socialauth" ]
stackoverflow_0006714723_django_django_socialauth_python_socialauth.txt
Q: Python runtime: recompiling and reusing C library I am developing a tool for some numerical analysis of user-defined functions. The idea is to make a convenient UI in Python, where user can enter C function, then press a button - and receive some output data. Computations can take minutes or hours, so Numpy-only ...
Python runtime: recompiling and reusing C library
I am developing a tool for some numerical analysis of user-defined functions. The idea is to make a convenient UI in Python, where user can enter C function, then press a button - and receive some output data. Computations can take minutes or hours, so Numpy-only performance is not acceptable. I have tried the followi...
[ "Python has really good multiprocessing support (and really not very good threading support), so you could spawn a new python process for each expression to be evaluated, compile and load the dll in the new process, then have it communicate the results back to the parent process. When the spawned process exits, eve...
[ 4, 2, 1 ]
[]
[]
[ "c", "cython", "jit", "python", "scientific_computing" ]
stackoverflow_0006717111_c_cython_jit_python_scientific_computing.txt
Q: Django ManyToMany doubt I have this models: class Comment(models.Model): text = models.TextField(max_length = 300) author = models.ForeignKey(User) timestamp = models.DateTimeField(auto_now_add = True) class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) comments = mo...
Django ManyToMany doubt
I have this models: class Comment(models.Model): text = models.TextField(max_length = 300) author = models.ForeignKey(User) timestamp = models.DateTimeField(auto_now_add = True) class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) comments = models.ManyToManyField(Comment)...
[ "Your first statement is correct, for a ManyToManyField \"an object A has many objects B, so an object B has many objects A\"\nNote that when you define\nclass Comment(models.Model):\n text = models.TextField(max_length = 300)\n author = models.ForeignKey(User)\n timestamp = models.DateTimeField(auto_now_a...
[ 1 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0006720624_django_django_orm_python.txt
Q: Django and MongoDB - good libraries to use? There have been several MongoDB and Django posts - one of the most recent I found was from about 12 months ago. I was wondering what the favourite library/integration method was at the present time and whether anyone had some good pointers about where to look for good id...
Django and MongoDB - good libraries to use?
There have been several MongoDB and Django posts - one of the most recent I found was from about 12 months ago. I was wondering what the favourite library/integration method was at the present time and whether anyone had some good pointers about where to look for good ideas? Thanks, J
[ "I always run in to this while exploring options Django-mongokit and mongokit on top of pymongo\nDjango-Mongokit\n" ]
[ 1 ]
[]
[]
[ "django", "mongodb", "python" ]
stackoverflow_0006719484_django_mongodb_python.txt
Q: If I'm dealing with dictionaries everywhere, should I make them "classes"? Right now, I have many python files. Each has many functions. I'm passing hash maps around everywhere. Basic dictionaries, with a word as a key and a score as the value. { 'dog': 33, 'cat': 294 } I'm also doing some more complicated strcut...
If I'm dealing with dictionaries everywhere, should I make them "classes"?
Right now, I have many python files. Each has many functions. I'm passing hash maps around everywhere. Basic dictionaries, with a word as a key and a score as the value. { 'dog': 33, 'cat': 294 } I'm also doing some more complicated strcutures, like: { 'dog': [ 33, 66, 11, 88 ], 'cat': [11, 66, 22] } Do I need to tur...
[ "Having maintained a large codebase for many years that favored raw dicts over objects, my opinion is that if this codebase is going to be maintained by either A) another person or B) several people, you should start migrating toward real classes and OOP. Primarily, the fact that you can easily see what attributes...
[ 4, 3, 3, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0006720440_oop_python.txt
Q: Comparing files in directory to each other with no repeated comparisons What I want to do is create a list of files to compare in a directory of N files. The end goal is to compare images to find duplicates regardless of the format. Given the files 1.jpg 2.jpg 3.jpg. Using this import sys,os,time def main(argv):...
Comparing files in directory to each other with no repeated comparisons
What I want to do is create a list of files to compare in a directory of N files. The end goal is to compare images to find duplicates regardless of the format. Given the files 1.jpg 2.jpg 3.jpg. Using this import sys,os,time def main(argv): list1 = os.listdir(argv[0]) list2 = os.listdir(argv[0]) file_compar...
[ "You need itertools.combinations. This code prints exactly what you need:\nimport os, itertools\n\nfiles = os.listdir(\"/path/to/files\")\nfor file1, file2 in itertools.combinations(files, 2):\n print file1, file2\n\nAnd some theory behind it: http://en.wikipedia.org/wiki/Combination\n", "there is always itertoo...
[ 6, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006720784_python.txt
Q: Get all __slots__ of derived class I need to initialise all slots of an instance with None. How do I get all slots of a derived class? Example (which does not work): class A(object): __slots__ = "a" def __init__(self): # this does not work for inherited classes for slot in type(self).__slo...
Get all __slots__ of derived class
I need to initialise all slots of an instance with None. How do I get all slots of a derived class? Example (which does not work): class A(object): __slots__ = "a" def __init__(self): # this does not work for inherited classes for slot in type(self).__slots__: setattr(self, slot, No...
[ "First of all, it's\nclass A(object):\n __slots__ = ('a',)\nclass B(A):\n __slots__ = ('b',)\n\nMaking a list that contains all elements contained by __slots__ of B or any of its parent classes would be:\nfrom itertools import chain\nslots = chain.from_iterable(getattr(cls, '__slots__', []) for cls in B.__mr...
[ 16, 11 ]
[]
[]
[ "inheritance", "python", "slots" ]
stackoverflow_0006720747_inheritance_python_slots.txt
Q: py2app built app displays `ERROR: pygame.macosx import FAILED` on other machines Trying to build an app on the Mac using py2app. Got everything working fine on my machine, but when moving the app to another, it crashes and the console displays this error. ERROR: pygame.macosx import FAILED Anybody have a solution...
py2app built app displays `ERROR: pygame.macosx import FAILED` on other machines
Trying to build an app on the Mac using py2app. Got everything working fine on my machine, but when moving the app to another, it crashes and the console displays this error. ERROR: pygame.macosx import FAILED Anybody have a solution to this?
[ "Found the problem and solution after many hours. Turns out other people have experienced similar problems and their articles were quite helpful:\nhttp://b.atcg.us/blog/2010/04/13/py2app-hell-the-first.html\nhttp://www.vijayp.ca/blog/?p=62\nIn case someone else runs into the issue, this particular problem was caus...
[ 12, 1 ]
[]
[]
[ "macos", "py2app", "pygame", "python" ]
stackoverflow_0005201133_macos_py2app_pygame_python.txt
Q: py2app dependency problem i will create a OS X Package using py2app. It is a Game using the FIFE-Engine. If i launch the resulting .app Bundle on another Mac i get this error Message: Failed to load FIFE: dlopen([...]/Contents/Resources/fife/engine/python/fife/_fife.so, 2): Library not loaded: /opt/local/lib/libS...
py2app dependency problem
i will create a OS X Package using py2app. It is a Game using the FIFE-Engine. If i launch the resulting .app Bundle on another Mac i get this error Message: Failed to load FIFE: dlopen([...]/Contents/Resources/fife/engine/python/fife/_fife.so, 2): Library not loaded: /opt/local/lib/libSDL_ttf-2.0.0.dylib Referenced f...
[ "I'm not sure if this will fix your problem, but it sounds related to the problem being discussed here: py2app built app displays `ERROR: pygame.macosx import FAILED` on other machines\nIn particular, notice the one-line dynlib bug fix to boot_app.py (part of the py2app source). \n" ]
[ 1 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0006087379_macos_py2app_python.txt
Q: Transform a flat list to nested List Using Python I want the following: [1, 2, 2, 1, 2, 3, 2, 3] To be transformed into: [1, 2, 2, [1, 2, 3], 2, 3] Rules: Go through each item in the list. If we hit a 2 followed by a 1 created a list and include that 1 in that list until we hit a 3, include that 3, then close th...
Transform a flat list to nested List
Using Python I want the following: [1, 2, 2, 1, 2, 3, 2, 3] To be transformed into: [1, 2, 2, [1, 2, 3], 2, 3] Rules: Go through each item in the list. If we hit a 2 followed by a 1 created a list and include that 1 in that list until we hit a 3, include that 3, then close the list and continue. It's like if 1 was 3 ...
[ "Still keeping in mind that @Walter is correct in his comments to your question, this is a silly implementation of what you asked for, inspired by the final bit of your question, in which you suggest that 1 and 3 could just be replaced with [1 and 3].\n>>> import re\n>>> s = repr([1, 2, 2, 1, 2, 3, 2, 3])\n>>> s = ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0006720574_python_recursion.txt
Q: Python XMl Parser with BeautifulSoup. How do I remove tags? For a project I decided to make an app that helps people find friends on Twitter. I have been able to grab usernames from xml pages. So for example with my current code I can get <uri>http://twitter.com/username</uri> from an XML page, but I want to remo...
Python XMl Parser with BeautifulSoup. How do I remove tags?
For a project I decided to make an app that helps people find friends on Twitter. I have been able to grab usernames from xml pages. So for example with my current code I can get <uri>http://twitter.com/username</uri> from an XML page, but I want to remove the <uri> and </uri> tags using Beautiful Soup. Here is my...
[ "Don't use BeautifulSoup to parse twitter, use their API (also don't use BeautifulSoup, use lxml). To answer your question:\nimport urllib\nfrom BeautifulSoup import BeautifulSoup\n\nresp = urllib.urlopen(\"http://search.twitter.com/search.atom?q=travel\")\nsoup = BeautifulSoup(resp.read())\nfor uri in soup.findAll...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0006721160_beautifulsoup_python.txt
Q: How to use python to read an encrypted folder I want to design an application that reads some a folder of text files and shows the user its contents. Three problems arise: I need the folder containing the text files to be encrypted which I don't know how to do, two, I need a way to read the encrypted files without...
How to use python to read an encrypted folder
I want to design an application that reads some a folder of text files and shows the user its contents. Three problems arise: I need the folder containing the text files to be encrypted which I don't know how to do, two, I need a way to read the encrypted files without revealing the key in the python code, so I guess C...
[ "I think the best thing to do would be to encrypt the individual text files using GPG, one of the strongest encryption systems available(and for free!) You can get several python libraries to do this, and I recommend python-gnupg. Also, you can probably just reference the file where the key is located and distribut...
[ 1 ]
[]
[]
[ "c", "directory", "encryption", "python" ]
stackoverflow_0006721138_c_directory_encryption_python.txt
Q: using swig to bind google protocol buffers I'm writing python program that needs to process a lot of small but complex protobuf-encoded messages. I tried to use the Python implementation of protocol buffers, which is written in pure python, but its performance is really terrible. So I'm looking into a solution tha...
using swig to bind google protocol buffers
I'm writing python program that needs to process a lot of small but complex protobuf-encoded messages. I tried to use the Python implementation of protocol buffers, which is written in pure python, but its performance is really terrible. So I'm looking into a solution that apparently some folks got to work - use protoc...
[ "New version of Protobuf supports using the fast C++ implementation of Protobuf with Python code. Set the environment variable PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp.\n", "Here is the correct link to the Greplin fast-python-pb solution which I ended up using.\nIt's very easy to use (at least in Linux), and pe...
[ 2, 1, 0 ]
[]
[]
[ "optimization", "performance", "protocol_buffers", "python", "swig" ]
stackoverflow_0006670771_optimization_performance_protocol_buffers_python_swig.txt
Q: Django seems to be caching? I'm running Django 1.2.1 for my personal website with a blog. It's all fine and dandy, but I've found that all the browsers I've tried (Firefox, Chromium, Opera) are caching webpages, which of course is a problem for other users viewing my blog (being that it won't load new posts up unl...
Django seems to be caching?
I'm running Django 1.2.1 for my personal website with a blog. It's all fine and dandy, but I've found that all the browsers I've tried (Firefox, Chromium, Opera) are caching webpages, which of course is a problem for other users viewing my blog (being that it won't load new posts up unless they empty their cache or for...
[ "The problem was that it really was browser-based caching, as I was told by a member on the Django-users mailing list. The reason I didn't see this problem in PHP is that it was sending cache suppression headers.\nThe solution was to add the @never_cache decorator to the relevant views.\n", "Here is the documenta...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006678912_django_python.txt
Q: Get GTK+ theme colors with python and GObject introspection With introduction of GObject introspection the way to access theme colors through widget.get_style() method is gone. I am interested on how to get theme colors when GTK+ is used through GOBject introspection. The solution should preferably work with both ...
Get GTK+ theme colors with python and GObject introspection
With introduction of GObject introspection the way to access theme colors through widget.get_style() method is gone. I am interested on how to get theme colors when GTK+ is used through GOBject introspection. The solution should preferably work with both versions (2 and 3) but a solution for each of these is acceptable...
[ "I'm not sure how to get it from gtk+-2.0, unless your using a pure gtk+-2.0 environment, in which case I think the old GtkStyle methods work. for example, assuming your not running a Gtk-3.0 environment like gnome-shell\nimport gi\n# make sure you use gtk+-2.0\ngi.require_version('Gtk', '2.0')\nfrom gi.repository...
[ 6 ]
[]
[]
[ "colors", "gobject", "gtk", "introspection", "python" ]
stackoverflow_0006500525_colors_gobject_gtk_introspection_python.txt
Q: Checkbuttons with Multiple Tkinter Windows Specs: Python2.7.1 Tkinter (Tk version 8.5) Windows7 IDLE 2.7.1 I'm coding a program that 'spawns' two windows, withdraws both, destroys one and then deiconifies the other (which then enters a mainloop). This arrangement is interfering with a Checkbutton on the remaining ...
Checkbuttons with Multiple Tkinter Windows
Specs: Python2.7.1 Tkinter (Tk version 8.5) Windows7 IDLE 2.7.1 I'm coding a program that 'spawns' two windows, withdraws both, destroys one and then deiconifies the other (which then enters a mainloop). This arrangement is interfering with a Checkbutton on the remaining window. eg: temp = Tk() temp.withdraw() root = ...
[ "Tkinter isn't designed to have two root windows. I'm amazed your code works at all. This has nothing to do with multi-threading -- Tkinter is single threaded and you don't appear to be creating any new threads (though if you are, that might contribute to the problem)/\nYou need to create a single root window with ...
[ 2 ]
[]
[]
[ "checkbox", "multithreading", "python", "tkinter", "windows_7" ]
stackoverflow_0006721469_checkbox_multithreading_python_tkinter_windows_7.txt
Q: Finding adjacent neighbors on a hexagonal grid EDIT: Wrapped the example map in a code block so the formatting is correct. Ok, I'm trying to write an extremely simple A* algorithm over a hexagonal grid. I understand, and can do the A* portion. In fact, my A* works for square grids. What I can't wrap my brain aroun...
Finding adjacent neighbors on a hexagonal grid
EDIT: Wrapped the example map in a code block so the formatting is correct. Ok, I'm trying to write an extremely simple A* algorithm over a hexagonal grid. I understand, and can do the A* portion. In fact, my A* works for square grids. What I can't wrap my brain around is finding neighbors with hexagons. Here's the lay...
[ "It depends on how you define the coordinates of your hex tiles.\nLet's see.\n , , , ,\n / \\ / \\ / \\ / \\\n| A1| A2| A3| A4|\n \\ / \\ / \\ / \\ /\n | B1| B2| B3|\n / \\ / \\ / \\ / \\\n| C1| C2| C3| C4|\n \\ / \\ / \\ / \\ /\n ' ' ' '\n\nIn this case, neighbor definition is different for even and...
[ 9, 2 ]
[]
[]
[ "grid", "hexagonal_tiles", "python", "tiles" ]
stackoverflow_0006661169_grid_hexagonal_tiles_python_tiles.txt
Q: How do I properly subclass a "dict"? class MyDict(dict): def __init__(self, *args): #fill in here How do I write the constructor so that it sets the key 'name' to 'james'. d = MyDict() print d['name'] ....this should print out "james" A: In (C)Python 2.5.2: >>> class MyDict(dict): ... def __init__...
How do I properly subclass a "dict"?
class MyDict(dict): def __init__(self, *args): #fill in here How do I write the constructor so that it sets the key 'name' to 'james'. d = MyDict() print d['name'] ....this should print out "james"
[ "In (C)Python 2.5.2:\n>>> class MyDict(dict):\n... def __init__(self, *args, **kwargs):\n... super(MyDict, self).__init__(*args, **kwargs)\n... self['name'] = 'james'\n...\n>>> d = MyDict()\n>>> print d['name']\njames\n\n", "A basic subclass of dict will allow basic storage:\nclass MyDict(dict):\n de...
[ 2, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0006722162_oop_python.txt
Q: How come this Python method does not have "self"? class MM(dict): def __init__(self, indexed, *args, **kwargs): super(MM, self).__init__(*args, **kwargs) #must do it. self['name'] = 'hello, this is a value' self.go() def go(self, kwargs): print kwargs #I want this to print ...
How come this Python method does not have "self"?
class MM(dict): def __init__(self, indexed, *args, **kwargs): super(MM, self).__init__(*args, **kwargs) #must do it. self['name'] = 'hello, this is a value' self.go() def go(self, kwargs): print kwargs #I want this to print out the kwargs How come this class creates an error w...
[ "You probably want to do:\ndef go(self, **kwargs):\n print kwargs\n\nTo take keyword only arguments. So the function call will work.\nAlso you have to pass something else to your constructor (because of unused argument indexed):\nm = MM(1) #or whatever\n\n", "Modify your code the following way:\nclass MM(dict)...
[ 2, 2, 2, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0006722252_oop_python.txt
Q: How come this python class prints out my kwargs? class Meta(dict): def __init__(self, indexed, method, *args, **kwargs): super(Meta, self).__init__(*args, **kwargs) print self How come this prints my kwargs? m = Meta(indexed='hello', method='distance', a='3', b='4') When I run this, it prints...
How come this python class prints out my kwargs?
class Meta(dict): def __init__(self, indexed, method, *args, **kwargs): super(Meta, self).__init__(*args, **kwargs) print self How come this prints my kwargs? m = Meta(indexed='hello', method='distance', a='3', b='4') When I run this, it prints out a dictionary with my kwargs, when I'm expecting a...
[ "Why do you expect self not to contain your keyword args, when you explicitly initialized your instance (a dict subclass) with the keyword args by calling the dict class's initializer?\n", "That's because the dict class initializes its contents from the keyword arguments passed to its constructor:\n>>> dict(index...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0006722316_oop_python.txt
Q: Can't escape table or column names when importing data model from XML using SQLite Possible Duplicate: How do you escape strings for SQLite table/column names in Python? I would like to import an entire data model from an XML file using SQLite, and while I know how to programmatically insert/escape values using ...
Can't escape table or column names when importing data model from XML using SQLite
Possible Duplicate: How do you escape strings for SQLite table/column names in Python? I would like to import an entire data model from an XML file using SQLite, and while I know how to programmatically insert/escape values using the ? syntax in queries, this does not work for the names of tables or columns when cre...
[ "Here's a similar question. It doesn't look like there's any way to do what you're asking through the sqlite module(s). Most people just include the table name literally. If you're really paranoid, you could write a function to see if a table name looks valid, maybe something like:\nimport string\n\ndef isValidTabl...
[ 1, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006673015_python_sqlite.txt
Q: Python lxml: How to tell if an element has been removed from a tree? I am attempting to manipulate a DOM tree using lxml's etree module. One task I haven't figured out yet is how to test whether a particular node is still part of a parsed tree. Since the behavior of etree is mostly undefined if you remove nodes ...
Python lxml: How to tell if an element has been removed from a tree?
I am attempting to manipulate a DOM tree using lxml's etree module. One task I haven't figured out yet is how to test whether a particular node is still part of a parsed tree. Since the behavior of etree is mostly undefined if you remove nodes during _ElementTree.iter(), I do the manipulation in two phases. First, I ...
[ "Step 0: parse the xml into a tree.\nStep 1: iterate over the tree, deleting nodes that need to be deleted.\nStep 2: iterate over the remaining nodes, processing those that need it.\nIf you own step 0, you can use iterparse() with end events to save building a large tree only to remove many nodes later, and making ...
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006721392_lxml_python.txt
Q: Django GenericForeignKey in the admin class Comment(models.Model): text = models.TextField() timestamp = models.DateTimeField(auto_now_add = True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', '...
Django GenericForeignKey in the admin
class Comment(models.Model): text = models.TextField() timestamp = models.DateTimeField(auto_now_add = True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class Product(models.Model): ...
[ "I suggest adding unicode method to Comment model:\ndef __unicode__(self):\n return 'Comment %s - to a %s - %s' % (self.pk, self.content_type, self.content_object.__unicode__(), self.timestamp)\n\nIf you are using standart ModelAdmin, then there is no need to change admin.py.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006722155_django_django_admin_python.txt
Q: "or die()" in Python Is anyone using anything like this in Python: def die(error_message): raise Exception(error_message) ... check_something() or die('Incorrect data') I think this kind of style is used in PHP and Perl. Do you find any (dis)advantages in this [style]? A: Well, first, sys.exit([arg]) is m...
"or die()" in Python
Is anyone using anything like this in Python: def die(error_message): raise Exception(error_message) ... check_something() or die('Incorrect data') I think this kind of style is used in PHP and Perl. Do you find any (dis)advantages in this [style]?
[ "Well, first, sys.exit([arg]) is more common, and if you really wanted something equivalent to die in PHP, you should use that, raise a SystemExit error, or call os._exit.\nThe major use of the die method in PHP is, \"The script has reached some impasse cannot recover from it\". It is rarely, if ever, used on produ...
[ 85, 48, 25, 7, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006722210_python.txt
Q: Python integer infinity for slicing I have defined a slicing parameter in a config file: max_items = 10 My class slices a list according to this parameter: items=l[:config.max_itmes] When max_items = 0, I want all items to be taken from l. The quick and dirty way is: config.max_items=config.max_items if config.m...
Python integer infinity for slicing
I have defined a slicing parameter in a config file: max_items = 10 My class slices a list according to this parameter: items=l[:config.max_itmes] When max_items = 0, I want all items to be taken from l. The quick and dirty way is: config.max_items=config.max_items if config.max_items>0 else 1e7 Assuming that there ...
[ "There is no \"infinity integer constant\" in Python, but using None in a slice will cause it to use the default for the given position, which are the beginning, the end, and each item in sequence, for each of the three parts of a slice.\n>>> 'abc'[:None]\n'abc'\n\n", "Have you tried with sys.maxint?\n" ]
[ 30, 0 ]
[]
[]
[ "infinity", "integer", "python" ]
stackoverflow_0006723009_infinity_integer_python.txt
Q: taskqueue and non-idempotent tasks I'm working on a voting app, where the user can upload a list of email addresses for all of the voters. After doing some error checking, I create a Voter entity for each voter. Since there can be a large number of voters, I create the Voter entities in a taskqueue to avoid the ...
taskqueue and non-idempotent tasks
I'm working on a voting app, where the user can upload a list of email addresses for all of the voters. After doing some error checking, I create a Voter entity for each voter. Since there can be a large number of voters, I create the Voter entities in a taskqueue to avoid the 30 second limit and the task looks like ...
[ "use a key_name rather than a uuid property to prevent creating duplicate voter entities.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "idempotent", "python", "task_queue" ]
stackoverflow_0006719989_google_app_engine_idempotent_python_task_queue.txt
Q: Running an external interactive program from a python script I have a python script which tries to execute external programs. My project involves a python talk bot through which the client should be able to execute commands in the remote terminal. So basically the module incorporating the talk bot allows me only t...
Running an external interactive program from a python script
I have a python script which tries to execute external programs. My project involves a python talk bot through which the client should be able to execute commands in the remote terminal. So basically the module incorporating the talk bot allows me only to get inputs and send output.I need to take the input and see if i...
[ "In my opinion the best model for this kind of problems is using an asynchronous single-threaded approach, but it requires code that is somewhat complex even with use of helping libraries.\nSomething conceptually simpler is the use of a multithread approach\nimport thread\nimport sys\nimport time\n\ndef repl():\n ...
[ 0, 0 ]
[]
[]
[ "external", "python" ]
stackoverflow_0006722438_external_python.txt
Q: How can I write a class that behaves exactly like another dynamically determined class? (Python) I want to create a 'File' object that returns 'Line' objects when the ReadLine() method is invoked instead of just strings. I also want to be able to initialize the File object with either a string containing the absol...
How can I write a class that behaves exactly like another dynamically determined class? (Python)
I want to create a 'File' object that returns 'Line' objects when the ReadLine() method is invoked instead of just strings. I also want to be able to initialize the File object with either a string containing the absolute path of a text document, or with a list of a strings, and have the resulting instance behave ident...
[ "To simplify the count property, use the property decorator:\n@property\ndef count(self):\n return self._count # or return self.actual.count\n\n@count.setter\ndef count(self, value):\n self._count = value # or self.actual.count = value\n\nOr if you don't want it to be a decorator:\ncount = property(Get_coun...
[ 1, 1, 0 ]
[]
[]
[ "inheritance", "input", "io", "object", "python" ]
stackoverflow_0006720215_inheritance_input_io_object_python.txt
Q: Ruby vs Python for Society Management System ! My Graduation Project is developing a web-based Society Management System and i sould deliver Final Product of it at May 2012. for sure the front-end side will be designed using javascript,HTML,CSS,AJAX,..etc. The Question at Back-end side, my choice will be between R...
Ruby vs Python for Society Management System !
My Graduation Project is developing a web-based Society Management System and i sould deliver Final Product of it at May 2012. for sure the front-end side will be designed using javascript,HTML,CSS,AJAX,..etc. The Question at Back-end side, my choice will be between Ruby on Rails and Python, i don't need to explain me ...
[ "I think learning Python is easier than learning Ruby (simpler syntax).\nSo in my opinion start with Python to learn the concepts of scripting languages and afterwards Ruby will be easier.\n" ]
[ 1 ]
[]
[]
[ "content_management_system", "python", "ruby_on_rails" ]
stackoverflow_0006723370_content_management_system_python_ruby_on_rails.txt
Q: Event-driven thread creation I have been trying all kinds of solution to the following problem; to no avail. I have a large number of (python) modules/scripts and a distinguished script, K.py . When K.py is executed, it generates some information, say a country name. Now, amongst the other modules (hundreds) there...
Event-driven thread creation
I have been trying all kinds of solution to the following problem; to no avail. I have a large number of (python) modules/scripts and a distinguished script, K.py . When K.py is executed, it generates some information, say a country name. Now, amongst the other modules (hundreds) there will be modules that can be execu...
[ "The usual way to solve this is to create a worker queue and store the single jobs there. So you need some kind of programatical representation of the work that should be done by one thread.\nIf you have that you can use the multiprocessing package that offers a \"thread\" pool (see 16.3.1.5.) and a multithreaded q...
[ 2 ]
[]
[]
[ "consumer", "multithreading", "producer", "python" ]
stackoverflow_0006723802_consumer_multithreading_producer_python.txt
Q: Appengine Bulkloader with django-nonrel I want to use appengine bulkloader with my django-nonrel project as suggested in http://thomas.broxrost.com/category/google-app-engine/ and in http://blog.suinova.com/2009/03/tutorial-on-bulkloading-data-onto-app.html. But it giving error : No module named google.appengine.e...
Appengine Bulkloader with django-nonrel
I want to use appengine bulkloader with my django-nonrel project as suggested in http://thomas.broxrost.com/category/google-app-engine/ and in http://blog.suinova.com/2009/03/tutorial-on-bulkloading-data-onto-app.html. But it giving error : No module named google.appengine.ext.webapp. I think this is because of Django-...
[ "just saw your post. I'm able to use the appengine bulkloader just fine with my django-nonrel project. \nThere are a couple things to note:\n\nOn the models I need bulkloaded, I have the primary keys set manually by placing 'primary_key=True' in the field I want to use as a primary key. This makes Django create the...
[ 2 ]
[]
[]
[ "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0006149791_django_nonrel_google_app_engine_python.txt
Q: can't set background color ttk python os x using styles With this code fragment, I would expect the label to have a background color red. def createWidgets(self): style = ttk.Style() style.configure("Red.TLabel", foreground="green", background="red") self.label1 = ttk.Label(textvariable=self.numberArr...
can't set background color ttk python os x using styles
With this code fragment, I would expect the label to have a background color red. def createWidgets(self): style = ttk.Style() style.configure("Red.TLabel", foreground="green", background="red") self.label1 = ttk.Label(textvariable=self.numberArray[0][0],style="Red.TLabel") self.label1.pack() I get th...
[ "\nYou'll sometimes try to change an option that is supposed to exist according to element options, but it will have no effect. As an example, you can't modify the background color of a button in the \"aqua\" theme used by Mac OS X. While there are valid reasons for these cases, at the moment its not easy to discov...
[ 7 ]
[]
[]
[ "macos", "operating_system", "python", "tkinter", "ttk" ]
stackoverflow_0006723850_macos_operating_system_python_tkinter_ttk.txt
Q: Can't Move Foward with Camera in OpenGL I'm experimenting with pyOpenGL and I've had trouble getting the camera to work properly. def Draw(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotatef(roty,1,0,0) glRotatef(rotx,0,1,0) gl...
Can't Move Foward with Camera in OpenGL
I'm experimenting with pyOpenGL and I've had trouble getting the camera to work properly. def Draw(): glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRotatef(roty,1,0,0) glRotatef(rotx,0,1,0) glTranslate(0,0,eyez) glPushMatrix() ...
[ "If you are writing an application that has the concept of the camera moving (and rotating too I suppose) then rather than operating on the object with glRotate and glTranslate consider looking into gluLookAt, which allows you to set things up in a camera-centered way, so to speak.\nBy the way, gluLookAt is depreca...
[ 5, 2, 0 ]
[]
[]
[ "camera", "opengl", "python" ]
stackoverflow_0006719756_camera_opengl_python.txt
Q: python: How to debug multiprocess? (using eclipse+pydev) I've seen a couple of questions on the topic but I didn't get a full answer... My code is basically: from multiprocessing import Process p = Process(target=f).start() p.join() def f(): print 'break!' And I want to put a breakpoint on the print. I'm usin...
python: How to debug multiprocess? (using eclipse+pydev)
I've seen a couple of questions on the topic but I didn't get a full answer... My code is basically: from multiprocessing import Process p = Process(target=f).start() p.join() def f(): print 'break!' And I want to put a breakpoint on the print. I'm using pydev+eclipse (on Ubuntu).
[ "Because the new process itself is not controlled by PyDev, you need to make PyDev debugger manually aware of through Remote Debugging facilities.\nhttp://pydev.org/manual_adv_remote_debugger.html\nUse pydevd.set_trace() - notice that your breakpoints won't work (not sure if this has changed recent PyDev versions),...
[ 10 ]
[]
[]
[ "debugging", "eclipse", "multiprocess", "pydev", "python" ]
stackoverflow_0006724149_debugging_eclipse_multiprocess_pydev_python.txt
Q: MiddleStorm middleware with bottle How do you use MiddleStorm middleware with bottle? I followed this example, replacing SessionMiddleware with MiddleStorm, but I can't get it to work. from bottle import * from storm.locals import * from middlestorm import MiddleStorm #other bottle code like this here... @get('/'...
MiddleStorm middleware with bottle
How do you use MiddleStorm middleware with bottle? I followed this example, replacing SessionMiddleware with MiddleStorm, but I can't get it to work. from bottle import * from storm.locals import * from middlestorm import MiddleStorm #other bottle code like this here... @get('/') def index(): return 'index' db ...
[ "Actually default_app and app are synonymous. This should work:\nmyapp = MiddleStorm(app(), db)\n\nJust testing briefly and it seems to work for me. Can you try testing this:\nfrom bottle import *\nfrom storm.locals import *\nfrom middlestorm import MiddleStorm\n\n@get('/')\ndef index():\n return 'index'\n\ndb = ...
[ 3 ]
[]
[]
[ "bottle", "python", "wsgi" ]
stackoverflow_0006724430_bottle_python_wsgi.txt
Q: how do i extract a partial value from a string in python? I have the following string: (1, 2, 3, 4) I want to convert it to just the last two values: (3, 4) In my actual code all four fields are whole numbers but vary greatly in length. I've tried doing this with both regex and 'for' statements as well as trying...
how do i extract a partial value from a string in python?
I have the following string: (1, 2, 3, 4) I want to convert it to just the last two values: (3, 4) In my actual code all four fields are whole numbers but vary greatly in length. I've tried doing this with both regex and 'for' statements as well as trying the various answers to similar questions here on SO but so far...
[ "This gives you the last two terms in your tuple:\n>> a = (1,2,3,4)\n>> a[-2:]\n(3,4)\n\n", "It sounds like you want to use the slice operator.\nEdit: Perhaps this is a better link. Scroll down a bit for the slice notation stuff. The examples deal with strings, but it should work with any sequence type.\n", "...
[ 5, 2, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0006724407_python_regex_string.txt
Q: put() doesn't "put" my changes! I'm tinkering with app engine and I've written an edit form to edit my stored objects, let's say they're the model Foo. I have this code which is all executed and doesn't produce any exceptions yet the items in the data store remain unchanged: class EditFooItemHandler(BaseHandler): ...
put() doesn't "put" my changes!
I'm tinkering with app engine and I've written an edit form to edit my stored objects, let's say they're the model Foo. I have this code which is all executed and doesn't produce any exceptions yet the items in the data store remain unchanged: class EditFooItemHandler(BaseHandler): page = "edit_fooitem" def pos...
[ "barid \n\nis not defined as a property but rather as a method in the model. To make the above code work I can retrieve Bar.get_by_id(barid) and then do\nnew_bar = Bar.get_by_id(barid)\nfoo.bar = new_bar\n\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006724327_google_app_engine_python.txt
Q: python converting string to int and adding 1 im stuck, im trying to add these together but instead of getting 8+7 = 15 im getting 8+7 = 87 I am converting count_current to an integer but it still doesn't work: count_current = int(count_current) for playlist in playlists_data: count_current += 1 any help is m...
python converting string to int and adding 1
im stuck, im trying to add these together but instead of getting 8+7 = 15 im getting 8+7 = 87 I am converting count_current to an integer but it still doesn't work: count_current = int(count_current) for playlist in playlists_data: count_current += 1 any help is much appreciated thanks J
[ "You are clearly not doing what you say you are doing:\n>>> x = '8'\n>>> y = '7'\n>>> x+y\n'87'\n>>> x = int(x)\n>>> y = int(y)\n>>> x+y\n15\n\nUse + on strings and you get concatenation. Use + on integers and you get addition. If you are getting concatenation then you must be operating on strings rather than int...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006724513_python.txt
Q: Python PHP SOA design I am in the planning stage of a moderately big application -- and after some discussions and meetings, my colleges and i have reached a conclusion that we'll be using SOA for this App. Here is the brief plan... a 4-tier architecture.. |-------- database (NoSQL + SQL polyglot store) ...
Python PHP SOA design
I am in the planning stage of a moderately big application -- and after some discussions and meetings, my colleges and i have reached a conclusion that we'll be using SOA for this App. Here is the brief plan... a 4-tier architecture.. |-------- database (NoSQL + SQL polyglot store) --------| |-------- py...
[ "A few thoughts on your ideas: As Mikko's comment mentions, the PHP layer seems superfluous. It's not clear what function it will actually implement, specifically in terms of the abstraction it provides on top of the service layer. Modern application design is tending towards implementing the UI in javascript+ht...
[ 3 ]
[]
[]
[ "php", "python", "soa" ]
stackoverflow_0006724004_php_python_soa.txt
Q: from reportlab.platypus import ListFlowable, ListItem not working I am a newbie to python. I have to create an ordered list in my pdf document using Reportlab. I found these two classes ListFlowable(), ListItem() in the user-guide of Reportlab to do the same. But the very first import statement for these classes i...
from reportlab.platypus import ListFlowable, ListItem not working
I am a newbie to python. I have to create an ordered list in my pdf document using Reportlab. I found these two classes ListFlowable(), ListItem() in the user-guide of Reportlab to do the same. But the very first import statement for these classes is not working. from reportlab.platypus import ListFlowable, ListItem ...
[ "In my install of ReportLab 2.5 this isn't available. I see it's there in the documentation, but searching through the code there is no such thing as a ListFlowable or ListItem. This might be something that's only available in the closed-source portion of ReportLab and not the open source.\nIf you need to make li...
[ 1 ]
[]
[]
[ "pdf_generation", "python", "reportlab" ]
stackoverflow_0006715530_pdf_generation_python_reportlab.txt
Q: Creating python lists of mapped values from keys in a list of lists I have a python dict as below mymap={'java':40,'haskell':60,'ruby':50,'python':70,'scala':30,'lisp':80,'scheme':75} I have the keys put in sublists mapkeys = [['haskell','java'],['lisp','python'],['scala','scheme'],['ruby']] Now,I need to create...
Creating python lists of mapped values from keys in a list of lists
I have a python dict as below mymap={'java':40,'haskell':60,'ruby':50,'python':70,'scala':30,'lisp':80,'scheme':75} I have the keys put in sublists mapkeys = [['haskell','java'],['lisp','python'],['scala','scheme'],['ruby']] Now,I need to create a list of lists of values of these keys as below [[60,40],[80,70],[30,75...
[ "Try this:\n>>> [[mymap[k] for k in l] for l in mapkeys]\n[[60, 40], [80, 70], [30, 75], [50]]\n\nFor a non-nested list, remove the brackets and reverse the for statements:\n>>> [mymap[k] for l in mapkeys for k in l]\n[60, 40, 80, 70, 30, 75, 50]\n\n", "In case that you find lambda expressions easier to read than...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006724648_dictionary_list_python.txt
Q: How to build a binary tree from down to top? I am trying to build a tree. I´m begging with the next piece of code: >>> class tree: def __init__(self, charge, left=None, right=None): self.charge = charge self.left = left self.right = right >>> class tree: def __str__(self): ...
How to build a binary tree from down to top?
I am trying to build a tree. I´m begging with the next piece of code: >>> class tree: def __init__(self, charge, left=None, right=None): self.charge = charge self.left = left self.right = right >>> class tree: def __str__(self): return str(self.charge) After writing that I writ...
[ "You are defining a class and then redefining it. Every time you say class tree: you create a new class definition, overwriting the previous one. Since the last definition of tree doesn't define an __init__ method, it doesn't take any arguments. \nThe fact that you are doing this in the interactive interpreter comp...
[ 7 ]
[]
[]
[ "binary_tree", "python" ]
stackoverflow_0006724747_binary_tree_python.txt
Q: Convert variable into class variable (no idea what to name it) Using Flask Flask-sqlalchemy Sqlalchemy Jquery Datatables (jquery plugin) Jeditable (jquery plugin) Consider this user class ( straight out of flask-sqlalchemy docs): class User(db.Model): id = db.Column(db.Integer, primary_key=True) username...
Convert variable into class variable (no idea what to name it)
Using Flask Flask-sqlalchemy Sqlalchemy Jquery Datatables (jquery plugin) Jeditable (jquery plugin) Consider this user class ( straight out of flask-sqlalchemy docs): class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.S...
[ "Use a map of column ID to attribute name.\ncolmap = {\n 0: 'id',\n 1: 'username',\n 2: 'email',\n}\n\n@app.route('/modify', methods=['GET', 'POST'])\ndef modify()\n if request.method == 'POST' :\n user = user.query.get(form.row_id)\n try:\n setattr(user, colmap[form.column_id],...
[ 2 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0006724772_flask_flask_sqlalchemy_python.txt
Q: Worker framework for Amazon EC2 Are there any generic worker frameworks for Amazon EC2 available for Python? Something, for which you could just say "run this Python task X" and it will automatically assign the task to one of worker process on the servers from a server pool and report back after the task has been ...
Worker framework for Amazon EC2
Are there any generic worker frameworks for Amazon EC2 available for Python? Something, for which you could just say "run this Python task X" and it will automatically assign the task to one of worker process on the servers from a server pool and report back after the task has been executed? Describe task in a Python ...
[ "You could try Elastic MapReduce \n" ]
[ 0 ]
[]
[]
[ "amazon_ec2", "multiprocessing", "python", "subprocess" ]
stackoverflow_0006724946_amazon_ec2_multiprocessing_python_subprocess.txt
Q: Excluding fields in generic CRUD views I have a model named Domain which looks like this: class Domain(models.Model): """ Model for storing the company domains """ user = models.ForeignKey( User ) host = models.CharField( null=False, verbose_name="Host", max_length=128, uniq...
Excluding fields in generic CRUD views
I have a model named Domain which looks like this: class Domain(models.Model): """ Model for storing the company domains """ user = models.ForeignKey( User ) host = models.CharField( null=False, verbose_name="Host", max_length=128, unique=True ) I'd like to use Django's gene...
[ "Have a look at Russel's answer to a similar question on the django-users group earlier this week.\nQuoting the answer*:\n\nForms and Views solve different problems.\nThe View is solving the problem of \"how do I handle this request and\n convert it into a response?\". The Form is solving the problem of \"How\n d...
[ 2 ]
[]
[]
[ "django", "django_generic_views", "django_views", "python" ]
stackoverflow_0006725080_django_django_generic_views_django_views_python.txt
Q: Deleting duplicates from a list of lists if some duplicates do not have the same order My problem is very similar to the one linked below except that if there was a [2,1] element I would need that to be deleted too. Removing duplicates from a list of lists I've tried all sorts of things but just can't make it wor...
Deleting duplicates from a list of lists if some duplicates do not have the same order
My problem is very similar to the one linked below except that if there was a [2,1] element I would need that to be deleted too. Removing duplicates from a list of lists I've tried all sorts of things but just can't make it work. Any help would be much appreciated! Thanks.
[ "This works, but it doesn't preserve the ordering of the sublists:\ndef bygroup(k):\n k = sorted(sorted(x) for x in k)\n return [k for k,_ in itertools.groupby(k)]\n\n>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [2, 1]]\n\n>>> bygroup(k)\n[[1, 2], [2, 5, 6], [3], [4]]\n\nIn Python 2.7 or 3.2, you could ...
[ 1, 0 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0006724544_duplicates_list_python.txt
Q: python re module to replace the binary data inside a text file? I know mixing text and binary is awful, but I have to do this. I want to replace the binary content, which is around with "Content-Type: image" and "----", by string "XXXXXXXX" So the code for test is: # coding=utf-8 import re raw_data = open('r_img.t...
python re module to replace the binary data inside a text file?
I know mixing text and binary is awful, but I have to do this. I want to replace the binary content, which is around with "Content-Type: image" and "----", by string "XXXXXXXX" So the code for test is: # coding=utf-8 import re raw_data = open('r_img.txt').read() #data = re.sub(r"Content-Type: image.*?-----","Content-Ty...
[ "This works for me:\ndata = re.sub(r\"Content-Type: image.*-----\",\"Content-Type: imageXXXXXXX-----\", \n raw_data, 0, re.DOTALL)\n\nEssentially it matches in a greedy way all characters between Content-Type: image and -----. The 0 means \"match all occurrences of this pattern\". Probably this is supe...
[ 1 ]
[]
[]
[ "binary", "content_type", "python", "regex" ]
stackoverflow_0006621280_binary_content_type_python_regex.txt
Q: Setting local variables to a function instead of using globals optimize the function In the documentation for the itertools module I found this comment def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) Note, many of the above recipes can be optimized by replacing global lookups with loc...
Setting local variables to a function instead of using globals optimize the function
In the documentation for the itertools module I found this comment def dotproduct(vec1, vec2): return sum(imap(operator.mul, vec1, vec2)) Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the dotproduct recipe can be writt...
[ "\nIs there a practical noticeable speed-up (that could balance the inconvenience of the larger function signature)?\n\nI very much doubt it, as the lookups occur once each in the original definition. Note that you've changed the meaning of the function.\n\nIn which specific conditions the use of local variables in...
[ 2 ]
[]
[]
[ "function_parameter", "local_variables", "python" ]
stackoverflow_0006725223_function_parameter_local_variables_python.txt
Q: How to install python cli scripts with setuptools without duplicates? I have 2 Python scripts that can be used from the shell as they are thanks to argparse. The relevant part of setup.py: setup( # (...) zip_safe=True, scripts=['bin/bgce.py', 'bin/sizes.py'], packages=find_packages(), data_file...
How to install python cli scripts with setuptools without duplicates?
I have 2 Python scripts that can be used from the shell as they are thanks to argparse. The relevant part of setup.py: setup( # (...) zip_safe=True, scripts=['bin/bgce.py', 'bin/sizes.py'], packages=find_packages(), data_files=data_files, entry_points = { 'console_scripts': [ ...
[ "Make sure that the actual modules have a main function like this:\ndef main():\n try:\n some_stuff()\n except KeyboardInterrupt :\n print \"\"\n sys.exit()\n\nif __name__ == \"__main__\" :\n main()\n\nWe often do the pattern of writing out main code below the if __name__ == \"__main_...
[ 4, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0004359553_python_setuptools.txt
Q: Counter in a recursive function in Python is not producing an output with Print(using Netbeans) I am new to Python. I am using Netbeans IDE 6.8. When I run the code below- using RUN FILE- it does not seem to produce any output. On the other hand when I debug the code, the output shows the value of counter- 6. I...
Counter in a recursive function in Python is not producing an output with Print(using Netbeans)
I am new to Python. I am using Netbeans IDE 6.8. When I run the code below- using RUN FILE- it does not seem to produce any output. On the other hand when I debug the code, the output shows the value of counter- 6. Is this a problem with the program below or one of quirks of Netbeans. Here is the code: class Count...
[ "This is a classic \"bug\" of netbeans and other IDEs. For terminal programs, they open a terminal, run the program under it, and then close it. This of course, means that your output window disappears.\nThere are two ways to fix it, depending on your IDE. Some IDEs have an option to wait for a key press after prog...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006725157_python.txt
Q: how do i hook commands sent to pdb through gud? i've started using pdb through gud in emacs 23.3, how can i hook command messages sent to the debugger from the buffer? i wrote the advice below for use with gdb, in order to persist comint's ring, but can't find an equivalent function to hook for pdb. i'm using pyth...
how do i hook commands sent to pdb through gud?
i've started using pdb through gud in emacs 23.3, how can i hook command messages sent to the debugger from the buffer? i wrote the advice below for use with gdb, in order to persist comint's ring, but can't find an equivalent function to hook for pdb. i'm using python-mode.el as my major mode. thanks. (defadvice gdb-s...
[ "i think i probably could have answered my own question at the time with just a little more digging, but the first gdb solution rather took it out of me on the old learning front. i recovered, so..\nC-h b \nC-s Major \nafter a bit of scrolling we can identify 'comint-send-input' as the function bound to key 'enter'...
[ 2 ]
[]
[]
[ "elisp", "emacs", "gud", "pdb", "python" ]
stackoverflow_0006257758_elisp_emacs_gud_pdb_python.txt
Q: A site is available but it always responses "Internal Server Error" The code looks like: url ="http://www.example.com" for a in range(0,10): opener = urllib2.build_opener() urllib2.install_opener(opener) postdata ="info=123456"+str(a) urllib2.urlopen(url, postdata) which just post some data to a...
A site is available but it always responses "Internal Server Error"
The code looks like: url ="http://www.example.com" for a in range(0,10): opener = urllib2.build_opener() urllib2.install_opener(opener) postdata ="info=123456"+str(a) urllib2.urlopen(url, postdata) which just post some data to a specific URL(e.g. http://www.example.com), however, I always get the err...
[ "You say you're sure the site is working, yet it returns an error. Why don't you try doing whatever you did to determine that the site is working, while running a network logger like wireshark, and then run your test program to see if the two are really issuing the same queries. If not, you've found the problem.\...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006725664_python.txt
Q: Solving for unknown in bit-wise algebra Suppose I have 3 bytes, X Y and Z. X XOR Y results in Z. I know what X and Z are, but I don't know what Y is, so I'm writing a quick script to figure this out. Though, I don't know how I would even begin. I did a couple of them by hand and it was simply a matter of comparing...
Solving for unknown in bit-wise algebra
Suppose I have 3 bytes, X Y and Z. X XOR Y results in Z. I know what X and Z are, but I don't know what Y is, so I'm writing a quick script to figure this out. Though, I don't know how I would even begin. I did a couple of them by hand and it was simply a matter of comparing each bit one by one, but how can I do this i...
[ "If x ^ y == z, then x ^ z == y. You can verify this in Python with\n>>> X = range(256) # all byte values\n>>> Y = range(256)\n>>> all(x ^ z == y for x in X for y in Y for z in [x^y])\n\n" ]
[ 7 ]
[]
[]
[ "bitwise_xor", "python" ]
stackoverflow_0006725881_bitwise_xor_python.txt
Q: google app engine with django upload file error i am using django with google app engine . i am trying to upload images. i made a form <form enctype="multipart/form-data" action="addImage" method="post"> <p>Title of the Image: <input type="text" name="title" /></p> <p>Please select imag...
google app engine with django upload file error
i am using django with google app engine . i am trying to upload images. i made a form <form enctype="multipart/form-data" action="addImage" method="post"> <p>Title of the Image: <input type="text" name="title" /></p> <p>Please select image to upload: <input type="file" name="img" r...
[ "I haven't used Google App Engine, but this is how I would do it on a pure Django 1.3 installation:\nforms.py:\nfrom django import forms\nfrom django.forms import fields\n\nclass UploadImageForm(forms.Form):\n image_file = fields.ImageField()\n\nviews.py:\nfrom django.shortcuts import render_to_response\nfrom dj...
[ 0, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python", "upload" ]
stackoverflow_0006443037_django_google_app_engine_python_upload.txt
Q: Using variable length argument lists and named parameters together I need some help with figuring out Pythons *args and **kwargs. It's simple but I haven't entire wrapped my head around them. Here's one of scenarios that's bewildering to me. I have two functions mainfunc and wrapperfunc (which is a wrapper functio...
Using variable length argument lists and named parameters together
I need some help with figuring out Pythons *args and **kwargs. It's simple but I haven't entire wrapped my head around them. Here's one of scenarios that's bewildering to me. I have two functions mainfunc and wrapperfunc (which is a wrapper function for the main function). It looks like this. def mainfunc(fname=None, l...
[ "Keyword arguments must come after position arguments in Python.\n\nparams = {'uname':'j.doe'}\nwrapperfunc('john', 'doe', **params)\n\nwill pass the keyword arguments after the two positional arguments,\nIf you want to look at an argument, but otherwise do the call normally, do:\ndef wrapper(*args, **kwargs):\n ...
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006726008_python.txt
Q: scipy stats geometric mean returns NaN I am using scipy's gmean() function to determine the geometric mean of a numpy array that contains voltage outputs. The range of the numbers is between -80.0 and 30.0. Currently, the numpy array is two dimensional, giving the voltage for two different measurements. array([[-6...
scipy stats geometric mean returns NaN
I am using scipy's gmean() function to determine the geometric mean of a numpy array that contains voltage outputs. The range of the numbers is between -80.0 and 30.0. Currently, the numpy array is two dimensional, giving the voltage for two different measurements. array([[-60.0924, -60.0882], [-80. , -80. ...
[ "The geometric mean cannot be applied to negative values.\n" ]
[ 12 ]
[]
[]
[ "mean", "numpy", "python", "scipy", "statistics" ]
stackoverflow_0006726297_mean_numpy_python_scipy_statistics.txt