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: Split words and creating new files with different names(python) I need to write a program like this: Write a program that reads a file .picasa.ini and copies pictures in new files, whose names are the same as identification numbers of person on these pictures (eg. 8ff985a43603dbf8.jpg). If there are more person on...
Split words and creating new files with different names(python)
I need to write a program like this: Write a program that reads a file .picasa.ini and copies pictures in new files, whose names are the same as identification numbers of person on these pictures (eg. 8ff985a43603dbf8.jpg). If there are more person on the picture it makes more copies. If a person is on more pictures, l...
[ "Consider using ConfigParser. Then you will have to split each value by hand, as you describe.\n", "Suggestions:\n\nYour lines don't start with 'faces', so your second line won't work the way you want it to. Depending on how the rest of the file looks, you might only need to check whether the line is empty or no...
[ 0, 0, 0 ]
[]
[]
[ "parsing", "python", "split" ]
stackoverflow_0004287985_parsing_python_split.txt
Q: Detecting JavaScript on an HTML page using Python I'm currently working on a network security project that checks for XSS vulnerabilities on a website, which hopefully can be used for pen-testers out there (in case you don't believe me and think I'm some kinda script kiddy, here's the class website: http://netsec....
Detecting JavaScript on an HTML page using Python
I'm currently working on a network security project that checks for XSS vulnerabilities on a website, which hopefully can be used for pen-testers out there (in case you don't believe me and think I'm some kinda script kiddy, here's the class website: http://netsec.cs.northwestern.edu/projects/). So, I'm having trouble ...
[ "A incredibly hacky way would be to look for \"text/javascript\" in the source of the webpage.\nimport urllib2\nif urllib2.urlopen('http://www.google.co.uk').read().find('text/javascript') == 0:\n print \"It has js.\"\n\nThis is NOT the best answer I would be happy to hear from someone who does know the correct ...
[ 0, 0, 0 ]
[]
[]
[ "html", "javascript", "python", "security" ]
stackoverflow_0004258539_html_javascript_python_security.txt
Q: How to eliminate email formatting in received email? I am practicing sending emails with Google App Engine with Python. This code checks to see if message.sender is in the database: class ReceiveEmail(InboundMailHandler): def receive(self, message): querySender = User.all() querySender.filter("...
How to eliminate email formatting in received email?
I am practicing sending emails with Google App Engine with Python. This code checks to see if message.sender is in the database: class ReceiveEmail(InboundMailHandler): def receive(self, message): querySender = User.all() querySender.filter("userEmail =", message.sender) senderInDatabase = N...
[ "Rather than storing the entire contents of a To: or From: header field as an opaque string, why don't you parse incoming email and store email address separately from full name? See email.utils.parseaddr(). This way you don't have to use complicated, slow pattern matching when you want to look up an address. Yo...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0004287945_google_app_engine_python_regex.txt
Q: Ordering cells by their distance from center cell(s) I had someone ask me, what at that time seemed an innocent enough question: How do we ordering cells in a 2D array by their distance from predefined/precomputed center cell(s). Here is a table showing how far the particular cell is from predefined center cells (...
Ordering cells by their distance from center cell(s)
I had someone ask me, what at that time seemed an innocent enough question: How do we ordering cells in a 2D array by their distance from predefined/precomputed center cell(s). Here is a table showing how far the particular cell is from predefined center cells ( they have values of 0 in them ). A value of n means it's ...
[ "To make it shorter (and using a slightly different metric):\n>>> rows, cols, centerx, centery = 6, 6, 2.5, 2.5\n>>> [p[1:] for p in sorted((((x - centerx) ** 2 + (y - centery) ** 2, x, y)\n... for x in xrange(rows) for y in xrange(cols)))]\n[(2, 2), (2, 3), (3, 2), (3, 3), (1, 2), (1, 3), \...
[ 1, 1 ]
[]
[]
[ "matrix", "optimization", "python" ]
stackoverflow_0004288446_matrix_optimization_python.txt
Q: Writing excellent Twisted web Resources I wrote my very first Twisted 10.1.0 web Resource and I am seeking for feedback, because I feel this isn't exactly following the best practice and may contain newbies bugs. The resource responds to /?url=http://www.foo.baz/abc123 and relies on a service that returns a dict. ...
Writing excellent Twisted web Resources
I wrote my very first Twisted 10.1.0 web Resource and I am seeking for feedback, because I feel this isn't exactly following the best practice and may contain newbies bugs. The resource responds to /?url=http://www.foo.baz/abc123 and relies on a service that returns a dict. If anything goes wrong (e.g., invalid or non-...
[ "I think you wouldn't need to explicitly override getChild() if you set isLeaf=True\n" ]
[ 3 ]
[]
[]
[ "http", "python", "twisted", "twisted.web" ]
stackoverflow_0004287310_http_python_twisted_twisted.web.txt
Q: How do you do an os.path.join with an array in python? How do you do an os.path.join with an array in python? Basically, I want to be able to run that command with an array as an argument. Any help is highly appreciated. A: By array I assume you mean list. os.path.join(*parts) The * takes a list (or similar obj...
How do you do an os.path.join with an array in python?
How do you do an os.path.join with an array in python? Basically, I want to be able to run that command with an array as an argument. Any help is highly appreciated.
[ "By array I assume you mean list.\nos.path.join(*parts)\n\nThe * takes a list (or similar object) and expands it into parameters. Be careful using it, in many situations it will make your code harder to read. But here is makes sense.\n" ]
[ 23 ]
[]
[]
[ "join", "operating_system", "path", "python" ]
stackoverflow_0004288792_join_operating_system_path_python.txt
Q: Dividing a string by type of data inside each line of file in python It's safe to say I'm a noob in programming and python, so I really need help handling a file. My file is a dat file with an integer, a string and a float in each line, and I need to compare the first int with other ints and the float with some o...
Dividing a string by type of data inside each line of file in python
It's safe to say I'm a noob in programming and python, so I really need help handling a file. My file is a dat file with an integer, a string and a float in each line, and I need to compare the first int with other ints and the float with some other value, I need to have the values as numbers and not as part of a stri...
[ "Ignacio's answer is basically completely correct, and he posted it before I even started typing. However, let me explain his two-liner in a little more detail.\nReading a file\nFirst, a critique of your code:\nreadfile = open('file_being_read.dat').read()\n\nThis will read out your entire file into a giant string....
[ 4, 2 ]
[]
[]
[ "list", "python", "split", "string", "types" ]
stackoverflow_0004288696_list_python_split_string_types.txt
Q: How do you show the path of the current running python module? How do you show the path of the current running python module? Which would print /Users/user/documents/python/bla.py if bla.py was placed in /Users/user/documents/python/. A: If you want a module to know where it's at even when imported, you should b...
How do you show the path of the current running python module?
How do you show the path of the current running python module? Which would print /Users/user/documents/python/bla.py if bla.py was placed in /Users/user/documents/python/.
[ "If you want a module to know where it's at even when imported, you should be able to use\nimport sys\n\nsys.modules[__name__].__file__\n\nI know this includes the absolute path on my linux system but I've heard it said that it doesn't on Windows. \n", "import os\nprint os.path.abspath(__file__)\n\n" ]
[ 14, 8 ]
[]
[]
[ "path", "python" ]
stackoverflow_0004288905_path_python.txt
Q: Will django be around for the next ~5~ years? I'm currently working as an asp.net developer, At work were looking at some open source based toolkits to do some new projects in Ive been given complete freedom to chose what I want to work with (be it rails, django, zend) with one requirement... It can't be a here to...
Will django be around for the next ~5~ years?
I'm currently working as an asp.net developer, At work were looking at some open source based toolkits to do some new projects in Ive been given complete freedom to chose what I want to work with (be it rails, django, zend) with one requirement... It can't be a here today gone tommorow framework.. So my question is.. I...
[ "As I'm sure you know, this is extremely subjective and any answer would be nothing but speculation.\nIn general, I like to reference the ThoughtWorks Technology Radar for this kind of speculation. Unfortunately, I don't see Django or even Python anywhere on it. I find that a little odd, since Python is a perfect...
[ 0 ]
[]
[]
[ "django", "frameworks", "python", "ruby_on_rails" ]
stackoverflow_0004289332_django_frameworks_python_ruby_on_rails.txt
Q: Handling the requirements of Django model fields that are based on other fields This is a very simplified version of a model I'm working on: class ClothingTop(models.Model): SWEATER = 0 SHIRT = 1 TOP_CHOICES = ( (SWEATER, 'Sweat shirt'), (SHIRT, 'Shirt'), ) name = models....
Handling the requirements of Django model fields that are based on other fields
This is a very simplified version of a model I'm working on: class ClothingTop(models.Model): SWEATER = 0 SHIRT = 1 TOP_CHOICES = ( (SWEATER, 'Sweat shirt'), (SHIRT, 'Shirt'), ) name = models.CharField(max_length=32) type = models.PositiveSmallIntegerField(choices=TOP_CHOI...
[ "My simplest suggestion, and I'd believe it's the best one in practice, is that you create a ClothingTop ModelForm and set the buttons_clean() method on the form that will do the custom validation. This form would also have to be set for the ClothingTop ModelAdmin.\nThe only other way to do it is by creating a cust...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004288957_django_django_models_python.txt
Q: How do I prevent concurrent inserts from creating duplicate items? I have a SQLAlchemy model object that looks like this: ResultModelBase = declarative_base() class Task(ResultModelBase): """Task result/status.""" id = sa.Column(sa.Integer, sa.Sequence("task_id_sequence"), primary_key=T...
How do I prevent concurrent inserts from creating duplicate items?
I have a SQLAlchemy model object that looks like this: ResultModelBase = declarative_base() class Task(ResultModelBase): """Task result/status.""" id = sa.Column(sa.Integer, sa.Sequence("task_id_sequence"), primary_key=True, autoincrement=True) task_id = sa.Column(sa.S...
[ "Your problem is ill-defined. You have a design flaw in your database. You can not define the uniqueness of the row by its auto-incrementing id. You must have other fields that define it as unique (e.g. task_name+worker), and then create the task by these fields: Task(task_name=smt, worker=smt) - do not put task_id...
[ 2, 0 ]
[]
[]
[ "celery", "python", "sqlalchemy" ]
stackoverflow_0004288581_celery_python_sqlalchemy.txt
Q: Upper memory limit? Is there a limit to memory for python? I've been using a python script to calculate the average values from a file which is a minimum of 150mb big. Depending on the size of the file I sometimes encounter a MemoryError. Can more memory be assigned to the python so I don't encounter the error? E...
Upper memory limit?
Is there a limit to memory for python? I've been using a python script to calculate the average values from a file which is a minimum of 150mb big. Depending on the size of the file I sometimes encounter a MemoryError. Can more memory be assigned to the python so I don't encounter the error? EDIT: Code now below NOTE:...
[ "(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.\nEdits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major....
[ 34, 20, 18, 10, 6 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0004285185_memory_python.txt
Q: Reading bytes from Python String I have hex data in a string. I need to be able parse the string byte by byte, but through reading the docs, the only way to get data bytewise is through the f.read(1) function. How do I parse a string of hex characters, either into a list, or into an array, or some structure where ...
Reading bytes from Python String
I have hex data in a string. I need to be able parse the string byte by byte, but through reading the docs, the only way to get data bytewise is through the f.read(1) function. How do I parse a string of hex characters, either into a list, or into an array, or some structure where I can access byte by byte.
[ "It sounds like what you might really want (Python 2.x) is:\nfrom binascii import unhexlify\nmystring = \"a1234f\"\nprint map(ord,unhexlify(mystring))\n\n\n[161, 35, 79]\n\nThis converts each pair of hex characters into its integer representation.\nIn Python 3.x, you can do:\n>>> list(unhexlify(mystring))\n[161, 35...
[ 8, 3, 3, 0 ]
[]
[]
[ "hex", "python", "string" ]
stackoverflow_0004288788_hex_python_string.txt
Q: how to get the absolute path to the root folder This is my current folder structure, and i need to get the absolute path to the root folder . └── root/ ├── api.py └── programexecutablefolder/ └── mainentry.py The program has to start at mainentry.py, however I need to get the path of the root fold...
how to get the absolute path to the root folder
This is my current folder structure, and i need to get the absolute path to the root folder . └── root/ ├── api.py └── programexecutablefolder/ └── mainentry.py The program has to start at mainentry.py, however I need to get the path of the root folder from api.py (though the entry to api.py is through...
[ "Modules (typically) have an attribute named __file__ that contains the name of the file the module was loaded from, so you should be able to do something along the lines of:\nos.path.dirname(api.__file__)\n\n(BTW: os.getcwd() is not guaranteed to give you the directory of mainentry.py unless that's the directory y...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004289574_python.txt
Q: list comprehension question Is there a way to add multiple items to a list in a list comprehension per iteration? For example: y = ['a', 'b', 'c', 'd'] x = [1,2,3] return [x, a for a in y] output: [[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2,3], 'd'] A: sure there is, but not with a plain list comprehension...
list comprehension question
Is there a way to add multiple items to a list in a list comprehension per iteration? For example: y = ['a', 'b', 'c', 'd'] x = [1,2,3] return [x, a for a in y] output: [[1,2,3], 'a', [1,2,3], 'b', [1,2,3], 'c', [1,2,3], 'd']
[ "sure there is, but not with a plain list comprehension: \nEDIT: Inspired by another answer:\ny = ['a', 'b', 'c', 'd']\nx = [1,2,3]\n\nreturn sum([[x, a] for a in y],[])\n\nHow it works: sum will add a sequence of anythings, so long as there is a __add__ member to do the work. BUT, it starts of with an initial to...
[ 6, 1, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004289659_list_comprehension_python.txt
Q: Is web2py suitable for a large public website? Web2py looks like a very nice Python framework but I am wondering if it is suitable to use for a large public web site. What sorts of issues might I run into? I'm not worried about technical scalability so much as UI/UX limitations, ability to connect other components...
Is web2py suitable for a large public website?
Web2py looks like a very nice Python framework but I am wondering if it is suitable to use for a large public web site. What sorts of issues might I run into? I'm not worried about technical scalability so much as UI/UX limitations, ability to connect other components, etc.
[ "web2py is a very capable web server application framework. UI/UX (User interface / Experience) limitations does not arises usually from a server framework.\nThere are quite a number of free application that demonstrates it's capabilities:\n\nhttp://www.web2py.com/appliances \n\nIf you want to compare it with other...
[ 7, 5 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0004274417_python_web2py.txt
Q: Python Infinite While Loop Crashing Mac I have a python script with a loop such as while True: #do something here Whenever i run it, it will crash the mac. The mac runs Mac OS X 10.6.5 and python 2.6.1 A: If you can write any infinite loop and it causes a crash, then you either have a problem with your OS o...
Python Infinite While Loop Crashing Mac
I have a python script with a loop such as while True: #do something here Whenever i run it, it will crash the mac. The mac runs Mac OS X 10.6.5 and python 2.6.1
[ "If you can write any infinite loop and it causes a crash, then you either have a problem with your OS or your Python (since this doesn't normally cause a crash). Try out the MacPorts Python distribution and hopefully you won't have the same problems.\n", "Maybe your computer is overheating when you let it run on...
[ 1, 1, 0 ]
[]
[]
[ "infinite_loop", "python" ]
stackoverflow_0004289797_infinite_loop_python.txt
Q: How to perform an "UPDATE" with elixir I'm using elixir/flask in a small web app I wrote for my own personal aggregator. I'm trying to create a restful call to mark all items of a particular rssfeed as read. The SQL statement would look something like UPDATE model_rssitems set hasbeenseen = 1 where rssfeed_id = '...
How to perform an "UPDATE" with elixir
I'm using elixir/flask in a small web app I wrote for my own personal aggregator. I'm trying to create a restful call to mark all items of a particular rssfeed as read. The SQL statement would look something like UPDATE model_rssitems set hasbeenseen = 1 where rssfeed_id = '%s' % feedid I don't know how to write the c...
[ "I assume you haven't used the bind expression yet :)\nYour code requires something like this to tell Elixir what database you're using.\nfrom elixir import metadata\nmetadata.bind = 'sqlite:///your_database_file.sqlite'\nmetadata.bind.echo = True\n\n" ]
[ 1 ]
[]
[]
[ "flask", "python", "python_elixir", "sql" ]
stackoverflow_0004290039_flask_python_python_elixir_sql.txt
Q: Add the current project to the python path with Komodo Edit Ive been using komodo edit recently to go through a few django tutorials, and ive been impressed with the level of code completion it provides for the framework. However what i really want it to do is provide code completion for the current project, so i...
Add the current project to the python path with Komodo Edit
Ive been using komodo edit recently to go through a few django tutorials, and ive been impressed with the level of code completion it provides for the framework. However what i really want it to do is provide code completion for the current project, so in effect my own views, models etc. would work in the same way as ...
[ "You can set per-project Python paths in Project [Menu] -> Properties -> Languages -> Python -> Additional Python Import Directories. See the official documentation for more details.\n" ]
[ 3 ]
[]
[]
[ "intellisense", "komodo", "komodoedit", "python", "pythonpath" ]
stackoverflow_0004284767_intellisense_komodo_komodoedit_python_pythonpath.txt
Q: Problems installing MYSQL-python-1.2.3 for Python 2.7 on Snow Leopard I downloaded the tar.gz file from http://sourceforge.net/projects/mysql-python/files/ unzip, then ran python setup.py install, but it said it requires setuptools module, so I downloaded setuptools from http://pypi.python.org/pypi/setuptools#file...
Problems installing MYSQL-python-1.2.3 for Python 2.7 on Snow Leopard
I downloaded the tar.gz file from http://sourceforge.net/projects/mysql-python/files/ unzip, then ran python setup.py install, but it said it requires setuptools module, so I downloaded setuptools from http://pypi.python.org/pypi/setuptools#files The file was setuptools-0.6c11-py2.7.egg (md5) then I ran sh setuptools-...
[ "The root cause is probably that you have installed a 64-bit only version of the MySQL client libraries. Note that the MySQLdb build process (in setup_posix.py) queries the mysql_build command to find the various flags that were used to build the MySQL client libraries and augment the building of the MySQLdb exten...
[ 2, 0 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0004289481_macos_mysql_python.txt
Q: change matplotlib axis settings How do I get control over the axis settings of a pyplot plot. I have simply done pylab.plot(*self.plot_generator(low, high)) pylab.show() and I get this which is what I want but I want the x axis to be at 0 instead of at the bottom. How would I do that? A: # create some...
change matplotlib axis settings
How do I get control over the axis settings of a pyplot plot. I have simply done pylab.plot(*self.plot_generator(low, high)) pylab.show() and I get this which is what I want but I want the x axis to be at 0 instead of at the bottom. How would I do that?
[ "# create some data\nx = np.linspace(-np.pi,np.pi,100)\ny = np.cos(2.5*x)\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x,y, mfc='orange', mec='orange', marker='.')\n\n# using 'spines', new in Matplotlib 1.0\nax.spines['left'].set_position('zero')\nax.spines['right'].set_color('none')\nax.spines['bottom...
[ 19, 12 ]
[]
[]
[ "matplotlib", "python", "scipy" ]
stackoverflow_0004289891_matplotlib_python_scipy.txt
Q: Python with Wiimote using pywiiuse module After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class. I want to make a game with pygame incorporating a wiimote. I found pywiiuse which is a very...
Python with Wiimote using pywiiuse module
After seeing the abilities and hackibility of wiimotes I really want to use it in my 'Intro to programming' final. Everyone must make a python program and present it to the class. I want to make a game with pygame incorporating a wiimote. I found pywiiuse which is a very basic wrapper for the wiiuse library using c t...
[ "I updated the pywiiuse wrapper. It didn't seem to be made for the latest version of wiiuse (0.12 at the time of this answer), since much of it just wouldn't work in the current iteration.\nI've got the package and some example scripts posted here:\nhttp://code.google.com/p/pywiiuse/downloads/list\nYou should also ...
[ 3, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "wii", "wiimote" ]
stackoverflow_0000481943_python_wii_wiimote.txt
Q: Shared mmap co-ordination using fcntl locks? When using mmap() for shared memory (from Linux, or other UNIX-like systems) is it possible (and portable) to use fcntl() (or flock() or lockf() functions) to co-ordinate access to the mapping? Responses to this SO question seems to suggest that it should work. The ide...
Shared mmap co-ordination using fcntl locks?
When using mmap() for shared memory (from Linux, or other UNIX-like systems) is it possible (and portable) to use fcntl() (or flock() or lockf() functions) to co-ordinate access to the mapping? Responses to this SO question seems to suggest that it should work. The idea I have in mind would be to have the shared memor...
[ "I'm sure the locks will provide mutual exclusion, but I don't know if they will give you a memory barrier. It seems like jumping into the kernel (which fcntl, flock, and lockf will do) is likely to do something that forces out of order memory reads and writes to commit, but I doubt you'll get a hard guarantee. I...
[ 1 ]
[]
[]
[ "fcntl", "mmap", "python", "shared_memory", "synchronization" ]
stackoverflow_0002806603_fcntl_mmap_python_shared_memory_synchronization.txt
Q: Why shouldn't I use async (evented) IO I am writing now writing some evented code (In python using gevent) and I use the nginx as a web server and I feel both are great. I was told that there is a trade off with events but was unable to see it. Can someone please shed some light? James A: The only difficulty of ...
Why shouldn't I use async (evented) IO
I am writing now writing some evented code (In python using gevent) and I use the nginx as a web server and I feel both are great. I was told that there is a trade off with events but was unable to see it. Can someone please shed some light? James
[ "The only difficulty of evented programming is that you mustn't block, ever. This can be hard to achieve if you use some libraries that were designed with threads in mind. If you don't control these libraries, a fork() + message ipc is the way to go.\n", "Biggest issue is that without threads, a block for one cli...
[ 9, 1 ]
[]
[]
[ "asynchronous", "gevent", "libevent", "python" ]
stackoverflow_0004140656_asynchronous_gevent_libevent_python.txt
Q: How to speed up string concatenation in Python? In the code below concatenation is the bottleneck. As you can see i've tried some sophisticated methods to speed this up, but its bloody slow anyway. I would like to know if there is anything i can do to make it faste. BTW both plain and secret are data read from bin...
How to speed up string concatenation in Python?
In the code below concatenation is the bottleneck. As you can see i've tried some sophisticated methods to speed this up, but its bloody slow anyway. I would like to know if there is anything i can do to make it faste. BTW both plain and secret are data read from binary file and they are quite big (around 1mb) x = b'' ...
[ "Python's lists have O(1) append, at least in the amortized sense. Instead of doing the join in the innermost list, you could build one big list and then join them at the end. This will turn your algorithm from O(N^2) to O(N). It's tough to give you working code without knowing exactly what your setBit() and get...
[ 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0004289777_python.txt
Q: Python - caching a property to avoid future calculations In the following example, cached_attr is used to get or set an attribute on a model instance when a database-expensive property (related_spam in the example) is called. In the example, I use cached_spam to save queries. I put print statements when setting an...
Python - caching a property to avoid future calculations
In the following example, cached_attr is used to get or set an attribute on a model instance when a database-expensive property (related_spam in the example) is called. In the example, I use cached_spam to save queries. I put print statements when setting and when getting values so that I could test it out. I tested it...
[ "Nothing wrong with your code, as far as it goes. The problem probably isn't there, but in how you use that code.\nThe main thing to realise is that model instances don't have identity. That means that if you instantiate an Egg object somewhere, and a different one somewhere else, even if they refer to the same und...
[ 9, 1 ]
[]
[]
[ "attributes", "caching", "django", "properties", "python" ]
stackoverflow_0004289064_attributes_caching_django_properties_python.txt
Q: Make a form from models using ModelForm, Models have many Foreignkeys( one class is the foreign key for the other.) I wanted to make a form which should be showing all the fields defined in models, wether the fields include a foreign key to some other class in the models. I am using ModelForm to generate forms. My...
Make a form from models using ModelForm, Models have many Foreignkeys( one class is the foreign key for the other.)
I wanted to make a form which should be showing all the fields defined in models, wether the fields include a foreign key to some other class in the models. I am using ModelForm to generate forms. My models look like class Employee(Person): nickname = models.CharField(_('nickname'), max_length=25, null=True, bl...
[ "Here is the documentation...\nBasic usage is:\nclass EmployeeForm(ModelForm):\n class Meta:\n model = Employee\n fields = ('somefield','otherfield')\n\netc...\nfields is a optional argument, used for defining witch fields will be presented on the form... You can also override some fields using the...
[ 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0004291285_django_forms_python.txt
Q: How to go up in a python loop with for In other languages for(i=0; i<10; i++){ if(...){ i = 4; } } the loop will go up, but in python,it doesn't work for i in range(1, 11): if ...: i = 4 So can I go up in a loop with 'for'? A: One possibility is that you want to skip items. Everyth...
How to go up in a python loop with for
In other languages for(i=0; i<10; i++){ if(...){ i = 4; } } the loop will go up, but in python,it doesn't work for i in range(1, 11): if ...: i = 4 So can I go up in a loop with 'for'?
[ "One possibility is that you want to skip items. Everything to do with looping over an index is ugly but here's a way to do that with a while loop.\ni = 1\nwhile i < 11:\n if predicate(i):\n i = 4\n i += 1\n\n\nIt's better to loop over items of the list that you want to work with directly and just ski...
[ 8, 5, 5, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004290399_python.txt
Q: is there any simple way to make the python raw_input UI more like the bash UI? i am using raw_input() in a script to take a user input which needs to refined iteratively. is there any way simple way to give it the familiar cursor functionality enabling cursor and (ideally) mouse support so that the left and right ...
is there any simple way to make the python raw_input UI more like the bash UI?
i am using raw_input() in a script to take a user input which needs to refined iteratively. is there any way simple way to give it the familiar cursor functionality enabling cursor and (ideally) mouse support so that the left and right cursors scroll along the string and the up cursor brings up the previous entry? than...
[ "You could make use of the readline module.\n", "you can benefit from bash-like history-list editing by wrapping cmd module.\nhttp://docs.python.org/library/cmd.html\n" ]
[ 2, 0 ]
[]
[]
[ "linux", "python", "raw_input", "user_interface" ]
stackoverflow_0004291437_linux_python_raw_input_user_interface.txt
Q: Sorting items using user-defined rule For instance, if I have a list of usernames, lets call this list L1, each username has his/her own profile (not stored in the L1). How should we write the function so that it will sort the usernames based on their actual name, if any usernames are tied for actual name, sort th...
Sorting items using user-defined rule
For instance, if I have a list of usernames, lets call this list L1, each username has his/her own profile (not stored in the L1). How should we write the function so that it will sort the usernames based on their actual name, if any usernames are tied for actual name, sort them by usernames. Note, I can get the userna...
[ "You can always store the user names in a list, and then use the builtin sorted() function to make a sorted list of user names. Example:\nusers = ['Guido', 'Alex', 'Jack', 'Brian']\nusers_sorted = sorted(users)\nprint repr(users_sorted)\n\nThe result of this would be the list of users sorted alphabetically:\n['Alex...
[ 3, 2, 2, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004290206_python_sorting.txt
Q: Windows live api for python I have read documentation about Windows Live API: http://msdn.microsoft.com/en-us/library/bb463989.aspx But how can I retrieve contacts from hotmail with python ? Is there any example ? A: Your program will first need to obtain "delegated authentication", for which the Python samples ...
Windows live api for python
I have read documentation about Windows Live API: http://msdn.microsoft.com/en-us/library/bb463989.aspx But how can I retrieve contacts from hotmail with python ? Is there any example ?
[ "Your program will first need to obtain \"delegated authentication\", for which the Python samples are here.\nAfter that, the interface is REST-like: you only need to HTTP GET the appropriate URI (per the docs, that's '/LiveContacts/contacts' to retrieve all contacts. The REST Schema is documented here. You can m...
[ 4, 0 ]
[]
[]
[ "hotmail", "python" ]
stackoverflow_0002166232_hotmail_python.txt
Q: Decomposition and decoding of nested dictionary/json In my app I'm connecting to a server which returns some json style unicode string resembling dictionary of dictionaries. As a result I'd like to get one leveled dictionary with id as a key and unicode value like this : {'1': u'autos','3': u'cities'} So I load th...
Decomposition and decoding of nested dictionary/json
In my app I'm connecting to a server which returns some json style unicode string resembling dictionary of dictionaries. As a result I'd like to get one leveled dictionary with id as a key and unicode value like this : {'1': u'autos','3': u'cities'} So I load the response with built in json module : >>> jsonData = json...
[ "This should work:\noutputdata = {}\nfor id, stuff in jsonData.iteritems():\n outputdata[id.encode(\"ascii\")] = stuff[u\"name\"]\n\nYou could also use a generator expression, as in dugres' answer.\n", "decomp=dict((v['id'], v['name']) for v in jsondata.values())\n\n" ]
[ 2, 0 ]
[]
[]
[ "decomposition", "dictionary", "encoding", "json", "python" ]
stackoverflow_0004291704_decomposition_dictionary_encoding_json_python.txt
Q: Python hangs with Qt bindings I have a 2.6 python installed with latest PySide Qt bindings. The following code hands if thread.start() line is uncommented. Anyone can suggest what i'm doing wrong? from PySide.QtCore import * from PySide.QtGui import * import sys app = QApplication( sys.argv ) window = QWidget() w...
Python hangs with Qt bindings
I have a 2.6 python installed with latest PySide Qt bindings. The following code hands if thread.start() line is uncommented. Anyone can suggest what i'm doing wrong? from PySide.QtCore import * from PySide.QtGui import * import sys app = QApplication( sys.argv ) window = QWidget() window.show() thread = QThread() # t...
[ "It'a a known PySide bug. The workaround is to subclass QThread and define run() method that calls exec_()\n" ]
[ 1 ]
[]
[]
[ "pyside", "python", "qt" ]
stackoverflow_0004215406_pyside_python_qt.txt
Q: Server Error (Google Apps Engine) when executing custom bulkloader I had not succeeded in using the bulkloader option that is officially provided, so i wrote my own bulkloader script (actually post handler that would incrementally load entities from csv into the datastore). The solution worked as follows: 1. I wou...
Server Error (Google Apps Engine) when executing custom bulkloader
I had not succeeded in using the bulkloader option that is officially provided, so i wrote my own bulkloader script (actually post handler that would incrementally load entities from csv into the datastore). The solution worked as follows: 1. I would copy data from a csv file 2. Paste it into a text area in a form on t...
[ "This is a known issue: Python dev SDK 1.3.8 datastore_file_stub.py appears to leak file handles.\nThere's an unofficial patch available.\n" ]
[ 0 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0004291014_bulkloader_google_app_engine_python.txt
Q: Send Email in Django without SMTP server. Like php mail() function does As far as I read, Django only supports sending mails using SMTP. I would like to send Emails from my script in Django, but do not want to setup SMTP server (it's too complex for me, I'm a linux newbie). Is it possible, to send mails in Django ...
Send Email in Django without SMTP server. Like php mail() function does
As far as I read, Django only supports sending mails using SMTP. I would like to send Emails from my script in Django, but do not want to setup SMTP server (it's too complex for me, I'm a linux newbie). Is it possible, to send mails in Django in the same way like I do it in PHP, without providing SMTP login, password a...
[ "PHP uses sendmail on UNIX system to send emails. I guess at some point when you set up the system, this is, sendmail is configured.\nThere is an API to sendmail for Python, maybe it helps you. But there is a SMTP server involved in any case ;)\n", "Postfix and Exim were built to deal with all of the problems ass...
[ 6, 3, 2, 2 ]
[ "I suppose since you're using Django you're fine with Python in general. There's a new Python MTA evolving which looks very promising http://lamsonproject.org/docs/hooking_into_django.html\n" ]
[ -1 ]
[ "django", "email", "python" ]
stackoverflow_0002335384_django_email_python.txt
Q: Django sending email In PHP I can send an email simply by calling mail(). In Django, I need to specify SMTP backends and other things. Is there a simpler way to send email from Django? A: There are several good mail-sending functions in the django.core.mail module. For a tutorial please see Sending e-mail: Alt...
Django sending email
In PHP I can send an email simply by calling mail(). In Django, I need to specify SMTP backends and other things. Is there a simpler way to send email from Django?
[ "There are several good mail-sending functions in the django.core.mail module.\nFor a tutorial please see Sending e-mail:\n\nAlthough Python makes sending e-mail\n relatively easy via the smtplib\n library, Django provides a couple of\n light wrappers over it. These wrappers\n are provided to make sending e-mai...
[ 3, 2, 0 ]
[]
[]
[ "django", "email", "python" ]
stackoverflow_0001963650_django_email_python.txt
Q: How to get a list of file extensions for a general file type? I am trying to get a list of file extensions based upon the first part of a MIME type using the mimetypes module. eg. 'image' is the first part of 'image/jpeg', 'image/png' etc. This is my code: import mimetypes def get_extensions_for_type(general_type...
How to get a list of file extensions for a general file type?
I am trying to get a list of file extensions based upon the first part of a MIME type using the mimetypes module. eg. 'image' is the first part of 'image/jpeg', 'image/png' etc. This is my code: import mimetypes def get_extensions_for_type(general_type): for ext in mimetypes.types_map: if mimetypes.types_m...
[ "I found the solution:\nuse:\nmimetypes.init()\n\nafter importing the module.\nThis reads additional mime types from the operating system. (see python documentation)\n" ]
[ 6 ]
[]
[]
[ "iterator", "mime_types", "python" ]
stackoverflow_0004292029_iterator_mime_types_python.txt
Q: How to proceed with this python program I'm trying to get acquainted with python. Thought I'd solve that camel puzzle. This is the code I have so far. I have couple of problems now: fCamel = 'F' bCamel = 'B' gap = 'G' def solution(formation): return len([i for i in formation[formation.index(fCamel) + 1:] if i...
How to proceed with this python program
I'm trying to get acquainted with python. Thought I'd solve that camel puzzle. This is the code I have so far. I have couple of problems now: fCamel = 'F' bCamel = 'B' gap = 'G' def solution(formation): return len([i for i in formation[formation.index(fCamel) + 1:] if i == bCamel]) == 0 def heuristic(formation): ...
[ "\nI need to have 3 more data fields along with a formation. g = current distance, f = total value (heuristic value + g), p = parent. How to make a structure including all these?\n\nYou should use a class to represent a formation:\nclass Formation(object):\n \"\"\"A formation of camels.\"\"\"\n def __init__(s...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004291843_python.txt
Q: Fitting data to distributions? I am not a statistician (more of a researchy web developer) but I've been hearing a lot about scipy and R these days. So out of curiosity I wanted to ask this question (though it might sound silly to the experts around here) because I am not sure of the advances in this area and want...
Fitting data to distributions?
I am not a statistician (more of a researchy web developer) but I've been hearing a lot about scipy and R these days. So out of curiosity I wanted to ask this question (though it might sound silly to the experts around here) because I am not sure of the advances in this area and want to know how people without a sound ...
[ "This is a complicated question, and there are no perfect answers. I'll try to give you an overview of the major concepts, and point you in the direction of some useful reading on the topic. \nAssume that you a one dimensional set of data, and you have a finite set of probability distribution functions that you thi...
[ 39, 11, 6, 3, 3 ]
[ "For what it's worth, it seems like you might want to look at the Poisson distribution.\n" ]
[ -4 ]
[ "python", "r", "scipy", "statistics" ]
stackoverflow_0004290081_python_r_scipy_statistics.txt
Q: python: how binding works I am trying to understand, how exactly variable binding in python works. Let's look at this: def foo(x): def bar(): print y return bar y = 5 bar = foo(2) bar() This prints 5 which seems reasonable to me. def foo(x): def bar(): print x return bar x = 5 bar...
python: how binding works
I am trying to understand, how exactly variable binding in python works. Let's look at this: def foo(x): def bar(): print y return bar y = 5 bar = foo(2) bar() This prints 5 which seems reasonable to me. def foo(x): def bar(): print x return bar x = 5 bar = foo(2) bar() This prints 2,...
[ "The second example implements what is called a closure. The function bar is referencing the variable x from its surrounding context, i.e. the function foo. This precedes the reference to the global variable x.\nSee also this question Can you explain closures (as they relate to Python)?\n", "The issue that you ar...
[ 7, 7, 1, 0, 0 ]
[]
[]
[ "closures", "nested_function", "python" ]
stackoverflow_0004292304_closures_nested_function_python.txt
Q: Django: when trying domain.com/admin gives 404 with an old unexisting urls file I had at some point an urls file that looked like that: # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: url(r'^$', 'girls.views.home', nam...
Django: when trying domain.com/admin gives 404 with an old unexisting urls file
I had at some point an urls file that looked like that: # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: url(r'^$', 'girls.views.home', name = 'home'), url(r'^registerasboy$', 'girls.views.regb', name= 'regb'), #url(r'^regi...
[ "Just a shot in the dark: \nDid you add the admin in your INSTALLED_APPS, do a syncdb and restarted the server ?\nRestarting the server is useful if you use Apache with mod_wsgi. It does not detect the changes in the code so you need to reload it manually.\nThe development server reloads code automatically.\nHere i...
[ 2 ]
[]
[]
[ "django", "python", "settings", "url" ]
stackoverflow_0004292382_django_python_settings_url.txt
Q: Dynamic forms in django-admin I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object. I have something like this: class ClassifiedsAdminForm(forms.ModelForm): def __init__(self,*args, **kwargs): super(ClassifiedsAdminForm, self).__init__(*args, **kwargs) ...
Dynamic forms in django-admin
I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object. I have something like this: class ClassifiedsAdminForm(forms.ModelForm): def __init__(self,*args, **kwargs): super(ClassifiedsAdminForm, self).__init__(*args, **kwargs) self.fields['testujemy'] = fo...
[ "I've managed to do it using type().\nclass ClassifiedAdmin(admin.ModelAdmin):\n\n def get_form(self, request, obj=None, **kwargs):\n\n adminform = ClassifiedsAdminForm()\n fields = adminform.getNewFields()\n\n form = type('ClassifiedsAdminForm', (forms.ModelForm,), fields)\n\n return form\n\nHope it wi...
[ 8 ]
[]
[]
[ "django", "django_admin", "django_forms", "python" ]
stackoverflow_0004291516_django_django_admin_django_forms_python.txt
Q: Which is more Efficient? regex on long string or list I'm using regex to look for matches. Is it more efficient to use it on a long string or that same string broken up into a list? For Example mystring = "asdfl;jkasdfj;ldj;lj;dlskjfasdfjkl; ;lj ;lf ak;lkjf al;kjdlkjsdl;fkja;dlkjf a;lsdf" OR mylist = ["asdfl;jka...
Which is more Efficient? regex on long string or list
I'm using regex to look for matches. Is it more efficient to use it on a long string or that same string broken up into a list? For Example mystring = "asdfl;jkasdfj;ldj;lj;dlskjfasdfjkl; ;lj ;lf ak;lkjf al;kjdlkjsdl;fkja;dlkjf a;lsdf" OR mylist = ["asdfl;jkasdfj;ldj;lj;dlskjfasdfjkl;",";lj", ";lf ak;lkjf","al;kjdlkj...
[ "The simpler and more efficient way, because of how the re module is written, is to use the regex on the string. This isn't definitively faster, but it's far more efficient because it's easier to code, easier to maintain, and makes better use of Python's included batteries.\nre is optimized for long strings, not li...
[ 5, 3, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004292694_python_regex.txt
Q: Backspace trouble Why this my Python clock runs only from Python2, Python3 does nothing. from __future__ import print_function import time wipe = '\b'*len(time.asctime()) print("The current date and time are: "+' '*len(wipe), end='') while True: print(wipe+time.asctime(), end='') time.sleep(1) A: In Pyth...
Backspace trouble
Why this my Python clock runs only from Python2, Python3 does nothing. from __future__ import print_function import time wipe = '\b'*len(time.asctime()) print("The current date and time are: "+' '*len(wipe), end='') while True: print(wipe+time.asctime(), end='') time.sleep(1)
[ "In Python 3, you need to flush the print buffer to force the characters to be written to the screen.\nAdd\nimport sys\n\nto the start of your script and change the loop to\nwhile True:\n print(wipe+time.asctime(), end='')\n sys.stdout.flush()\n time.sleep(1)\n\n", "The problem is not with the python ver...
[ 4, 1 ]
[]
[]
[ "console_application", "python", "python_3.x" ]
stackoverflow_0004293101_console_application_python_python_3.x.txt
Q: One-to-many relationships in datastore There is a nice explanation of 1-to-many relationships in datastore here by Rafe Kaplan. I tried to adapt that to a simpler case of User and Venue. So user can go to many restaurants; and I want to print the user email and the restaurants the user went to: class User(db.Model...
One-to-many relationships in datastore
There is a nice explanation of 1-to-many relationships in datastore here by Rafe Kaplan. I tried to adapt that to a simpler case of User and Venue. So user can go to many restaurants; and I want to print the user email and the restaurants the user went to: class User(db.Model): userEmail = db.StringProperty() clas...
[ "userEmail is not a defined name in the scope of the for loop. What you need is:\nfor v in scott.venues:\n self.response.out.write(scott.userEmail)\n self.response.out.write(v.venue)\n\nEDIT: Concerning your edit - if your goal is to make a joined query - you can't, not with the google app datastore. However,...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "one_to_many", "python" ]
stackoverflow_0004293191_google_app_engine_google_cloud_datastore_one_to_many_python.txt
Q: Python process keeps growing in django db upload script I'm running a conversion script that commits large amounts of data to a db using Django's ORM. I use manual commit to speed up the process. I have hundreds of files to to commit, each file will create more than a million objects. I'm using Windows 7 64bit. I ...
Python process keeps growing in django db upload script
I'm running a conversion script that commits large amounts of data to a db using Django's ORM. I use manual commit to speed up the process. I have hundreds of files to to commit, each file will create more than a million objects. I'm using Windows 7 64bit. I noticed the Python process keeps growing until it consumes mo...
[ "First thing, make sure DEBUG=False in your settings.py. All queries sent to the database are stored in django.db.connection.queries when DEBUG=True. This will turn into a large amount of memory if you import many records. You can check it via the shell:\n$ ./manage.py shell\n> from django.conf import settings\n...
[ 3, 0 ]
[]
[]
[ "django", "memory_management", "python", "windows" ]
stackoverflow_0004292963_django_memory_management_python_windows.txt
Q: Is there any merit to a web developer learning C? I have been working as a web dev with C#, VB and PHP (now learning python).. I have been considering learning C (as a right of passage) because i hate feeling stupid =P Apart from making me a better programmer in general.. Is there any particualr use to C for a Web...
Is there any merit to a web developer learning C?
I have been working as a web dev with C#, VB and PHP (now learning python).. I have been considering learning C (as a right of passage) because i hate feeling stupid =P Apart from making me a better programmer in general.. Is there any particualr use to C for a Web Dev in 2010? Thanks, Daniel
[ "Learning C (or, for the added fun, C++) as a device of increasing your understanding of programming is a good idea IMHO. But it doesn't have anything to offer you as regards web development.\n", "You always need to know enough c to port headers to your language of choice when there are no ports for a library you...
[ 4, 2, 2, 1, 0, 0 ]
[]
[]
[ "c", "c#", "python" ]
stackoverflow_0004291401_c_c#_python.txt
Q: Is there a way in python3 to check for more than one thing? Like, for example: pie = 1 if pie == 1 OR 2: print("pie is either 1 or 2!") else: print("pie is not 1 or 2!") Except you know, something that actually has the intended effect. Because that doesn't work. :P A: Same way as in 2.x. if pie in (1, 2): ...
Is there a way in python3 to check for more than one thing?
Like, for example: pie = 1 if pie == 1 OR 2: print("pie is either 1 or 2!") else: print("pie is not 1 or 2!") Except you know, something that actually has the intended effect. Because that doesn't work. :P
[ "Same way as in 2.x.\nif pie in (1, 2):\n ...\n\n", "if pie == 1 or pie == 2\n...\nif pie in (1, 2)\n...\n\n" ]
[ 3, 3 ]
[]
[]
[ "if_statement", "python", "python_3.x", "variables" ]
stackoverflow_0004293364_if_statement_python_python_3.x_variables.txt
Q: Django: Define a form differently when in testing mode I have a customized captcha field. I want to remove that field from a form when displaying it during tests. My initial thought was to have a TESTING variable in a separate settings file that will be supplied as an argument to the test runner command. Then, I c...
Django: Define a form differently when in testing mode
I have a customized captcha field. I want to remove that field from a form when displaying it during tests. My initial thought was to have a TESTING variable in a separate settings file that will be supplied as an argument to the test runner command. Then, I could to something like: class CaptchaForm(forms.Form): n...
[ "You can disable captcha in constructor of unit-testing class. Like this:\nclass MyTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(MyTest, self).__init__(*args, **kwargs)\n settings.TESTING = True\n\nOr you can disable captcha field validation in this constructor, for exam...
[ 2, 0 ]
[]
[]
[ "captcha", "django", "django_forms", "python", "testing" ]
stackoverflow_0004292398_captcha_django_django_forms_python_testing.txt
Q: Id's of immutable types I'm a little confused about the distinction between mutable and immutable objects. I tried the following chunk of code to find the id's of objects: tuple1 = ('Object1', 'Object2') print id(tuple1) tuple2 = ('Object1', 'Object2') print id(tuple2) list1 = ['Object1', 'Object2'] print id(list1...
Id's of immutable types
I'm a little confused about the distinction between mutable and immutable objects. I tried the following chunk of code to find the id's of objects: tuple1 = ('Object1', 'Object2') print id(tuple1) tuple2 = ('Object1', 'Object2') print id(tuple2) list1 = ['Object1', 'Object2'] print id(list1) list2 = ['Object1', 'Object...
[ "Same IDs means the exact same object, but an implementation of Python is free to optimize the creation of immutable objects as it pleases. For example, in CPython 2.6.6 small integer objects are cached, so:\n>>> x=256\n>>> x is 256\nTrue\n>>> x=1024\n>>> x is 1024\nFalse\n\n[NOTE: 'is' tests for object identity (...
[ 5, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004293408_python.txt
Q: How can you remove the new line characters in python? I am writing a vcf parser and I have the file open but now I need to parse their first name. The file shows "FN:John Smith;;;\n\r" I want to take out the \n and \r. Can anybody help me? A: Use the rstrip function: s = s.rstrip() This will remove all whitespa...
How can you remove the new line characters in python?
I am writing a vcf parser and I have the file open but now I need to parse their first name. The file shows "FN:John Smith;;;\n\r" I want to take out the \n and \r. Can anybody help me?
[ "Use the rstrip function:\ns = s.rstrip()\n\nThis will remove all whitespace from the end of your string.\n", "If as you say the file shows \"FN:John Smith;;;\\n\\r\", then you have a problem -- that \\r is totally unexpected.\nWhat operating system are you using, what version of Python, and exactly how did you d...
[ 12, 1 ]
[]
[]
[ "newline", "python" ]
stackoverflow_0004292113_newline_python.txt
Q: Can I call Perl from within python? I have searched a lot and I have understood that there exists inline::Python for putting in python code within Perl.. But I am looking for some means by which I can access modules and functions written in Perl by not writing any Perl code, through a python code. Maybe, I am aski...
Can I call Perl from within python?
I have searched a lot and I have understood that there exists inline::Python for putting in python code within Perl.. But I am looking for some means by which I can access modules and functions written in Perl by not writing any Perl code, through a python code. Maybe, I am asking for too much?
[ "I believe this is the sort of thing that the Parrot project aims to allow. It's a VM that's supposed to be able to run various dynamic languages, including Python and Perl. I've no idea how ready it is for real use, though, and I've never seen any instructions for people wanting to use Parrot, rather than develop ...
[ 6, 0 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0004293841_perl_python.txt
Q: Using scp to transfer a single file into a remote folder that doesn't exist I'm working on a python script that monitors a directory and uploads files that have been created or modified using scp. That's fine, except I want this to be done recursively, and I'm having a problem if a user creates a directory in the ...
Using scp to transfer a single file into a remote folder that doesn't exist
I'm working on a python script that monitors a directory and uploads files that have been created or modified using scp. That's fine, except I want this to be done recursively, and I'm having a problem if a user creates a directory in the watch directory, and then modifies a file inside that new directory. I can detect...
[ "Since you have ssh, can't you just create the directory first? For example, given a file with absolute path /some/path/file.txt, issue a mkdir -p /home/path before uploading file.txt.\nUPDATE: If you're looking to lower the number of transactions, a better method might be to make a tar file locally, transfer tha...
[ 2, 1, 0 ]
[]
[]
[ "python", "scp" ]
stackoverflow_0003693666_python_scp.txt
Q: Problem Dynamically Drawing to Tkinter Canvas Object One question: How do you dynamically draw to a Tkinter Canvas object from a button click? This topic was posted originally by user339860 (see 1) as a two part question, but the second portion of the question has not yet been addressed. I'm experiencing the same...
Problem Dynamically Drawing to Tkinter Canvas Object
One question: How do you dynamically draw to a Tkinter Canvas object from a button click? This topic was posted originally by user339860 (see 1) as a two part question, but the second portion of the question has not yet been addressed. I'm experiencing the same problem, specifically I cannot draw to a Canvas object fr...
[ "This is a Python problem, not a tkinter one. You have defined local variables inside createWidgets, but you haven't set them as instance attributes. You need to use self.foo for that:\n>>> class Foo:\n... def __init__(self):\n... bar = \"baz\"\n...\n>>> class Bar:\n... def __init__(self):\n... ...
[ 2, 1 ]
[]
[]
[ "python", "tkinter_canvas" ]
stackoverflow_0004293307_python_tkinter_canvas.txt
Q: Python sort items by specific defined rule say i have a dict: d = {'Abc':5,'Jack':4,'amy':9,'Tom':0,'abc':5} If i want to write a function such that if i pass that function to the built-in sort function, eg. list(d).sort(function), the sort function will sort the list based on the values, of any have identical val...
Python sort items by specific defined rule
say i have a dict: d = {'Abc':5,'Jack':4,'amy':9,'Tom':0,'abc':5} If i want to write a function such that if i pass that function to the built-in sort function, eg. list(d).sort(function), the sort function will sort the list based on the values, of any have identical values, sort them by their keys(alphabetical order)...
[ "[k for k, v in sorted(d.iteritems(), key=lambda x: (-x[1], x[0].lower()))]\n\nEDIT:\n(I refuse to use the name \"dict\" since it shadows a builtin, and shadowing builtins is stupid)\nL1.sort(key=lambda x: (-d.get(x, 0), x.lower()))\n\n", "You can't achieve this with list(d).sort(function), because you'll get a l...
[ 3, 1 ]
[]
[]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0004293989_dictionary_list_python_sorting.txt
Q: Import code directly into script with Python? I'm developing a PyQT4 application, and it's getting pretty hard for me to navigate through all of the code at once. I know of the import foo statement, but I can't figure out how to make it import a chunk of code directly into my script, like the BASH source foo state...
Import code directly into script with Python?
I'm developing a PyQT4 application, and it's getting pretty hard for me to navigate through all of the code at once. I know of the import foo statement, but I can't figure out how to make it import a chunk of code directly into my script, like the BASH source foo statement. I'm trying to do this: # File 'functions.py' ...
[ "For some reason, my first thought was multiple inheritance. But why not try normal inheritance?\nclass foo(functions.foo):\n # All of the methods that you want to add go here.\n\nIs there some reason that this wont work?\n\nSince you just want to merge class definitions, why don't you do:\n# main.py\nimport fun...
[ 4, 3, 0 ]
[]
[]
[ "class", "import", "include", "merge", "python" ]
stackoverflow_0004294266_class_import_include_merge_python.txt
Q: operating on embedded tuples/strings, python say I have a tagged text (word, tag) in tuple format. i want to convert it to a string in order to make some changes to the tags. my function below only sees the last sentence in the text, i guess there is some obvious and stupid mistake which i cant realize, so plz he...
operating on embedded tuples/strings, python
say I have a tagged text (word, tag) in tuple format. i want to convert it to a string in order to make some changes to the tags. my function below only sees the last sentence in the text, i guess there is some obvious and stupid mistake which i cant realize, so plz help to make it work on the entire text. >>> import ...
[ ">>> ' '.join(' '.join(nltk.tag.tuple2str(item) for item in sent) for sent in tpl)\n'This/V is/V one/NUM sentence/NN ./. And/CNJ This/V is/V another/DET one/NUM'\n\nEDIT:\nIf you want this to be reversible then just don't do the outer join.\n>>> [' '.join([nltk.tag.tuple2str(item) for item in sent]) for sent in tpl...
[ 3 ]
[]
[]
[ "nltk", "python", "string", "tuples" ]
stackoverflow_0004294474_nltk_python_string_tuples.txt
Q: How to query datastore when using ReferenceProperty? I am trying to understand the 1-to-many relationships in datastore; but I fail to understand how query and update the record of a user when the model includes ReferenceProperty. Say I have this model: class User(db.Model): userEmail = db.StringProperty() ...
How to query datastore when using ReferenceProperty?
I am trying to understand the 1-to-many relationships in datastore; but I fail to understand how query and update the record of a user when the model includes ReferenceProperty. Say I have this model: class User(db.Model): userEmail = db.StringProperty() userScore = db.IntegerProperty(default=0) class Comment(...
[ "The snippet you posted is doing this (see comments):\nq = User.all() # prepare User table for querying\nq.filter(\"userEmail =\", \"az@example.com\") # apply filter, email lookup \n - this is a simple where clause\nresults = q.fetch(1) # execute the query, apply limit ...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "one_to_many", "python" ]
stackoverflow_0004294562_google_app_engine_google_cloud_datastore_one_to_many_python.txt
Q: I know Perl 5. What are the advantages of learning Perl 6, rather than moving to Python? Coming from a Perl 5 background, what are the advantages of moving to Perl 6 or Python? A: There is no advantage to be gained by switching from Perl to Python. There is also no advantage to be gained by switching from Python...
I know Perl 5. What are the advantages of learning Perl 6, rather than moving to Python?
Coming from a Perl 5 background, what are the advantages of moving to Perl 6 or Python?
[ "There is no advantage to be gained by switching from Perl to Python. There is also no advantage to be gained by switching from Python to Perl. They are both equally capable. Choose your tools based on what you know and the problem you are trying to solve rather than on some sort of notion that one is somehow inher...
[ 25, 14, 11, 8, 6, 5, 4, 4 ]
[]
[]
[ "perl", "python", "raku" ]
stackoverflow_0000124604_perl_python_raku.txt
Q: Reliably force Return-Path with Python I'm a Python junior, so keep that in mind. In a Python script, I need to set a Return-Path address that is different than the sender's address. (I'm using Gmail as SMTP server.) I've done lots of searching on this question and found plenty of "answers", but no solutions. I tr...
Reliably force Return-Path with Python
I'm a Python junior, so keep that in mind. In a Python script, I need to set a Return-Path address that is different than the sender's address. (I'm using Gmail as SMTP server.) I've done lots of searching on this question and found plenty of "answers", but no solutions. I tried this link Setting Return-Path with Pytho...
[ "Reply-to and return path are two distinct beasts. See the RFC.\nYou can set Reply-to with:\nmsg['reply-to'] = 'smith@acme.com'\n\nThe return-path is set by the MTA to the address that receives bounces. It is controlled by the server administrator, so unless you work for Google I don't think this is under your cont...
[ 6 ]
[]
[]
[ "email", "python", "smtplib" ]
stackoverflow_0004294700_email_python_smtplib.txt
Q: Python file.write() taking two tries? not sure how to explain this, any help will be appreciated! Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2, pynotify, tempfile, os >>> opener = urllib2.build_ope...
Python file.write() taking two tries?
not sure how to explain this, any help will be appreciated! Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2, pynotify, tempfile, os >>> opener = urllib2.build_opener() >>> page = opener.open('http://img.yo...
[ "If you open the thumb file, you'll see that there's one whole copy and a partial copy of the data that you are writing in it.\nflush the file instead of writing a second time. \ntemp.flush()\n\nThe file wasn't writing the first time because the contents aren't large enough to fill the buffer. The second write over...
[ 10, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0004294781_file_io_python.txt
Q: Python - Fill and submit a HTML Form I would like to fill in and submit a form on a web page using python. The form I want to interact with has several drop down boxes which are filled using JavaScript. I have looked at the mechanize library but it doesn't handle JavaScript. Can you suggest an alternate library/me...
Python - Fill and submit a HTML Form
I would like to fill in and submit a form on a web page using python. The form I want to interact with has several drop down boxes which are filled using JavaScript. I have looked at the mechanize library but it doesn't handle JavaScript. Can you suggest an alternate library/method for interacting with the form? Cheers...
[ "\nSelenium RC or Windmill (http://www.getwindmill.com/)\nExamine the form's returned GET or POST values;\nuse urllib2 to submit synthesized requests directly.\n\n", "The form effectively sends information back to the server (or maybe somewhere else) after you press the submit button. \nI don't know how you would...
[ 3, 0 ]
[]
[]
[ "forms", "html", "javascript", "python", "submit" ]
stackoverflow_0004294487_forms_html_javascript_python_submit.txt
Q: Jinja2 compile extension after includes In Jinja2, is it possible to have a Node from the AST render after all include statements have completed? This is a key piece of a solution to a bigger puzzle. Example code: x.py from jinja2 import nodes, Environment, FileSystemLoader from jinja2.ext import Extension class ...
Jinja2 compile extension after includes
In Jinja2, is it possible to have a Node from the AST render after all include statements have completed? This is a key piece of a solution to a bigger puzzle. Example code: x.py from jinja2 import nodes, Environment, FileSystemLoader from jinja2.ext import Extension class XExtension(Extension): tags = set(['x', '...
[ "Jinja2 does streaming of template data. The template is evaluated instruction for instruction into a stream of smaller strings that gets concatenated into an actual unicode string by the render() method. However you can also get hold of the stream by calling into generate() instead of render().\nWith some in-ban...
[ 3 ]
[]
[]
[ "jinja2", "python", "templates" ]
stackoverflow_0004294837_jinja2_python_templates.txt
Q: Extracting the introduction part of a Wikipedia article, by python I want to extract the introduction part of a wikipedia article(ignoring all other stuff, including tables, images and other parts). I looked at html source of the articles, but I don't see any special tag which this part is wrapped in. Can anyone g...
Extracting the introduction part of a Wikipedia article, by python
I want to extract the introduction part of a wikipedia article(ignoring all other stuff, including tables, images and other parts). I looked at html source of the articles, but I don't see any special tag which this part is wrapped in. Can anyone give me a quick solution to this? I'm writing python scripts. thanks
[ "\nYou may want to check mwlib to parse the wikipedia source\nAlternatively, use the wikidump lib\nHTML screen scraping through BeautifulSoup\n\nAh, there is a question already on SO on this topic: \n\nParsing a Wikipedia dump\nHow to parse/extract data from a mediawiki marked-up article via python\n\n", "I think...
[ 3, 0 ]
[]
[]
[ "html_content_extraction", "python" ]
stackoverflow_0004295029_html_content_extraction_python.txt
Q: Limited deep copy of an instance with a container of containers as an attribute I have a class whose instances have attributes that are containers which themselves contain containers, each containing many items has an expensive initialization of these containers I want to create copies of instances such that ...
Limited deep copy of an instance with a container of containers as an attribute
I have a class whose instances have attributes that are containers which themselves contain containers, each containing many items has an expensive initialization of these containers I want to create copies of instances such that the container attributes are copied, rather than shared as references, but the contai...
[ "A class is a callable. When you call SetDict(3), SetDict.__call__ first calls the constructor SetDict.__new__(SetDict) and then calls the initializer __init__(3) on the return value of __new__ if it's an instance of SetDict. So you can get a new instance of SetDict (or any other class) without calling its initiali...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004294480_python.txt
Q: Python - Getting all images from an html file Can someone help me parse a html file to get the links for all the images in the file in python? Preferably with out a 3rd party module... Thanks! A: You can use Beautiful Soup. I know you said without a 3rd party module. However, this is an ideal tool for parsing HT...
Python - Getting all images from an html file
Can someone help me parse a html file to get the links for all the images in the file in python? Preferably with out a 3rd party module... Thanks!
[ "You can use Beautiful Soup. I know you said without a 3rd party module. However, this is an ideal tool for parsing HTML. \nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\npage = BeautifulSoup(urllib2.urlopen(\"http://www.url.com\"))\npage.findAll('img')\n\n", "only using PSL\nfrom html.parser import HTM...
[ 11, 10, 2 ]
[]
[]
[ "image", "python", "urllib" ]
stackoverflow_0004295139_image_python_urllib.txt
Q: how to load a view in main window with pyobjc? I have a window that contains a toolbar with 7 button, the window has a subview empty where they should place the selected view from any button when pressed the light fading pre-loaded. My code example https://github.com/jyr/opentumblr-cocoa/blob/master/DashboardContr...
how to load a view in main window with pyobjc?
I have a window that contains a toolbar with 7 button, the window has a subview empty where they should place the selected view from any button when pressed the light fading pre-loaded. My code example https://github.com/jyr/opentumblr-cocoa/blob/master/DashboardController.py
[ "My solution in https://gist.github.com/718610:\n\"\"\"\nEn una ventana muestra 7 vistas seleccionadas desde una barra de herramientas\n\"\"\"\n\nfrom Foundation import *\nfrom AppKit import *\nimport objc\n\nclass DashboardController (NSViewController):\n\n def show(self):\n self.window = NSWindow.alloc(...
[ 0 ]
[]
[]
[ "cocoa", "pyobjc", "python" ]
stackoverflow_0004241305_cocoa_pyobjc_python.txt
Q: urllib2, Google App Engine, and unicode question Hey guys, I'm just learning google app engine so I'm running into a bunch of problems... My current predicament is this. I have a database, class Website(db.Model): web_address = db.StringProperty() company_name = db.StringProperty() content = db.TextPr...
urllib2, Google App Engine, and unicode question
Hey guys, I'm just learning google app engine so I'm running into a bunch of problems... My current predicament is this. I have a database, class Website(db.Model): web_address = db.StringProperty() company_name = db.StringProperty() content = db.TextProperty() div_section = db.StringProperty() loc...
[ "It would appear that the lines returned from readlines are not unicode strings, but rather byte strings (i.e. instances of str containing potentially non-ASCII characters). These bytes are the raw data received in the HTTP response body, and will represent different strings depending on the encoding used. They nee...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "urllib2" ]
stackoverflow_0004290125_google_app_engine_python_urllib2.txt
Q: Why does re.sub in Python not work correctly on this test case? Try this code. test = ' az z bz z z stuff z z ' re.sub(r'(\W)(z)(\W)', r'\1_\2\3', test) This should replace all stand-alone z's with _z However, the result is: ' az _z bz _z z stuff _z _z ' You see there's a z there that is missing. I theorize th...
Why does re.sub in Python not work correctly on this test case?
Try this code. test = ' az z bz z z stuff z z ' re.sub(r'(\W)(z)(\W)', r'\1_\2\3', test) This should replace all stand-alone z's with _z However, the result is: ' az _z bz _z z stuff _z _z ' You see there's a z there that is missing. I theorize that it's because the grouping can't grab the space between the z's to ...
[ "If your goal is to make sure you only match z when it's a standalone word, use \\b to match word boundaries without actually consuming the whitespace:\n>>> re.sub(r'\\b(z)\\b', r'_\\1', test)\n' az _z bz _z _z stuff _z _z '\n\n", "You want to avoid capturing the whitespace. Try using the 0-width word break \\b,...
[ 7, 5, 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004295591_python_regex.txt
Q: Recursive Linear Search - returns list index I have a function search that search a list ('l') for key and returns True if found and False if not. I want it to return the index of key if found and False if not found but I'm confused on what my return statement should be. Here's my code: def search(l,key): """ ...
Recursive Linear Search - returns list index
I have a function search that search a list ('l') for key and returns True if found and False if not. I want it to return the index of key if found and False if not found but I'm confused on what my return statement should be. Here's my code: def search(l,key): """ locates key in list l. if present, returns lo...
[ "For your base case you just found the item at index 0, right? Return 0.\nif l[0] == key: # base case - first index is key\n return 0\n\nFor your recursive part let's think about what to return. Let's say the item is at index 5. Since we've passed the recursive call a list that's shifted by one element, it's...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0004295608_python_recursion.txt
Q: Few questions on generator expressions and speed efficient alternatives Consider the following code, integral to my questions below: import functools N = 3 class Struct: """Create an instance with argument=value slots. This is for making a lightweight object whose class doesn't matter.""" def __init_...
Few questions on generator expressions and speed efficient alternatives
Consider the following code, integral to my questions below: import functools N = 3 class Struct: """Create an instance with argument=value slots. This is for making a lightweight object whose class doesn't matter.""" def __init__(self, **entries): self.__dict__.update(entries) def __repr__(s...
[ "Q1. [x for x in somelist].sort() creates a list and calls the sort method. This returns None The assignment assigns None to successorSorted. If you want to do this, you'll have to implement it yourself and it will probably be way slower than the builtin sort creating the temporary list.\nQ2. You could take apart t...
[ 2 ]
[]
[]
[ "bytecode_manipulation", "functional_programming", "generator", "lambda", "python" ]
stackoverflow_0004295806_bytecode_manipulation_functional_programming_generator_lambda_python.txt
Q: What's the bottleneck of a TCP2HTTP(urllib) Proxy ThreadingTcpServer in Python I have implmented a TCP to HTTP proxy server using urllib, which converts a TCP request to a HTTP request to a specific server, It's something like this: class RequestHandler(socketserver.BaseRequestHandler): def handle(self): ...
What's the bottleneck of a TCP2HTTP(urllib) Proxy ThreadingTcpServer in Python
I have implmented a TCP to HTTP proxy server using urllib, which converts a TCP request to a HTTP request to a specific server, It's something like this: class RequestHandler(socketserver.BaseRequestHandler): def handle(self): size, = struct.unpack('L', s.recv(4)) data = s.recv(size) assert...
[ "Use profiler, one of: http://docs.python.org/library/profile.html\n" ]
[ 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0004295869_python_urllib.txt
Q: Python Multidimensional Arrays - most efficient way to count number of non-zero entries Hi there on a Saturday Fun Night, I am getting around in python and I am quite enjoying it. Assume I have a python array: x = [1, 0, 0, 1, 3] What is the fastest way to count all non zero elements in the list (ans: 3) ? Also ...
Python Multidimensional Arrays - most efficient way to count number of non-zero entries
Hi there on a Saturday Fun Night, I am getting around in python and I am quite enjoying it. Assume I have a python array: x = [1, 0, 0, 1, 3] What is the fastest way to count all non zero elements in the list (ans: 3) ? Also I would like to do it without for loops if possible - the most succint and terse manner possi...
[ "For the single-dimensional case:\nsum(1 for i in x if i)\n\nFor the multi-dimensional case, you can either nest:\nsum(sum(1 for i in row if i) for row in rows)\n\nor do it all within the one construct:\nsum(1 for row in rows\n for i in row if i)\n\n", "If you are using numpy as suggested by the fact that yo...
[ 12, 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "arrays", "multidimensional_array", "python" ]
stackoverflow_0004294482_arrays_multidimensional_array_python.txt
Q: Having trouble writing a url pattern in django I want to match the following url pattern /posts/tagged/tag-name/ I've tried a few different patterns but Django splits out a 404 because it the url doesn't match any patterns. This is the pattern I pulled from the docs http://www.webmonkey.com/2010/02/use_url_patte...
Having trouble writing a url pattern in django
I want to match the following url pattern /posts/tagged/tag-name/ I've tried a few different patterns but Django splits out a 404 because it the url doesn't match any patterns. This is the pattern I pulled from the docs http://www.webmonkey.com/2010/02/use_url_patterns_and_views_in_django/ (r'^posts/tagged/(?P[-w]+)/...
[ "Try this:\n(r'^posts/tagged/(?P<tag>[-\\w]+)/$', 'blog.view.posts_by_tag')\n\nYour posts_by_tag view will then receive a keyword argument called tag.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0004296341_django_python_regex.txt
Q: Switch gst video to some point in another video on pygtk Button press I'm trying to play a video and have a button that switches the video to a new one, starting the new one at some point other than the beginning. I haven't written much UI or video-related code. I have the following that kind of works (very trimme...
Switch gst video to some point in another video on pygtk Button press
I'm trying to play a video and have a button that switches the video to a new one, starting the new one at some point other than the beginning. I haven't written much UI or video-related code. I have the following that kind of works (very trimmed): class Main(gobject.GObject): def __init__(self): self.player = gs...
[ "Instead of waiting one second, use something like self.player.get_state(timeout=3*gst.SECOND) to wait for the switch to gst.STATE_PAUSED to complete.\nThe timeout is used because if an error occurs and GStreamer doesn't succeed at changing the pipeline state, a get_state without a timeout will just get stuck waiti...
[ 1 ]
[]
[]
[ "gstreamer", "pygtk", "python", "video" ]
stackoverflow_0004198438_gstreamer_pygtk_python_video.txt
Q: when a function embedded in class be the "method" of the class? When this is executed... class A: def b(self, a): print a print dir(b) print dir(A.b) It gives the result: ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__modu...
when a function embedded in class be the "method" of the class?
When this is executed... class A: def b(self, a): print a print dir(b) print dir(A.b) It gives the result: ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr...
[ "In Python 2, the second case returns an unbound method, and the first case a function. From the documentation, emphasis mine:\n\nUser-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined function object, an unbound u...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004296477_python.txt
Q: Clone elements of a list Let's say I have a Python list that looks like this: list = [ a, b, c, d] I am looking for the most efficient way performanse wise to get this: list = [ a, a, a, a, b, b, b, c, c, d ] So if the list is N elements long then the first element is cloned N-1 times, the second element N-2 tim...
Clone elements of a list
Let's say I have a Python list that looks like this: list = [ a, b, c, d] I am looking for the most efficient way performanse wise to get this: list = [ a, a, a, a, b, b, b, c, c, d ] So if the list is N elements long then the first element is cloned N-1 times, the second element N-2 times, and so forth...the last el...
[ "Note that I am testing speed, not correctness. If someone wants to edit in a unit test, I'll get around to it.\npyfunc_fastest: 152.58769989 usecs\npyfunc_local_extend: 154.679298401 usecs\npyfunc_iadd: 158.183312416 usecs\npyfunc_xrange: 162.234091759 usecs\npyfunc: 166.495800018 usecs\nIgnacio: 238.87629509 usec...
[ 5, 4, 3, 2, 2, 1, 1, 0, 0 ]
[ "def gen_indices(list_length):\n for index in range(list_length):\n for _ in range(list_length - index):\n yield index\n\nnew_list = [list[i] for i in gen_indices(len(list))]\n\nuntested but I think it'll work\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0004295467_python.txt
Q: image download problem (python) I was trying to download images with multi-thread, which has a limited max_count in python. Each time a download_thread is started, I leave it alone and activate another one. I hope the download process could be ended in 5s, which means downloading is failed if opening the url costs...
image download problem (python)
I was trying to download images with multi-thread, which has a limited max_count in python. Each time a download_thread is started, I leave it alone and activate another one. I hope the download process could be ended in 5s, which means downloading is failed if opening the url costs more than 5s. But how can I know it ...
[ "Can you tell which version of python you are using?\nMaybe you could have posted a snippet too.\nFrom Python 2.6, you have a timeout added in urllib2.urlopen.\nHope this will help you. It's from the python docs.\n\nurllib2.urlopen(url[, data][,\n timeout]) Open the URL url, which can\n be either a string or a Re...
[ 3 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004295482_multithreading_python.txt
Q: A parser with Lepl I want to parse a text file, for example, something like this: div:: class:yo-d text:example id:my-class h1:: Title href:http://www.example.com div:: class:class1 id:my-class2 It is similar to reStructuredText. Every tag ends with :: and can have some...
A parser with Lepl
I want to parse a text file, for example, something like this: div:: class:yo-d text:example id:my-class h1:: Title href:http://www.example.com div:: class:class1 id:my-class2 It is similar to reStructuredText. Every tag ends with :: and can have some attributes attr:value. ...
[ "An alternative to using Lepl is Pyparsing: https://github.com/pyparsing/pyparsing\nI am currently using Pyparsing successfully, and if you name the results you can get out dictionaries of named results.\n" ]
[ 2 ]
[]
[]
[ "lepl", "parsing", "python" ]
stackoverflow_0004296241_lepl_parsing_python.txt
Q: RTMP: check if stream is online with Python I have several Flash streams and I want to display only active/live/online streams. Can someone provide sample code that can check status of stream? or point out where I can grab it (I think Red5 and RTMPy should have this, but I completely don't have any experience with...
RTMP: check if stream is online with Python
I have several Flash streams and I want to display only active/live/online streams. Can someone provide sample code that can check status of stream? or point out where I can grab it (I think Red5 and RTMPy should have this, but I completely don't have any experience with RTMP; there is also RTMP specification, but wiki...
[ "In case of connection lost or connection fail the code below will print error message.\nfrom twisted.internet import reactor\nfrom rtmpy.client import ClientFactory\n\nreactor.connectTCP('localhost', 1935, ClientFactory())\nreactor.run()\n\n" ]
[ 2 ]
[]
[]
[ "flash", "python", "rtmp" ]
stackoverflow_0004296750_flash_python_rtmp.txt
Q: Python syntax reasoning (why not fall back for . the way django template syntax does?) My karate instructor is fond of saying, "a block is a lock is a throw is a blow." What he means is this: When we come to a technique in a form, although it might seem to look like a block, a little creativity and examination s...
Python syntax reasoning (why not fall back for . the way django template syntax does?)
My karate instructor is fond of saying, "a block is a lock is a throw is a blow." What he means is this: When we come to a technique in a form, although it might seem to look like a block, a little creativity and examination shows that it can also be seen as some kind of joint lock, or some kind of throw, or some kin...
[ "django templates and python are two, unrelated languages. They also have different target audiences. \nIn django templates, the target audience is designers, who proabably don't want to learn 4 different ways of doing roughly the same thing ( a dictionary lookup ). Thus there is a single syntax in django templa...
[ 7, 6, 1, 1, 1 ]
[]
[]
[ "django_templates", "python", "syntax", "types" ]
stackoverflow_0004295384_django_templates_python_syntax_types.txt
Q: Controlling rate of downloads on a per request and/or per resource basis (and providing a first-come-first-serve waiting system) My goal: I want to host a folder of photos, but if at anytime 100 files are being downloaded, I want to redirect a new downloader/request to a 'waiting page' and give them a place in l...
Controlling rate of downloads on a per request and/or per resource basis (and providing a first-come-first-serve waiting system)
My goal: I want to host a folder of photos, but if at anytime 100 files are being downloaded, I want to redirect a new downloader/request to a 'waiting page' and give them a place in line and an approximate countdown clock until its their turn to download their requested content. Then either redirect them directly to...
[ "Twisted network engine is about the best answer for you. What you can have is you can have the downloader serving a maximum of 100 x people then when the queue is full you will direct people to a holding loop, in the holding loop they will wait x seconds, check if queue is full, check not expired, see who else is ...
[ 0 ]
[]
[]
[ "apache", "c#", "nginx", "php", "python" ]
stackoverflow_0004295823_apache_c#_nginx_php_python.txt
Q: Full text search engine for Python I'm searching for a Python full text search engine. I took a look at PyLucense, but I think that using a Java-based library in a Python project is not good. As I understand, Sphinx does not have a Python API. Any ideas ? A: Have you looked at Whoosh? It's pure Python. A: "Sph...
Full text search engine for Python
I'm searching for a Python full text search engine. I took a look at PyLucense, but I think that using a Java-based library in a Python project is not good. As I understand, Sphinx does not have a Python API. Any ideas ?
[ "Have you looked at Whoosh? It's pure Python.\n", "\n\"Sphinx does not have a Python API\"\n\nis not true. Download the release and look at sphinx/api/sphinxapi.py\nI use it myself and I'm pretty happy with it. The documentation is for PHP only but the Python API uses the exact same names for all functions.\n", ...
[ 8, 4, 2, 2, 2, 1 ]
[]
[]
[ "full_text_search", "pylons", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0004297672_full_text_search_pylons_python_sqlalchemy_sqlite.txt
Q: Custom Tag for Hiding Views in Django Is there a custom tag in Django (or written by somebody else) that supports displaying/hiding views based on user roles and permissions? Thanks in Advance! A: What do you mean "hiding" views? Preventing a user from accessing them? Check out the permission_required decorator ...
Custom Tag for Hiding Views in Django
Is there a custom tag in Django (or written by somebody else) that supports displaying/hiding views based on user roles and permissions? Thanks in Advance!
[ "What do you mean \"hiding\" views? Preventing a user from accessing them?\nCheck out the permission_required decorator\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004297991_django_python.txt
Q: Problem with json response in Python REST server I'm writing For my own education I'm creating a simple daemon that will function as a REST server, listening on socket 9000. For my first test I'm trying to do a REST call of simply doing a GET on http://localhost:9000/getsettings.json. The simple server I hacked u...
Problem with json response in Python REST server I'm writing
For my own education I'm creating a simple daemon that will function as a REST server, listening on socket 9000. For my first test I'm trying to do a REST call of simply doing a GET on http://localhost:9000/getsettings.json. The simple server I hacked up gets the request OK, but I think there's a problem with the resp...
[ "You need to return a 200 OK HTTP response and an empty line before sending your content.\nYou'll probably need some HTTP headers, too (Content-type would be an obvious one).\nI would, however, recommend using one of Python's many HTTP libraries instead of implementing the protocol yourself.\n", "Check that the s...
[ 3, 2, 1 ]
[]
[]
[ "ajax", "json", "python" ]
stackoverflow_0004294185_ajax_json_python.txt
Q: using cython to port modules to python 3.1 Is it possible to import arbitrary modules in cython, compile them to shared object files and then use them in python 3.1? The reason for this is, that I am writing an extension for the program "blender", which has an internal python 3.1 interpreter. But i would also like...
using cython to port modules to python 3.1
Is it possible to import arbitrary modules in cython, compile them to shared object files and then use them in python 3.1? The reason for this is, that I am writing an extension for the program "blender", which has an internal python 3.1 interpreter. But i would also like to make use of some python-modules which are no...
[ "In principle, I believe it's possible. Cython works by translating Python-like code to C code. That code can be compiled for either Python 2 or Python 3 (it uses C preprocessor statements to change which code is used).\nThe bad news is that it will only work for extensions written in Python-like code that Cython c...
[ 4 ]
[ "Check your Python documentation, the section \"Python/C API Reference Manual\" describes in detail how to do it.\nEDITED:\nSo what you want is porting a 2.x lib to 3.x. That's a big work to do.\nIf the solution your wished exists. Python 2.x should have been eliminated by now.\nSure there is a 2to3 tool. But a Pyt...
[ -2 ]
[ "c", "cython", "module", "numpy", "python" ]
stackoverflow_0004297167_c_cython_module_numpy_python.txt
Q: How can I send python multiprocessing Process output to a Tkinter gui I'm trying to get output from a python multiprocessing Process displayed in a Tkinter gui. I can send output from Processes via a gui to a command shell, for example by running the fllowing tiny script at a shell prompt: from multiprocessing imp...
How can I send python multiprocessing Process output to a Tkinter gui
I'm trying to get output from a python multiprocessing Process displayed in a Tkinter gui. I can send output from Processes via a gui to a command shell, for example by running the fllowing tiny script at a shell prompt: from multiprocessing import Process import sys def myfunc(text): print text sys....
[ "You could redirect stdout/stderr to a StringIO in myfunc(), then send whatever gets written into that StringIO back to the parent (as suggested by unutbu). See my answer to this question for one way of doing this redirection.\nSince that example does a bit more than you need, here's a version that's more aligned ...
[ 8, 3, 0 ]
[]
[]
[ "multiprocessing", "python", "stdout", "tkinter", "user_interface" ]
stackoverflow_0004227808_multiprocessing_python_stdout_tkinter_user_interface.txt
Q: Faster Development Rails or Django? I have around 2 Weeks of Real development time to churn out a contact database system to replace various spreadsheets and pieces of paper laying around. Also I need to develop two websites (with dynamic content) and a small AJAXian web service. I have no experience of rails or d...
Faster Development Rails or Django?
I have around 2 Weeks of Real development time to churn out a contact database system to replace various spreadsheets and pieces of paper laying around. Also I need to develop two websites (with dynamic content) and a small AJAXian web service. I have no experience of rails or django, but I can learn fast. Both claim t...
[ "The Django admin will generate a CRUD application that you can customize to suit almost any need, from your model definitions. I've used the admin for the main user interface for several projects and can tell you that it is a real timesaver. You don't have to spend any time whatsoever at writing templates or Javas...
[ 8, 6, 4, 4, 1 ]
[]
[]
[ "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0004298622_django_python_ruby_ruby_on_rails.txt
Q: Python ImportError on web hosting I'm fairly new to Python, so forgive me if I'm missing something obvious. I have been using the Topia TermExtract package, and the code I wrote has been working fine on my local machine (Mac OS 10.6.5; Python 2.6). However, when I copy the entire directory, complete with package f...
Python ImportError on web hosting
I'm fairly new to Python, so forgive me if I'm missing something obvious. I have been using the Topia TermExtract package, and the code I wrote has been working fine on my local machine (Mac OS 10.6.5; Python 2.6). However, when I copy the entire directory, complete with package files, to my GoDaddy hosting, I get this...
[ "The pkg_resources package is part of setuptools. Install that on the hosting.\n", "I got it. I had to install VirtualEnv. If anyone has a similar problem, check out this post:\nHow to install setuptools?\n" ]
[ 1, 1 ]
[]
[]
[ "extraction", "importerror", "python" ]
stackoverflow_0004299043_extraction_importerror_python.txt
Q: Python: inspect where an exception raise would go Take this code: def A(): try: B() except Exception: pass def B(): C() def C(): print exception_handling_pointer() A() The function exception_handling_pointer should return me a pointer to the function where this specific exception would ...
Python: inspect where an exception raise would go
Take this code: def A(): try: B() except Exception: pass def B(): C() def C(): print exception_handling_pointer() A() The function exception_handling_pointer should return me a pointer to the function where this specific exception would be checked first for being handled. I.e., in this case,...
[ "You can't decide where a Exception will get handled without actually raising the Exception. This is easy to see here:\ntry: \n raise input('Raise which?')\nexcept input('Catch which?') as e: \n pass`\n\nAny function that does what you want would have to predict user input here. The whole endeavor is futile a...
[ 3, 2 ]
[]
[]
[ "exception", "inspect", "python" ]
stackoverflow_0004298108_exception_inspect_python.txt
Q: Modifying strings in Python I have a string here in python '#b9d9ff'. How do I remove the hash symbol (#)? A: There are various trivially-different options. Each one does the same thing for your string but handles other strings differently. # Strip any hashes on the left. string.lstrip('#') # Remove hashes anyw...
Modifying strings in Python
I have a string here in python '#b9d9ff'. How do I remove the hash symbol (#)?
[ "There are various trivially-different options. Each one does the same thing for your string but handles other strings differently.\n# Strip any hashes on the left.\nstring.lstrip('#')\n\n# Remove hashes anywhere in the string, not necessarily just from the front.\nstring.replace('#', '')\n\n# Remove only the first...
[ 9, 3, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004299293_python_string.txt
Q: Select sub-list with highest integer value in a specified position I have a nested list: nested_list = [['a', 3], ['a', 1], ['a', 5]] How do I iterate over this list, select the sublist with the max integer value? holder = [] for entry in nested_list: tmp = sublist with max entry[2] value holder.append(t...
Select sub-list with highest integer value in a specified position
I have a nested list: nested_list = [['a', 3], ['a', 1], ['a', 5]] How do I iterate over this list, select the sublist with the max integer value? holder = [] for entry in nested_list: tmp = sublist with max entry[2] value holder.append(tmp) I am stuck on coding the second line.
[ "try:\nmax(nested_list, key=lambda x: x[1])\n\nor\nimport operator\n\nmax(nested_list, key=operator.itemgetter(1))\n\nIf the first item will always be 'a', you can just do\nmax(nested_list)\n\nIf you're willing to dive into some type checking and you want to do this for arbitrary sublists (Of one level only. someth...
[ 8, 1, 1 ]
[]
[]
[ "max", "nested_lists", "python" ]
stackoverflow_0004299422_max_nested_lists_python.txt
Q: Python - Way to encode foreign characters in format Python can work with? I'm working with large files in French and German. Basically, writing strings of characters from one file to another, collecting data from them, and so forth. Unfortunately, I have no idea what to import in order to let Python handle these c...
Python - Way to encode foreign characters in format Python can work with?
I'm working with large files in French and German. Basically, writing strings of characters from one file to another, collecting data from them, and so forth. Unfortunately, I have no idea what to import in order to let Python handle these characters. Even when collecting data from files that Python has already convert...
[ "\"Unicode in Python, Completely Demystified\"\n" ]
[ 3 ]
[]
[]
[ "character_encoding", "dictionary", "python", "string" ]
stackoverflow_0004299490_character_encoding_dictionary_python_string.txt
Q: Multiple writes to file I have the following python code that expects data coming from the serial port, and writes it to a file. import time import serial def write_log ( text ): f = open('logger.log', 'a') f.write( text ) f.close() ser = serial.Serial() ser.port = "/dev/ttyS0" ser.baudrate = 4800 se...
Multiple writes to file
I have the following python code that expects data coming from the serial port, and writes it to a file. import time import serial def write_log ( text ): f = open('logger.log', 'a') f.write( text ) f.close() ser = serial.Serial() ser.port = "/dev/ttyS0" ser.baudrate = 4800 ser.open() if ser.isOpen(): ...
[ "You have an infinite loop in your code, and you don't break out from it when there is a problem - or the serial device is no longer open.\nProbably use:\nwhile ser.isOpen():\n while ser.inWaiting() <= 0:\n time.sleep(1)\n response = ser.read(ser.inWaiting())\n if len(response):\n ...
[ 1, 0 ]
[]
[]
[ "io", "python", "serial_port" ]
stackoverflow_0004299454_io_python_serial_port.txt
Q: How can I make sense of a badly encoded message? --------------------------- ƒGƒ‰[ --------------------------- ƒfƒBƒXƒvƒŒƒCƒ‚[ƒh‚ªÝ’è‚Å‚«‚Ü‚¹‚ñ. --------------------------- OK --------------------------- I get this clear error message out of Shooter's Solitude system 4, after I feed it this version of d3drm.dl...
How can I make sense of a badly encoded message?
--------------------------- ƒGƒ‰[ --------------------------- ƒfƒBƒXƒvƒŒƒCƒ‚[ƒh‚ªÝ’è‚Å‚«‚Ü‚¹‚ñ. --------------------------- OK --------------------------- I get this clear error message out of Shooter's Solitude system 4, after I feed it this version of d3drm.dll (sigh.) Here's an hexdump for your convenience: 0000...
[ "Obviously.\nSince it is a Japanese game\n\n'ディスプレイモ\\x81[ドが\\x90ン定できません.\\n'\n'Disupureimo \\ x81 [the de \\ x90 applications can not be fixed. \\ N'\n\nBecause I pasted the string, there are some missing.\nThe coding named Shift-JIS. I use my Opera to show the characters actually.\nEDIT:\nSadly all my browsers ca...
[ 6, 6, 3 ]
[]
[]
[ "character_encoding", "language_agnostic", "python", "windows" ]
stackoverflow_0004298402_character_encoding_language_agnostic_python_windows.txt
Q: Kill a Python process if it doesn't finish in a certain time? Here's the scenario: I have a Python script that is called from a browser with AJAX. I want the Python script to run and return its output, however if it fails to successfully run in 10 seconds, I want the script to abort and return some other process....
Kill a Python process if it doesn't finish in a certain time?
Here's the scenario: I have a Python script that is called from a browser with AJAX. I want the Python script to run and return its output, however if it fails to successfully run in 10 seconds, I want the script to abort and return some other process. Also, at the very beginning, I want to log what the request was. ...
[ "If this script is run under Unix-like system, you may use SIGALRM to do it.\nThere's an example in python docs.\n", "check out: \nsubprocess.Popen.poll\nand\nsubprocess.Popen.terminate\n", "I highly sugges using the multiprocessing library of Python. It has process.terminate() methods.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "multithreading", "process", "python" ]
stackoverflow_0004299370_multithreading_process_python.txt
Q: Python script to convert from UTF-8 to ASCII I'm trying to write a script in python to convert utf-8 files into ASCII files: #!/usr/bin/env python # *-* coding: iso-8859-1 *-* import sys import os filePath = "test.lrc" fichier = open(filePath, "rb") contentOfFile = fichier.read() fichier.close() fichierTemp = o...
Python script to convert from UTF-8 to ASCII
I'm trying to write a script in python to convert utf-8 files into ASCII files: #!/usr/bin/env python # *-* coding: iso-8859-1 *-* import sys import os filePath = "test.lrc" fichier = open(filePath, "rb") contentOfFile = fichier.read() fichier.close() fichierTemp = open("tempASCII", "w") fichierTemp.write(contentOfF...
[ "data=\"UTF-8 DATA\"\nudata=data.decode(\"utf-8\")\nasciidata=udata.encode(\"ascii\",\"ignore\")\n\n", "import codecs\n\n ...\n\nfichier = codecs.open(filePath, \"r\", encoding=\"utf-8\")\n\n ...\n\nfichierTemp = codecs.open(\"tempASCII\", \"w\", encoding=\"ascii\", errors=\"ignore\")\nfichierTemp.write(contentOf...
[ 65, 9, 6 ]
[]
[]
[ "ascii", "character_encoding", "python", "utf_8" ]
stackoverflow_0004299675_ascii_character_encoding_python_utf_8.txt
Q: Relief for menubar I'm in the process of creating a Gnome pannel applet. I've added a menubar to the applet but it seems I can't set the relief on the menubar. Does anyone know how I can edit that? I only want the relief to show when the bar is hovered or the submenu is collapsed. This is how it looks now: http://...
Relief for menubar
I'm in the process of creating a Gnome pannel applet. I've added a menubar to the applet but it seems I can't set the relief on the menubar. Does anyone know how I can edit that? I only want the relief to show when the bar is hovered or the submenu is collapsed. This is how it looks now: http://i.stack.imgur.com/7i8C9....
[ "Nevermind. Found it: \n gtk.rc_parse_string(\"\"\"\n style \"globalmenu_event_box_style\"\n {\n GtkWidget::focus-line-width=0\n GtkWidget::focus-padding=0\n }\n style \"globalmenu_menu_bar_style\"\n {\n ythickness = 0\n GtkMenuBar::s...
[ 0 ]
[]
[]
[ "gnome", "gtk", "pygtk", "python" ]
stackoverflow_0004299459_gnome_gtk_pygtk_python.txt
Q: Python sorting multiple attributes I have a dictionary like the following. Key value pairs or username:name d = {"user2":"Tom Cruise", "user1": "Tom Cruise"} My problem is that i need to sort these by the Name, but if multiple users contain the same name like above, i then need to sort those by their username. I ...
Python sorting multiple attributes
I have a dictionary like the following. Key value pairs or username:name d = {"user2":"Tom Cruise", "user1": "Tom Cruise"} My problem is that i need to sort these by the Name, but if multiple users contain the same name like above, i then need to sort those by their username. I looked up the sorted function but i dont...
[ "cmp is obsolescent. lambda just makes a function.\nsorted(d.iteritems(), key=operator.itemgetter(1, 0))\n\n", "I'm just going to elaborate on Ignacio Vazquez-Abrams's answer. cmp is deprecated. Don't use it. Use the key attribute instead. \nlambda makes a function. It's an expression and so can go places that a ...
[ 6, 5, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0004299492_dictionary_python_sorting.txt
Q: Best way to enumerate a cartesian product with labels in python? Given a dictionary mapping variables to possible outcomes: { 'lblA' : [False, True], 'lblB' : [False, True], 'lblC' : [0,1,2] } I want to enumerate all possible dictionary outcomes: [ { 'lblA' : False , 'lblB' : False, 'lblC' : 0 }, { 'lblA' : True ,...
Best way to enumerate a cartesian product with labels in python?
Given a dictionary mapping variables to possible outcomes: { 'lblA' : [False, True], 'lblB' : [False, True], 'lblC' : [0,1,2] } I want to enumerate all possible dictionary outcomes: [ { 'lblA' : False , 'lblB' : False, 'lblC' : 0 }, { 'lblA' : True , 'lblB' : False, 'lblC' : 0 }, { 'lblA' : False , 'lblB' : True, 'lblC...
[ "[dict(zip(('lblA', 'lblB', 'lblC'), term)) for term in\n itertools.product((False, True) , (False, True), (0, 1, 2))]\n\nEDIT:\nPicky, picky...\nsrc = {'lblA': (False, True), 'lblB': (False, True), 'lblC': (0, 1, 2)}\n\nlabels, terms = zip(*src.items())\n\nprint [dict(zip(labels, term)) for term in itertools.prod...
[ 9 ]
[]
[]
[ "enumeration", "python", "python_itertools" ]
stackoverflow_0004299927_enumeration_python_python_itertools.txt