content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: reduce on tuple of tuples I am trying to compute in Python the length of the path from a point A to a point B going through a list of intermediary points. I know how to do it but I do want to use the reduce Built-in function. Why I tried so far, please note that it is completely wrong, is this: reduce(lamb...
Python: reduce on tuple of tuples
I am trying to compute in Python the length of the path from a point A to a point B going through a list of intermediary points. I know how to do it but I do want to use the reduce Built-in function. Why I tried so far, please note that it is completely wrong, is this: reduce(lambda x,y: math.sqrt((y[1]-y[0])**2+(x[1]-...
[ "You should map before you reduce.\npoints = [(1, 2), (3, 4), (1, 8)]\ndistances = (math.hypot(b[0]-a[0], b[1]-a[1])\n for a, b in zip(points, points[1:]))\ntotal_distance = sum(distances)\n\nor, if you must use reduce(), although sum() is better for this purpose:\nimport operator\n\ntotal_distance = re...
[ 6, 4, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "euclidean_distance", "lambda", "python", "reduce" ]
stackoverflow_0008170562_euclidean_distance_lambda_python_reduce.txt
Q: Install mod_python for Apache 2.2.21, Python 2.5.4 on Mac OS X 10.6 I was able to install apache & python successfully from source. I installed mod_python with following configure command: ./configure --prefix=/usr/local/python/lib/python2.5/site-packages/mod_python --with-apxs=/usr/local/apache/bin/apxs --with-py...
Install mod_python for Apache 2.2.21, Python 2.5.4 on Mac OS X 10.6
I was able to install apache & python successfully from source. I installed mod_python with following configure command: ./configure --prefix=/usr/local/python/lib/python2.5/site-packages/mod_python --with-apxs=/usr/local/apache/bin/apxs --with-python=/usr/local/python/bin/python2.5 I copied my test file (mptest.py) t...
[ "I'm afraid I can't help with mod_python. We've switched all our code away from mod_python in favor of mod_wsgi and never looked back.\nmod_wsgi has some great features -- not to mention the ability to easily create debug/diagnostic code than can be run entirely from python without the trouble of running Apache (wh...
[ 1 ]
[]
[]
[ "apache", "mod_python", "python" ]
stackoverflow_0008163904_apache_mod_python_python.txt
Q: Python IDLE freezes This is absolutely frustrating, but I am not sure if the following is an issue only on my machine or with IDLE in general. When attempting to print a long list in the shell, and that could happen by accident while debugging, the program crushes and you have to restart it manually. Even worse, i...
Python IDLE freezes
This is absolutely frustrating, but I am not sure if the following is an issue only on my machine or with IDLE in general. When attempting to print a long list in the shell, and that could happen by accident while debugging, the program crushes and you have to restart it manually. Even worse, if you have a few editor w...
[ "It seems tk needs to write a lot of data in the shell frame, this takes a lot of time and when the list is long then it becomes unresponsive.\nI did:\n>>a = range(n)\n>>print(list(a))\n\nIt was OK for n = 100 or n = 1000. After that point things started being slow. For n as low as 10000, moving the page up and dow...
[ 2, 2 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0002743715_python_python_idle.txt
Q: In Tkinter how can I correct this loop/function so that each button changes a value to the value of the button? In Tkinter how can I correct this loop/function so that each button changes a value to the value of the button? This is a simplified version of my code, at the moment each button changes the value of si...
In Tkinter how can I correct this loop/function so that each button changes a value to the value of the button?
In Tkinter how can I correct this loop/function so that each button changes a value to the value of the button? This is a simplified version of my code, at the moment each button changes the value of size to 15 rather than the number on the button. I was wondering if there was anyway of fixing this loop without printi...
[ "Change your lambda to bind the value at the time the anonymous function is created.\nlambda a=a: inputBoardSize(a)\n\n" ]
[ 2 ]
[]
[]
[ "lambda", "python", "tkinter" ]
stackoverflow_0008172682_lambda_python_tkinter.txt
Q: Child to parent communication in Python multiprocessing I am writing a python script that will parse through a file quickly by sending lines to different processes to handle. At the end, I want the parent to receive the results from each child process and then be able to manipulate that. Here is the code: #!/usr/b...
Child to parent communication in Python multiprocessing
I am writing a python script that will parse through a file quickly by sending lines to different processes to handle. At the end, I want the parent to receive the results from each child process and then be able to manipulate that. Here is the code: #!/usr/bin/env python import os import re from datetime import datet...
[ "You can pass values back through an results queue.\nIn LineConsumer:\ndef __init__(self, queue, result_queue):\n self.result_queue = result_queue\n # ...\n\ndef terminate(self):\n self.results_queue.put(self.lines)\n super(LineConsumer, self).terminate()\n\nIn Parser:\nqueue = JoinableQueue(100)\nresult_qu...
[ 3, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0008172965_multiprocessing_python.txt
Q: How do you make the linewidth of a single line change as a function of x in matplotlib? Does anyone know how to make the linewidth of a single line change as a function of x in matplotlib? For example, how would you make a line thin for small values of x, and thick for large values of x? A: Basically, you need t...
How do you make the linewidth of a single line change as a function of x in matplotlib?
Does anyone know how to make the linewidth of a single line change as a function of x in matplotlib? For example, how would you make a line thin for small values of x, and thick for large values of x?
[ "Basically, you need to use a polygon instead of a line. As a quick example:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Make the original line...\nx = np.linspace(0, 10, 100)\ny = 2 * x\nthickness = 0.5 * np.abs(np.sin(x) * np.cos(x))\n\nplt.fill_between(x, y - thickness, y + thickness, color='blue'...
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008172312_matplotlib_python.txt
Q: Can a Python Fabric task invoke other tasks and respect their hosts lists? I have a fabfile like the following: @hosts('host1') def host1_deploy(): """Some logic that is specific to deploying to host1""" @hosts('host2') def host2_deploy(): """Some logic that is specific to deploying to host2""" def deplo...
Can a Python Fabric task invoke other tasks and respect their hosts lists?
I have a fabfile like the following: @hosts('host1') def host1_deploy(): """Some logic that is specific to deploying to host1""" @hosts('host2') def host2_deploy(): """Some logic that is specific to deploying to host2""" def deploy(): """"Deploy to both hosts, each using its own logic""" host1_deploy(...
[ "Since Fabric 1.3, the execute helper is now available to do just this. The documentation is available here: Intelligently executing tasks with execute. \nHere is the example they use:\nfrom fabric.api import run, roles, execute\n\nenv.roledefs = {\n 'db': ['db1', 'db2'],\n 'web': ['web1', 'web2', 'web3'],\n}...
[ 31, 3, 1, 1 ]
[]
[]
[ "deployment", "fabric", "python", "ssh" ]
stackoverflow_0005346135_deployment_fabric_python_ssh.txt
Q: Determine if JSON parsing was successful in python What kind of exceptions can I expect to be thrown if I try to parse invalid JSON with json.load? I couldn't find this in the documentation anywhere. A: Why not try it ;) >>> json.loads('ewrwerw') ValueError: No JSON object could be decoded Grepping for raise in...
Determine if JSON parsing was successful in python
What kind of exceptions can I expect to be thrown if I try to parse invalid JSON with json.load? I couldn't find this in the documentation anywhere.
[ "Why not try it ;)\n>>> json.loads('ewrwerw')\nValueError: No JSON object could be decoded\n\nGrepping for raise in the sourcecode of the json module will also show that nothing but ValueError is raised.\n\nIn case you use simplejson:\nclass JSONDecodeError(ValueError):\n\nSo catching ValueError will also work with...
[ 7 ]
[]
[]
[ "json", "python" ]
stackoverflow_0008173514_json_python.txt
Q: How to measure width in KMs with geos I've got a bounding box, and I want to adjust it so it's not less than, say, 2km across. I get the bounding box from google's geolocate service, and then I search for stuff that's inside that in my database, but I want to make sure I don't test against anything smaller than 1 ...
How to measure width in KMs with geos
I've got a bounding box, and I want to adjust it so it's not less than, say, 2km across. I get the bounding box from google's geolocate service, and then I search for stuff that's inside that in my database, but I want to make sure I don't test against anything smaller than 1 or 2km across.. I'd like to get the area, m...
[ "The answer to this depends on the SRID. You call expand which gets a unitless float as a parameter, and the units on that depend on the units with which the SRID is defined.\n" ]
[ 0 ]
[]
[]
[ "django", "geodjango", "geos", "python" ]
stackoverflow_0007198085_django_geodjango_geos_python.txt
Q: How can I order a queryset by a filtered bridge table field? Given the following models class Blog(models.Model): followers = models.ManyToManyField(User, through='Follow') class Follow(models.Model): blog = models.ForeignKey(Blog) user = models.ForeignKey(User) created = models.DateField(auto_now...
How can I order a queryset by a filtered bridge table field?
Given the following models class Blog(models.Model): followers = models.ManyToManyField(User, through='Follow') class Follow(models.Model): blog = models.ForeignKey(Blog) user = models.ForeignKey(User) created = models.DateField(auto_now_add=True) If I have a user, how can I get blogs the user follows...
[ "Try something like this:\nqs = user.blog_set.all().order_by(\"follow__created\")\n\nFor descending order use the following:\nqs = user.blog_set.all().order_by(\"-follow__created\")\n\nI am not sure about \"order_by\" part, but you can \"play\" with it.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0008173576_django_django_models_django_queryset_python.txt
Q: Why isn't the cookie I'm setting in Django and reading in jQuery's cookie plugin using my expire time? I'm trying to create a cookie that has a specific expire time. I set it in my django view with the following code: from datetime import datetime response.set_cookie('cookie_name', 'cookie_value', expires=datetime...
Why isn't the cookie I'm setting in Django and reading in jQuery's cookie plugin using my expire time?
I'm trying to create a cookie that has a specific expire time. I set it in my django view with the following code: from datetime import datetime response.set_cookie('cookie_name', 'cookie_value', expires=datetime.today() + timedelta(20*365), path='/path/to/cookie/') I'm reading the value of the cookie using the jQuery...
[ "Set max_age as well. If not the browser will throw out the cookie when the session is complete. Or better yet, just specify max_age, not expires and expires will be calculated for you.\nUpon further investigation, you are using a date object, expires requires a datetime object. So you'll want to do datetime.dat...
[ 0, 0, 0 ]
[]
[]
[ "cookies", "django", "jquery", "python" ]
stackoverflow_0008098896_cookies_django_jquery_python.txt
Q: Does realloc actually shrink buffers in common implementations? In common implementations such as Linux/Glibc, Windows/MSVC and BSD/Mac OS X, will void *p = malloc(N + M); // assume this doesn't fail p = realloc(p, N); // nor this for N, M > 0, actually shrink the buffer returned by malloc in the realloc ...
Does realloc actually shrink buffers in common implementations?
In common implementations such as Linux/Glibc, Windows/MSVC and BSD/Mac OS X, will void *p = malloc(N + M); // assume this doesn't fail p = realloc(p, N); // nor this for N, M > 0, actually shrink the buffer returned by malloc in the realloc call, in the sense that up to M bytes may return to the free list? An...
[ "I can say about Linux/glibc.\nIn the source code it contains comments like this:\n\nif n is for fewer bytes than already held by p, the newly unused\n space is lopped off and freed if possible.\n\nif you look at code of glibc, it contains lines like this:\nremainder_size = newsize - nb;\n\nif (remainder_size < M...
[ 16, 4, 0 ]
[]
[]
[ "c", "malloc", "memory_management", "numpy", "python" ]
stackoverflow_0008174278_c_malloc_memory_management_numpy_python.txt
Q: How do I allow a user (via cgi/python) to access files on the webserver? I have a really good working cgi-bin script written in python right now. It works like this 1) The engineer will copy a test report folder from a remote linux machine to our main server. (I will automate this by writing a telnet/ssh script? ...
How do I allow a user (via cgi/python) to access files on the webserver?
I have a really good working cgi-bin script written in python right now. It works like this 1) The engineer will copy a test report folder from a remote linux machine to our main server. (I will automate this by writing a telnet/ssh script? link to examples appreciated.. where the engineer just plugs in the ip, and t...
[ "If you're using python I'd recommend porting your site to django. Django provides a lot of features you're looking for.\nhttps://www.djangoproject.com/\nFor part 1, you can allow the engineer to upload files via the site (avoiding any ssh scripting): https://docs.djangoproject.com/en/dev/topics/http/file-uploads/...
[ 2 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0008174391_cgi_python.txt
Q: newbie error on installing python on OS X Lion via brew I get this error when running on OX Lion: brew install python Error: MD5 mismatch Expected: c8cfcfd42ec9ab900fb3960a3308eef2 Got: f783444754861f9b33e9f4083bd97b60 Archive: /Users/jt/Library/Caches/Homebrew/distribute-0.6.21.tar.gz (To retry an incomplete...
newbie error on installing python on OS X Lion via brew
I get this error when running on OX Lion: brew install python Error: MD5 mismatch Expected: c8cfcfd42ec9ab900fb3960a3308eef2 Got: f783444754861f9b33e9f4083bd97b60 Archive: /Users/jt/Library/Caches/Homebrew/distribute-0.6.21.tar.gz (To retry an incomplete download, remove the file above.) I remove file but same is...
[ "They simply replaced the MD5 value in Python formula. Try 'brew update' command and see if it works after that. \nIf all else fails you can edit the file yourself locally. \nvi /usr/local/Library/Formula/python.rb \n\nJust make the same change as outlined in diff:\nhttps://github.com/martinploeger/homebrew/commit...
[ 1 ]
[]
[]
[ "osx_lion", "python" ]
stackoverflow_0008174375_osx_lion_python.txt
Q: How to build a random number generator in python that produces numbers in line with some data Its a question from a problem set i have. I need to devise a random number generator that produces request sizes that are in line with the data. And then devise another random number generator that produces interarrival t...
How to build a random number generator in python that produces numbers in line with some data
Its a question from a problem set i have. I need to devise a random number generator that produces request sizes that are in line with the data. And then devise another random number generator that produces interarrival times that are in line with the data. After I done that I need to explain how I analysed the data to...
[ "I don't understand precisely what you're asking, but it almost seems like you're looking to either model your data or fit it to a statistical distribution, or perhaps generate a set of data for each of your data points by using each point as the central tendency. \nIn either case, you will probably want to use th...
[ 1, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0008173511_python_random.txt
Q: How do I debug my appengine site being offline? Coding n00b here - I have a website here which is a python site on appengine: http://www.7bks.com/ And it's currently down. Completely unavailable. My appengine dashboard appears normal, no quota denials, no errors and when I try and visit there's no log generated (b...
How do I debug my appengine site being offline?
Coding n00b here - I have a website here which is a python site on appengine: http://www.7bks.com/ And it's currently down. Completely unavailable. My appengine dashboard appears normal, no quota denials, no errors and when I try and visit there's no log generated (because I can't even reach the site). I also can't rea...
[ "Check if you have a DNS problem\nOpen the application with Google Chrome and when you get an error you will see the error code with the explanation on the bottom.\nCheck if you have a link issue\nIn a terminal type \ntraceroute http://www.7bks.com/ \n\nand see what it gives\nAnyway it is more likely to be a DNS is...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008174743_google_app_engine_python.txt
Q: Comet for User based Notification over a Message Queue We trying to build application that should use Comet (AJAX Push) to send notifications to individual users. Most notifications will have a fairly low timeout. As we are running RabbitMQ, it would be easiest to send messages through AMQP. I am wondering what th...
Comet for User based Notification over a Message Queue
We trying to build application that should use Comet (AJAX Push) to send notifications to individual users. Most notifications will have a fairly low timeout. As we are running RabbitMQ, it would be easiest to send messages through AMQP. I am wondering what the best way to address individual users is, so that both the ...
[ "I had almost the same use case and eventually ended up with Socket.IO for client-side, TornadIO for handling connections and RabbitMQ for message passing (via pika). Works quite well, worth to try it out.\n" ]
[ 0 ]
[]
[]
[ "amqp", "comet", "orbited", "python", "tornado" ]
stackoverflow_0003112303_amqp_comet_orbited_python_tornado.txt
Q: Convention for declaring variables in Python, when required for scope? Take this example: def f(): myvar = None def g(): print myvar ... myvar = get_real_value() g() Is "myvar = None" a conventional (or at least, reasonable) way of declaring the variable, to make it visible to g()? Is...
Convention for declaring variables in Python, when required for scope?
Take this example: def f(): myvar = None def g(): print myvar ... myvar = get_real_value() g() Is "myvar = None" a conventional (or at least, reasonable) way of declaring the variable, to make it visible to g()? Is there a better way? (Python 2.6.x, if relevant)
[ "There is no need to declare the variable before the definition for g():\n>>> def f():\n... def g():\n... print myvar\n... myvar = 1\n... g()\n... \n>>> f()\n1\n\nHowever, if you can avoid referencing non-local variables in g() that would be preferable, which you would probably do here by having...
[ 3, 1 ]
[]
[]
[ "coding_style", "python", "scope" ]
stackoverflow_0008174796_coding_style_python_scope.txt
Q: python error - unboundLocalError I'm a newbie to programming but I am into natural languages (as you can see). I am trying to write a simple program to help test French present tense verbs. However, in this code I keep getting an error message because correctAnswers apparently hasn't been set as a global variable....
python error - unboundLocalError
I'm a newbie to programming but I am into natural languages (as you can see). I am trying to write a simple program to help test French present tense verbs. However, in this code I keep getting an error message because correctAnswers apparently hasn't been set as a global variable. Any ideas!? import random level1=["(...
[ "correctAnswers=0 is out of scope. They should be inside of getVerb. You also don't need recursion.\nAssuming you want to test every level and every question once:\nimport random\n\n\nlevel1=[\"(manger)\",\"je mange\", \"tu manges\", \"il mange\", \"elle mange\", \"nous mangeons\", \"vous mangez\", \"ils mangent\",...
[ 1, 1, 1, 0 ]
[ "A more pythonic approach would be to use a generator to get the next question for the current level:\nimport random\n\nlevels = {\n '(manger)' : [\"je mange\", \"tu manges\", \"il mange\", \"elle mange\", \"nous mangeons\", \"vous mangez\", \"ils mangent\", \"elles mangent\"],\n '(boire)' : [\"je bois\", \"t...
[ -1 ]
[ "python", "scope", "variables" ]
stackoverflow_0008172643_python_scope_variables.txt
Q: urllib is mangling my urls I'm writing a little scraper. Here's the code so far. from urllib import urlopen from BeautifulSoup import BeautifulSoup import re soup = BeautifulSoup( urlopen('http://www.high-rely.com/HR3/includes/ProductFamily.php').read() ) links = soup.findAll('a', 'visible_link') hrefs ...
urllib is mangling my urls
I'm writing a little scraper. Here's the code so far. from urllib import urlopen from BeautifulSoup import BeautifulSoup import re soup = BeautifulSoup( urlopen('http://www.high-rely.com/HR3/includes/ProductFamily.php').read() ) links = soup.findAll('a', 'visible_link') hrefs = ['www.high-rely.com' + relativ...
[ "You forgot to write http://:\nhrefs = ['http://www.high-rely.com' + relative for relative in [x['href'] for x in links]]\n\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "urllib" ]
stackoverflow_0008174884_beautifulsoup_python_urllib.txt
Q: How can I evaluate my technique? I am dealing with a problem of text summarization i.e. given a large chunk(s) of text, I want to find the most representative "topics" or the subject of the text. For this, I used various information theoretic measures such as TF-IDF, Residual IDF and Pointwise Mutual Information t...
How can I evaluate my technique?
I am dealing with a problem of text summarization i.e. given a large chunk(s) of text, I want to find the most representative "topics" or the subject of the text. For this, I used various information theoretic measures such as TF-IDF, Residual IDF and Pointwise Mutual Information to create a "dictionary" for my corpus....
[ "I'm not an expert of machine learning, but I would use cross-validation. If you used e.g. 1000 pages of text to \"train\" the algorithm (there is a \"human in the loop\", but no problem), then you could take another few hundred test pages, and use your \"top-k phrases algorithm\" to find the \"topic\" or \"subject...
[ 1 ]
[]
[]
[ "machine_learning", "nlp", "nltk", "python" ]
stackoverflow_0008174904_machine_learning_nlp_nltk_python.txt
Q: Pyinstaller not working I was trying to create a stand alone executable file using Pyinstaller. The process ranging from Configure to Makespec part went fine. But while processing Build.py , the following error was shown. checking PYZ rebuilding outPYZ1.toc because outPYZ1.pyz is missing building PYZ o...
Pyinstaller not working
I was trying to create a stand alone executable file using Pyinstaller. The process ranging from Configure to Makespec part went fine. But while processing Build.py , the following error was shown. checking PYZ rebuilding outPYZ1.toc because outPYZ1.pyz is missing building PYZ outPYZ1.toc checking PKG ...
[ "This is a reported issue. PyInstaller looks in the wrong place for tcl8.5. My guess is that not all Linux distributions keep tcl in the same spot.\nOne user solved the error by doing this:\n\nfor me, pyinstaller is looking in /usr/lib/tcl8.5, when it should be\n looking in /usr/share/tcltk/tcl8.5 when I hack con...
[ 1 ]
[]
[]
[ "pyinstaller", "python" ]
stackoverflow_0008159646_pyinstaller_python.txt
Q: Random guessing in Python I have 40 cards. 10 yellow. 10 red. 10 blue and 10 green. I need to pick 25 random cards, and then give them to 500 people. Each one needs to guess the right color for each of the 25 cards. This is what I have done so far: import random nSuits = 4 # yellow/red/blue/green ...
Random guessing in Python
I have 40 cards. 10 yellow. 10 red. 10 blue and 10 green. I need to pick 25 random cards, and then give them to 500 people. Each one needs to guess the right color for each of the 25 cards. This is what I have done so far: import random nSuits = 4 # yellow/red/blue/green nCards = 25 # Number of ra...
[ "if i understand correctly, each player needs 25 guesses (one for each card):\nrandomGuesses = [[random.randrange(nSuits) for i in range (nCards)] for j in range(nPlayers)]\n\nthis will produce a list with nPlayer nested lists, each with nCards \"guesses\". \nrandomGuesses[i][j]\n\nis the j'th guess of the i'th pl...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008175042_python.txt
Q: Django's built in web server: Usage and Reliability Concerns Short Question 1 What constitutes a production environment defined in Django's documentation about 1/2 the way through? Short Question 2 Is there any documented cases of the admin interface corrupting the database if multiple people access the DB simulta...
Django's built in web server: Usage and Reliability Concerns
Short Question 1 What constitutes a production environment defined in Django's documentation about 1/2 the way through? Short Question 2 Is there any documented cases of the admin interface corrupting the database if multiple people access the DB simultaneously? Background I have used Django as an ORM for a PostgreSQL ...
[ "If you're not using the development server for development of the django project, it sounds like production to me. Is deploying your application with Apache and mod WSGI worth the hassle? That's up to you, but the advice of the Django developers is pretty unambiguous.\n\nDO NOT USE THIS SERVER IN A PRODUCTION SETT...
[ 2, 0 ]
[]
[]
[ "django", "orm", "python", "ubuntu" ]
stackoverflow_0008174987_django_orm_python_ubuntu.txt
Q: Dynamic Content with a Polling Interval I plan to run a webserver with some content generated through a Python script. I have a script that generates the data I would want to present at the moment that polls every 2 minutes with a fairly large request. How can I put this data onto a webpage without making volumino...
Dynamic Content with a Polling Interval
I plan to run a webserver with some content generated through a Python script. I have a script that generates the data I would want to present at the moment that polls every 2 minutes with a fairly large request. How can I put this data onto a webpage without making voluminous numbers of requests? I can think of a few ...
[ "I wouldn't write off the javascript polling idea.\nConsider generating the file and pushing to a CDN. Make sure to let the CDN know you need a specific TTL that meets with the schedule you're generating with as their default TTL will probably be longer than 2 min. The CDN should be awesome at serving static cont...
[ 0 ]
[]
[]
[ "cgi", "html", "python" ]
stackoverflow_0008175406_cgi_html_python.txt
Q: Memory Game in Python with Tkinter I'm trying to make a memory game using python 3 and tkinter. I'm new to python so this is kind of hard. My problem is that I'm trying to call the method "show_word" in the class "Cell" from the class "Memory" but I don't know exactly how to do it. the memory game: def create_...
Memory Game in Python with Tkinter
I'm trying to make a memory game using python 3 and tkinter. I'm new to python so this is kind of hard. My problem is that I'm trying to call the method "show_word" in the class "Cell" from the class "Memory" but I don't know exactly how to do it. the memory game: def create_widgets(self): """ Create widget...
[ "You've run into a subtle scoping problem. When you create a function that refers to variables from a containing scope, the value of those variables isn't fixed at the time of function definition, but at the time of function execution. In other words, when you do this:\ncommand = lambda: print(index) \n\nYou're tel...
[ 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0008175334_python_tkinter.txt
Q: PyQt Collection of QLineEdit objects Is there some way in PyQt to get a collection of all QLineEdit objects? I am trying to add a reset button that will blank out all text in all QLineEdit on a form, so I am looking for a way to loop through all QLineEdit objects rather than listing them all in my reset function t...
PyQt Collection of QLineEdit objects
Is there some way in PyQt to get a collection of all QLineEdit objects? I am trying to add a reset button that will blank out all text in all QLineEdit on a form, so I am looking for a way to loop through all QLineEdit objects rather than listing them all in my reset function that will connect to the reset button. Than...
[ "If all the line-edits have a parent, you could use:\nfor child in parent.findChildren(QtGui.QLineEdit):\n child.clear()\n\nOr possibly:\nfor widget in qApp.allWidgets():\n if isinstance(widget, QtGui.QLineEdit):\n widget.clear()\n\n" ]
[ 7 ]
[]
[]
[ "pyqt", "python", "qlineedit", "qt" ]
stackoverflow_0008175119_pyqt_python_qlineedit_qt.txt
Q: Simulate static variables in python with closures Is it possible to write a function in python, which takes an argument a and prints the result of h+a where h is a local variable. Then it should return itself, with h increased by one. A: In python 3, you can do this: >>> def f(a): ... h = 1 ... def inner...
Simulate static variables in python with closures
Is it possible to write a function in python, which takes an argument a and prints the result of h+a where h is a local variable. Then it should return itself, with h increased by one.
[ "In python 3, you can do this:\n>>> def f(a):\n... h = 1\n... def inner():\n... nonlocal h\n... print(a+h)\n... h += 1\n... return inner\n... return inner\n... \n>>> g = f(3) \n>>> g = g()\n4\n>>> g = g()\n5 \n>>> g = g()\n6\n>>> g()()()\n7 \n8\n9\n<funct...
[ 5, 2 ]
[]
[]
[ "closures", "python", "static" ]
stackoverflow_0008175323_closures_python_static.txt
Q: Fitting to a piecewise function using Python I'm trying to fit a piecewise function with absolute values using Numpy. The mathematical function is x < p[1]: y = 1 + p[0] * abs((size + x - p[1]) / size - size / 2) x >= p[1]: y = 1 + p[0] * abs((x - p[1]) / size - size / 2) Here's my Python function: fitfunc = lambd...
Fitting to a piecewise function using Python
I'm trying to fit a piecewise function with absolute values using Numpy. The mathematical function is x < p[1]: y = 1 + p[0] * abs((size + x - p[1]) / size - size / 2) x >= p[1]: y = 1 + p[0] * abs((x - p[1]) / size - size / 2) Here's my Python function: fitfunc = lambda p, x: \ x < p[1] and\ 1 + p[0] * abs((da...
[ "The code above does not look idiomatic and is making life harder than it should be. :)\nIf you're trying to define a function and give it a name at the same time, the conventional approach is to use def, not lambda.\nfitfunc = lambda p, x: ... ## you're making a named function, so just do...\n\ndef fitfunc(p, x)...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008174914_numpy_python.txt
Q: Passing Arguments with Newstyle signals in PyQT I've been having some trouble with a set of dynamically created buttons in PyQT. I'm using a list to create buttons corresponding to different values. Because each button is different, I need to have them pass an argument to the "Button Clicked" function identifying...
Passing Arguments with Newstyle signals in PyQT
I've been having some trouble with a set of dynamically created buttons in PyQT. I'm using a list to create buttons corresponding to different values. Because each button is different, I need to have them pass an argument to the "Button Clicked" function identifying themselves separately so I can perform different act...
[ "You can add attribute dynamically to objects using setattr\nfor x in buttons:\n name = str(x)\n button = QtGui.QPushButton(Frame)\n button.setText(name)\n button.clicked.connect(self.changeProject(name))\n setattr(self, \"btn_%s\" % name, button)\n\n", "What the error message is telling you is tha...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "pyqt", "python", "signals" ]
stackoverflow_0003807733_pyqt_python_signals.txt
Q: reverse the nesting of elements with python lxml.etree I'm looking for a recipe for python's lxml.etree that will reverse the nesting of elements, turning: <text> <name> <ref>foobar</ref> </name> </text> into: <text> <ref> <name>foobar</name> </ref> </text> I've a feeling this is ...
reverse the nesting of elements with python lxml.etree
I'm looking for a recipe for python's lxml.etree that will reverse the nesting of elements, turning: <text> <name> <ref>foobar</ref> </name> </text> into: <text> <ref> <name>foobar</name> </ref> </text> I've a feeling this is obvious, but I'm not seeing it.
[ "Something like this?\nimport lxml.etree as et\nfrom lxml.builder import E\n\nxml = \"\"\"\n<text>\n <name>\n <ref>foobar</ref>\n </name>\n</text>\n\"\"\"\n\ntree = et.fromstring(xml)\n\nfor name in tree.findall('name'):\n text = name.find('ref').text\n tree.replace(name, E.ref(E.name(text)))\n\n...
[ 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0008175066_lxml_python.txt
Q: unable to create table using django syncdb I am quite new to django and web framework development and I tired my hands on creating tables by using the inbuilt django models and then running the syncdb command to create it automatically . However I am having trouble creating it Here is my model from django.db impor...
unable to create table using django syncdb
I am quite new to django and web framework development and I tired my hands on creating tables by using the inbuilt django models and then running the syncdb command to create it automatically . However I am having trouble creating it Here is my model from django.db import models class User(models.Model): username...
[ "You seem to be defining your model here: /home/thor/scripts/django/quiz/dbs.py.\nIt should be in the root of your app module and named models.py.\nSee here for more info: https://docs.djangoproject.com/en/dev/topics/db/models/#using-models\n", "Did you know that Django have its own User model? don't waste time d...
[ 2, 0 ]
[]
[]
[ "django", "django_syncdb", "python" ]
stackoverflow_0008173128_django_django_syncdb_python.txt
Q: How to register a Pylons translator object? I've got an application that runs in several processes (one webserver and few processes that are used for heavy calculations). The goal is to make these calculation processes return localized errors. In order to do that, I've made a dictionary that will be used by Babel:...
How to register a Pylons translator object?
I've got an application that runs in several processes (one webserver and few processes that are used for heavy calculations). The goal is to make these calculation processes return localized errors. In order to do that, I've made a dictionary that will be used by Babel: errors = { 'ERR_REQUEST_FORMAT': (1, _('ERR_...
[ "I would recommend you translate in the main server thread, but you can register/use a translator object like so:\nimport gettext\nstr_to_translate = u'String to Translate'\nDOMAIN = 'example' # name of your translation babel translation file, here would be example.po\nLOCALE_DIR = '/path/to/locale/dir' # directory...
[ 2 ]
[]
[]
[ "localization", "pylons", "python", "python_babel" ]
stackoverflow_0007835543_localization_pylons_python_python_babel.txt
Q: Matching HTML subtree with BeautifulSoup I'm trying to match something like this with beautifulsoup. <a href="./SlimLineUSB3/SlimLine1BayUSB3.php"> <b>1 Bay SlimLine with both eSATA and USB 3.0</b> </a> In a regexp, it would look something like this. I want to capture the url. <a href="\.(.*)"> <b>.*</b> </a> Ho...
Matching HTML subtree with BeautifulSoup
I'm trying to match something like this with beautifulsoup. <a href="./SlimLineUSB3/SlimLine1BayUSB3.php"> <b>1 Bay SlimLine with both eSATA and USB 3.0</b> </a> In a regexp, it would look something like this. I want to capture the url. <a href="\.(.*)"> <b>.*</b> </a> How do I go about doing something like this wit...
[ "This can be done quite elegantly using an XPath expression if you don't mind using lxml.\nimport lxml.html as lh\n\nhtml = '''\n<a href=\"./SlimLineUSB3/SlimLine1BayUSB3.php\">\n <b>1 Bay SlimLine with both eSATA and USB 3.0</b>\n</a>\n\n<a href=\"./Some/URL.php\"></a>\n\n<a href=\"./Another/URL.php\">\n <b>...
[ 2, 2 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0008176101_beautifulsoup_python_regex.txt
Q: Are python list comprehensions always a good programming practice? To make the question clear, I'll use a specific example. I have a list of college courses, and each course has a few fields (all of which are strings). The user gives me a string of search terms, and I return a list of courses that match all of the...
Are python list comprehensions always a good programming practice?
To make the question clear, I'll use a specific example. I have a list of college courses, and each course has a few fields (all of which are strings). The user gives me a string of search terms, and I return a list of courses that match all of the search terms. This can be done in a single list comprehension or a few ...
[ "IMHO, they're good programming practice when they're clearer (or at least, no less clear) and more succinct than the alternative. In this case neither option is that clear. Personally, I'd stick the search logic in the Course class. This makes more sense to me as the logic is linked to the class.\nclass Course:\n ...
[ 4, 1, 0 ]
[]
[]
[ "coding_style", "list_comprehension", "python" ]
stackoverflow_0008176168_coding_style_list_comprehension_python.txt
Q: How to run invisible subprocess in Python? I would like to know if it's possible to run Python application subprocess in such way that there wouldn't be duplicate process in task manager? A: Not without getting into subversive process hiding tasks. If as a user that wants to look at the running processes, let m...
How to run invisible subprocess in Python?
I would like to know if it's possible to run Python application subprocess in such way that there wouldn't be duplicate process in task manager?
[ "Not without getting into subversive process hiding tasks. \nIf as a user that wants to look at the running processes, let me see the running processes. Don't hide it from me. \nTechniques to hide running processes may also be picked up by some anti virus as potential threats.\nDon't do it.\nActually, why do you wa...
[ 5, 0 ]
[]
[]
[ "process", "python", "subprocess" ]
stackoverflow_0008176421_process_python_subprocess.txt
Q: Scrapy :: Issues with JSON export So, I have spent quite a bit of time going through the Scrapy documentation and tutorials, and I have since been plugging away at a very basic crawler. However, I am not able to get the output into a JSON file. I feel like I am missing something obvious, but I haven't been able to...
Scrapy :: Issues with JSON export
So, I have spent quite a bit of time going through the Scrapy documentation and tutorials, and I have since been plugging away at a very basic crawler. However, I am not able to get the output into a JSON file. I feel like I am missing something obvious, but I haven't been able to turn anything up after looking at a nu...
[ "JsonItemExporter is fairly simple:\nclass JsonItemExporter(JsonLinesItemExporter):\n\n def __init__(self, file, **kwargs):\n self._configure(kwargs)\n self.file = file\n self.encoder = json.JSONEncoder(**kwargs)\n self.first_item = True\n\n def start_exporting(self):\n self...
[ 1, 1 ]
[]
[]
[ "json", "python", "scrapy", "web_crawler" ]
stackoverflow_0007839559_json_python_scrapy_web_crawler.txt
Q: Python ZipFile path separators If I am unzipping a Zip file with the Python ZipFile library, where the file was created on Windows, but my code is running on Unix-like, will the path separators always be Unix-style? A: Internally, ZipFile stores forward slashes as required by the zip file specification. Externa...
Python ZipFile path separators
If I am unzipping a Zip file with the Python ZipFile library, where the file was created on Windows, but my code is running on Unix-like, will the path separators always be Unix-style?
[ "Internally, ZipFile stores forward slashes as required by the zip file specification. \nExternally, they get translated using os.sep so it will match what is normally expected on a given platform.\nCode references: \n\nhttp://hg.python.org/cpython/file/2.7/Lib/zipfile.py#l295\nhttp://hg.python.org/cpython/file/2...
[ 17 ]
[]
[]
[ "python", "python_zipfile", "zip" ]
stackoverflow_0008176953_python_python_zipfile_zip.txt
Q: Content Migration for a Specific Folder I have a script, migrating Image to a custom type, for my Plone instance. Its partial code sample looks like this: class ImagesToPhotosMigrator(InplaceATItemMigrator): src_portal_type = 'Image' src_meta_type = 'ATBlob' dst_portal_type = 'Photo' dst_meta_type ...
Content Migration for a Specific Folder
I have a script, migrating Image to a custom type, for my Plone instance. Its partial code sample looks like this: class ImagesToPhotosMigrator(InplaceATItemMigrator): src_portal_type = 'Image' src_meta_type = 'ATBlob' dst_portal_type = 'Photo' dst_meta_type = 'Photo' def last_migrate_reindex(self)...
[ "You should have specified that you refer to Products.contentmigration, cause it's not implicit in the words \"content migration\" (lately there are more kind of migrations than lines of code). Anyway, here your solution (CustomQueryWalker is the key):\nfrom Products.contentmigration.walker import CustomQueryWalker...
[ 2 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0008176065_plone_python.txt
Q: OrderedDict performance (compared to deque) I've been trying to performance optimize a BFS implementation in Python and my original implementation was using deque to store the queue of nodes to expand and a dict to store the same nodes so that I would have efficient lookup to see if it is already open. I attempted...
OrderedDict performance (compared to deque)
I've been trying to performance optimize a BFS implementation in Python and my original implementation was using deque to store the queue of nodes to expand and a dict to store the same nodes so that I would have efficient lookup to see if it is already open. I attempted to optimize (simplicity and efficiency) by movin...
[ "Both deque and dict are implemented in C and will run faster than OrderedDict which is implemented in pure Python.\nThe advantage of the OrderedDict is that it has O(1) getitem, setitem, and delitem just like regular dicts. This means that it scales very well, despite the slower pure python implementation. \nComp...
[ 51, 1 ]
[]
[]
[ "algorithm", "optimization", "performance", "python" ]
stackoverflow_0008176513_algorithm_optimization_performance_python.txt
Q: Printing every entry in a list on its own individual line in Python Say I have an array thusly: a = [1, 2, 3, 4] I want to have it be printed like so: 1 2 3 4 but I don't want to go: print(a[0]) print(a[1]) print(a[2]) print(a[3]) I want it to automatically print each entry, but dynamically enough so that it st...
Printing every entry in a list on its own individual line in Python
Say I have an array thusly: a = [1, 2, 3, 4] I want to have it be printed like so: 1 2 3 4 but I don't want to go: print(a[0]) print(a[1]) print(a[2]) print(a[3]) I want it to automatically print each entry, but dynamically enough so that it stops when there is nothing more, but keeps going if there is, if that make...
[ "Join the list together with linefeeds:\nprint '\\n'.join(a)\n\n", "Use a loop:\nfor x in a:\n print x\n\n", "Obligatory Python3 answer:\n[print(k) for k in a]\n\nprint is a function in Python3.\n" ]
[ 7, 5, 0 ]
[]
[]
[ "list", "printing", "python" ]
stackoverflow_0008176763_list_printing_python.txt
Q: Python: Maximum recursion depth exceeded I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node. here is the error: Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x8797...
Python: Maximum recursion depth exceeded
I have the following recursion code, at each node I call sql query to get the nodes belong to the parent node. here is the error: Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored RuntimeError: maximum recursion...
[ "You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:\nimport sys\nsys.setrecursionlimit(10000) # 10000 is an example, try with different values\n\n... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.\n" ...
[ 176 ]
[]
[]
[ "depth", "max", "python", "recursion", "tree_traversal" ]
stackoverflow_0008177073_depth_max_python_recursion_tree_traversal.txt
Q: IP REGEX validation I've been trying to validate an inputted string (sys argv[1] in this case). I need to create a script that goes through a log file and matches the entries for source and destination ip with any argument input with the script. The kinds of valid inputs are either an IP or partial ip "any"(strin...
IP REGEX validation
I've been trying to validate an inputted string (sys argv[1] in this case). I need to create a script that goes through a log file and matches the entries for source and destination ip with any argument input with the script. The kinds of valid inputs are either an IP or partial ip "any"(string which means all ip addr...
[ "When you use re.compile you call the match function on the compiled object: ippattern.match(ip). Also, to get to matched ip from a MatchObject, use MatchObject.group(). Fixed up your example some and it should now do what you need:\n#!/usr/bin/python\n\nimport sys\nimport re\n\ndef ipcheck(ip):\n ippattern_st...
[ 1, 0 ]
[]
[]
[ "loops", "python", "regex", "validation" ]
stackoverflow_0008177261_loops_python_regex_validation.txt
Q: How do I setup PyQt in my station? I watched streaming videos and searched the internet but seems not clear what are the requirement to set up a PyQt on my workstation. What do you need or what do you do in order to program using PyQt? Please state step by step or a link for step by step setup procedure will do. T...
How do I setup PyQt in my station?
I watched streaming videos and searched the internet but seems not clear what are the requirement to set up a PyQt on my workstation. What do you need or what do you do in order to program using PyQt? Please state step by step or a link for step by step setup procedure will do. Thanks.
[ "Assuming your OS is Windows, there are all-in-one binary installers available here. The only other thing you'll need to install is, of course, python itself.\nThe latest PyQt4 reference guide is available here, and the latest Qt Documentation is here.\n" ]
[ 3 ]
[]
[]
[ "installation", "pyqt", "python" ]
stackoverflow_0008177060_installation_pyqt_python.txt
Q: Drawing ellipses on matplotlib basemap projections I am trying to draw ellipses on a basemap projection. To draw a circle like polygon there is the tissot function used to draw Tissot's indicatrix' as illustrates the following example. from mpl_toolkits.basemap import Basemap x0, y0 = 35, -50 R = 5 m = Basemap(w...
Drawing ellipses on matplotlib basemap projections
I am trying to draw ellipses on a basemap projection. To draw a circle like polygon there is the tissot function used to draw Tissot's indicatrix' as illustrates the following example. from mpl_toolkits.basemap import Basemap x0, y0 = 35, -50 R = 5 m = Basemap(width=8000000,height=7000000, resolution='l',projection='...
[ "After hours analyzing the source code of basemap's tissot function, learning some properties of ellipses and lot's of debugging, I came with a solution to my problem. I've extended the basemap class with a new function called ellipse as follows,\nfrom __future__ import division\nimport pylab\nimport numpy\n\nfrom ...
[ 24 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008161144_matplotlib_python.txt
Q: Create class instance in python from list as attributes So I have an object: class Particle(object): def __init__(self, x, y, vx, vy, ax, ay): self._x = int(x) self._y = int(y) self._vx = int(vx) self._vy = int(vy) self._ax = int(ax) self._ay = int(ay) # ...
Create class instance in python from list as attributes
So I have an object: class Particle(object): def __init__(self, x, y, vx, vy, ax, ay): self._x = int(x) self._y = int(y) self._vx = int(vx) self._vy = int(vy) self._ax = int(ax) self._ay = int(ay) # ... I want to create an instance of that object from a list ...
[ "Precede your list name by a star:\ndef foo(a, b, c):\n print(a, b, c)\n\na = [1,2,3]\nfoo(*a)\n# 1 2 3\n\nThe star unpacks the list, which gives 3 separate values.\n", "What you need is called \"unpacking argument lists\". \nHere's an example taken from the tutorial:\n>>> range(3, 6) # normal call...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008177505_python.txt
Q: Splitting a list into a pairs in Python This is a homework. I'm not looking for answers, just a nudge into the right direction. Given a list: ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'] I want to be able to sort the list by pairs: [['The Boy','1:34']['Let go','4:21']['Wherever to', '5:30']] A: Di...
Splitting a list into a pairs in Python
This is a homework. I'm not looking for answers, just a nudge into the right direction. Given a list: ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'] I want to be able to sort the list by pairs: [['The Boy','1:34']['Let go','4:21']['Wherever to', '5:30']]
[ "Difficult without knowing which parts of Python you have been taught so far, but here are some steps that may help\n>>> ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'][::2]\n['The Boy', 'Let go', 'Wherever to']\n>>> ['The Boy','1:34','Let go','4:21','Wherever to', '5:30'][1::2]\n['1:34', '4:21', '5:30']\n...
[ 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008177447_list_python.txt
Q: Django hierarchical model list This should be simple, but I'm shredding my hair just trying to think how to tackle it! I have a navigation menu down the side of my site that is used to pick products. It's formatted like so: Every product belongs in a 'list' (clicking on the list sends to you a page with the list ...
Django hierarchical model list
This should be simple, but I'm shredding my hair just trying to think how to tackle it! I have a navigation menu down the side of my site that is used to pick products. It's formatted like so: Every product belongs in a 'list' (clicking on the list sends to you a page with the list of products). Every list belongs in ...
[ "When I see hierarchical or tree structures, I usually turn to mptt, a modified pre-order traversal tree. Google \"django mptt\" and you will find a large number of tutorials on using the django-mptt package.\n", "Something like this would work:\nfrom __future__ import with_statement\nimport os\nfrom django.templ...
[ 5, 1, 0 ]
[]
[]
[ "django", "hierarchical_data", "model", "nested_lists", "python" ]
stackoverflow_0008177207_django_hierarchical_data_model_nested_lists_python.txt
Q: Django unable to find my custom template tags? I'm creating custom template tags for my django site. I've followed the django documentation for this and have created a templatetags directory in my main application. /project/apps/core/templatetags -/__init__.py -/core_extras.py Si...
Django unable to find my custom template tags?
I'm creating custom template tags for my django site. I've followed the django documentation for this and have created a templatetags directory in my main application. /project/apps/core/templatetags -/__init__.py -/core_extras.py Since I am not sure if this is causing the problem, I ...
[ "It's failing to import because of a syntax error. Django's templating system just swallows it up.\nThis line:\nsite_name = getarrr(settings, \"SITE_NAME\", false)\n\nshould be:\nsite_name = getattr(settings, \"SITE_NAME\", false)\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "templatetags" ]
stackoverflow_0008177662_django_python_templatetags.txt
Q: google appengine - how to configure to send and receive email I've googled a lot on this and I dont know what I'm missing. I have a contact form so users can contact me: contact.html <form id="contact" action="" method="post" name="contact"> <label for="subject">Subject:</label> <input id="id_subject" typ...
google appengine - how to configure to send and receive email
I've googled a lot on this and I dont know what I'm missing. I have a contact form so users can contact me: contact.html <form id="contact" action="" method="post" name="contact"> <label for="subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100"> <label for="email">Ema...
[ "From the App Engine docs\n\nThe email address of the sender, the From address. The sender address\n must be one of the following types:\n\nThe address of a registered administrator for the application. You can add administrators to an application using the Administration\n Console.\nThe address of the user for t...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008177693_google_app_engine_python.txt
Q: Eccentricity estimation in Python I've got a binary numpy array and have labeled the connected regions with scipy.ndimage. Is there a call that I can make to estimate the eccentricity of each labeled section? Edit: I'm trying to develop criteria to find and toss the labeled sections that are much longer than they ...
Eccentricity estimation in Python
I've got a binary numpy array and have labeled the connected regions with scipy.ndimage. Is there a call that I can make to estimate the eccentricity of each labeled section? Edit: I'm trying to develop criteria to find and toss the labeled sections that are much longer than they are wide. In the following array, I mig...
[ "I guess you first need a bit of math. Let first consider you have only one blob labeled as 1. Your matrix label will be a scalar field.\nYou should first compute its average:\n\nwhere is your label (it as no index since it is a scalar).\nThen compute:\n\nA good definition of eccentricity would be the ratio of the...
[ 2, 1 ]
[]
[]
[ "pca", "python" ]
stackoverflow_0008158647_pca_python.txt
Q: Error returned when running imdbpy2sql.py with MySQL database I am working on getting IMDbPY installed and working and I have come to a point where I am working on pulling in all of the data from the flat (text) files in to a (MySQL) database. When I run the appropriate command: imdbpy2sql.py -d /tmp/IMDB/ -u 'my...
Error returned when running imdbpy2sql.py with MySQL database
I am working on getting IMDbPY installed and working and I have come to a point where I am working on pulling in all of the data from the flat (text) files in to a (MySQL) database. When I run the appropriate command: imdbpy2sql.py -d /tmp/IMDB/ -u 'mysql://user:password@host/database' I recieve the following error: ...
[ "You need the Tempita package. Install it using your distribution's package manager - e.g., for Ubuntu it would be \"apt-get install python-tempita\".\n" ]
[ 1 ]
[]
[]
[ "imdbpy", "mysql", "python", "sqlalchemy", "sqlobject" ]
stackoverflow_0008177402_imdbpy_mysql_python_sqlalchemy_sqlobject.txt
Q: Can you assign to a variable defined in a parent function? Possible Duplicate: Python nested functions variable scoping After much trial and error I have eventually discovered that this doesn't work: def a(): def b(): print x x=2 x = 1 b() print x You get an exception (x not defi...
Can you assign to a variable defined in a parent function?
Possible Duplicate: Python nested functions variable scoping After much trial and error I have eventually discovered that this doesn't work: def a(): def b(): print x x=2 x = 1 b() print x You get an exception (x not defined before being referenced). So it looks like b can read from ...
[ "The nonlocal statement in Python 3 will do this.\n\nEdit: In Python 2, there's not a simple way to do it. I suggest you use some mutable container object if you need this capability. For example:\ndef a():\n def b():\n print d[\"x\"]\n d[\"x\"]=2\n d = dict(x=1)\n b()\n print d[\"x\"]\n\n...
[ 6 ]
[]
[]
[ "python", "scope", "variables" ]
stackoverflow_0008178633_python_scope_variables.txt
Q: Python: logging the garbage collector I have a python application that has some performance hiccups. I want to add the garbage collector's events (especially, when does it get called) to my logs. Is it possible? thanks. A: http://docs.python.org/library/gc.html#gc.set_debug You can set the Flags, but they get w...
Python: logging the garbage collector
I have a python application that has some performance hiccups. I want to add the garbage collector's events (especially, when does it get called) to my logs. Is it possible? thanks.
[ "http://docs.python.org/library/gc.html#gc.set_debug\nYou can set the Flags, but they get written to stderr.\nAvailable flags are\ngc.DEBUG_STATS\ngc.DEBUG_COLLECTABLE\ngc.DEBUG_UNCOLLECTABLE\ngc.DEBUG_INSTANCES\ngc.DEBUG_OBJECTS\ngc.DEBUG_SAVEALL\ngc.DEBUG_LEAK\n\nALSO\nWhen you are dealing with performance, you m...
[ 6, 1 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0008179320_garbage_collection_python.txt
Q: sqlalchemy id equality vs reference equality I'm working with SQLAlchemy for the first time and was wondering...generally speaking is it enough to rely on python's default equality semantics when working with SQLAlchemy vs id (primary key) equality? In other projects I've worked on in the past using ORM technologi...
sqlalchemy id equality vs reference equality
I'm working with SQLAlchemy for the first time and was wondering...generally speaking is it enough to rely on python's default equality semantics when working with SQLAlchemy vs id (primary key) equality? In other projects I've worked on in the past using ORM technologies like Java's Hibernate, we'd always override .eq...
[ "Short answer: No, unless you're working with multiple Session objects.\nLonger answer, quoting the awesome documentation:\n\nThe ORM concept at work here is known as an identity map and ensures that all operations upon a particular row within a Session operate upon the same set of data. Once an object with a parti...
[ 11, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008179068_python_sqlalchemy.txt
Q: How to convert current webpage to a text file? I have created one plugin and we need current webpage in the form of plain text file so that we can use that text file as an input to the plugin .How do I do it?? A: import urllib url = "http://google.com" text = urllib.open(url)
How to convert current webpage to a text file?
I have created one plugin and we need current webpage in the form of plain text file so that we can use that text file as an input to the plugin .How do I do it??
[ "import urllib\nurl = \"http://google.com\"\ntext = urllib.open(url)\n\n" ]
[ 1 ]
[]
[]
[ "python", "text_files", "webpage" ]
stackoverflow_0005216499_python_text_files_webpage.txt
Q: Mako, Babel and string interpolation I'm trying to do something like this: ${_('Hello ${name}, welcome to...', mapping=dict(name='${name}'))} Where _() is my Babel translation function, the first ${name} is string interpolation I'd like to be performed by Babel and the second ${name} I'd like to be replaced by Mak...
Mako, Babel and string interpolation
I'm trying to do something like this: ${_('Hello ${name}, welcome to...', mapping=dict(name='${name}'))} Where _() is my Babel translation function, the first ${name} is string interpolation I'd like to be performed by Babel and the second ${name} I'd like to be replaced by Mako so the value is the value in the Python ...
[ "Why not use Python's string formatting?\n${ _('Hello {name}, welcome to ...').format(name=name) }\n\n" ]
[ 3 ]
[]
[]
[ "mako", "python", "python_babel" ]
stackoverflow_0008177733_mako_python_python_babel.txt
Q: Python programming help? I have been trying to make a cash register like code, where the user types in their product name the price and the quantity. I have four products. After doing all the adding for these i need to get the 5% GST and then print out the total amount including the GST. This is what i could come ...
Python programming help?
I have been trying to make a cash register like code, where the user types in their product name the price and the quantity. I have four products. After doing all the adding for these i need to get the 5% GST and then print out the total amount including the GST. This is what i could come with so far and i am new to py...
[ "I see many strange things here. I would recommend the following approach:\n\nWrite your program so that it can handle a single product. \nThen add a second product.\nNow think about a loop.\n\nIf you have trouble with a specific step, ask a question here.\n", "What is sum_total? \nYou are writing\nsum_total = so...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008179902_python.txt
Q: How to pass class's self through a flask.Blueprint.route decorator? I am writing my website's backend using Flask and Python 2.7, and have run into a bit of a problem. I like to use classes to enclose my functions, it makes things neat for me and helps me keep everything modular. One problem I'm having, though, is...
How to pass class's self through a flask.Blueprint.route decorator?
I am writing my website's backend using Flask and Python 2.7, and have run into a bit of a problem. I like to use classes to enclose my functions, it makes things neat for me and helps me keep everything modular. One problem I'm having, though, is that the decorators flask uses for routing doesn't preserve the self var...
[ "There is an error if you add self because the method works the same as a function for the decorator, and the flask isn't expecting a function with a first argument self.\nLet's look at the code of route : https://github.com/pallets/flask/blob/master/src/flask/blueprints.py#L52\nIt calls self.add_url_rule (self bei...
[ 8 ]
[]
[]
[ "decorator", "flask", "python" ]
stackoverflow_0008179558_decorator_flask_python.txt
Q: How does django-nose differ from the default Django test-runner I've been seeing and reading about a lot of people using nose to run their Django tests. I haven't been able to figure out the added benefits of using Nose to run my Django tests. If someone could fill me in on what nose is and how it adds more to a D...
How does django-nose differ from the default Django test-runner
I've been seeing and reading about a lot of people using nose to run their Django tests. I haven't been able to figure out the added benefits of using Nose to run my Django tests. If someone could fill me in on what nose is and how it adds more to a Django project, it would be helpful. I haven't been able to find a goo...
[ "I was curious about this too and it seems that the main advantage of django-nose using the python nose library is \"Test Discovery\".\nIn addition, from http://readthedocs.org/docs/nose/en/latest/testing.html\n\nyou can also write simple test functions, as well as test classes that are not\n subclasses of unittes...
[ 3, 2 ]
[]
[]
[ "django", "nose", "python" ]
stackoverflow_0007846564_django_nose_python.txt
Q: Any documentation for the package subnets-resolver? I am a new user of python and would like to try subnets-resolver. However, I can`t find the documentation of this package. Can someone point me to it? A: It seems you are out of luck. Google does not bring anything up, and the code contains no docstrings (quite...
Any documentation for the package subnets-resolver?
I am a new user of python and would like to try subnets-resolver. However, I can`t find the documentation of this package. Can someone point me to it?
[ "It seems you are out of luck. Google does not bring anything up, and the code contains no docstrings (quite unpythonic). You will have to figure it out yourself. You could write a documentation in the process and and make it available for others though.\n" ]
[ 0 ]
[]
[]
[ "pypi", "python" ]
stackoverflow_0008180098_pypi_python.txt
Q: Create different distribution types with setup.py Given the following (demonstration) project layout: MyProject/ README LICENSE setup.py myproject/ ... # packages extrastuff/ ... # some extra data How (and where) do I declare different distribution types? Especially I need thes...
Create different distribution types with setup.py
Given the following (demonstration) project layout: MyProject/ README LICENSE setup.py myproject/ ... # packages extrastuff/ ... # some extra data How (and where) do I declare different distribution types? Especially I need these two options: A distribution containing only the sour...
[ "I've implemented something like this before ... the sdist command can be extended to handle additional command line arguments and to manipulate the data files based on these. If you run python setup.py sdist --help, it'll include your custom command line arguments in the help, which is nice. Use the following reci...
[ 11, 3 ]
[]
[]
[ "python", "setup.py", "setuptools" ]
stackoverflow_0008064823_python_setup.py_setuptools.txt
Q: Building OpenSSL to compile portable version of Python I am trying to build Python from source and need to include the SSL module for my web scraper to work with it. I ran into the problem of SSL not being found, so I downloaded and built OpenSSL from source. The problem is, I need to install the development libra...
Building OpenSSL to compile portable version of Python
I am trying to build Python from source and need to include the SSL module for my web scraper to work with it. I ran into the problem of SSL not being found, so I downloaded and built OpenSSL from source. The problem is, I need to install the development libraries along with OpenSSL in order for Python to run the -lssl...
[ "The default OpenSSL build should install the appropriate header files and libraries using make install, just make sure to provide the right prefix to the configure script (e.g., ./configure --prefix=/usr).\nIf this fails, please post the exact error that gcc shows.\nBy the way, please consider using an automated t...
[ 1, 1, 1 ]
[]
[]
[ "linux", "openssl", "python" ]
stackoverflow_0004862598_linux_openssl_python.txt
Q: python + auto ssh proccess to get date info I need to perform on my linux 5.3 ssh [Linux machine red hat 5.3] date in order to get the date results , during ssh need to answer on the following question (yes/no)? --> yes password: --> diana_123 and then I will get the date results please advice how to d...
python + auto ssh proccess to get date info
I need to perform on my linux 5.3 ssh [Linux machine red hat 5.3] date in order to get the date results , during ssh need to answer on the following question (yes/no)? --> yes password: --> diana_123 and then I will get the date results please advice how to do this automated process with python? ( on my Lin...
[ "You can skip the host key check by passing the StrictHostKeyChecking=no parameter to ssh:\nssh -oStrictHostKeyChecking=no 103.116.140.151 date\n\nI don't think it's possible to do the same for the password. The correct way to bypass SSH's password prompt is with a restricted passphraseless key: see here for detai...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008180404_python.txt
Q: Remove top and right axis in matplotlib after increasing margins? Generate figure with desired size and margins: fig = plt.figure(figsize=(3,5)) ax = plt.Axes(fig,[left,bottom,width,height]) fig.add_axes(ax) This along with legends, gridlines and everything else gives me what i'm expecting, except i can not remov...
Remove top and right axis in matplotlib after increasing margins?
Generate figure with desired size and margins: fig = plt.figure(figsize=(3,5)) ax = plt.Axes(fig,[left,bottom,width,height]) fig.add_axes(ax) This along with legends, gridlines and everything else gives me what i'm expecting, except i can not remove the top and right axis. I referred to a similar question here, which ...
[ "Here is a solution which shows two possible ways to solve your problem:\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid.axislines import Subplot\n\nleft,bottom,width,height= -0.02 , 0.12, 1, 0.9\nfig = plt.figure(figsize=(3,5))\nax1 = plt.Axes(fig,[left,bottom,width,height])\nax1.plot([1,2,3,4],'b') ...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008176458_matplotlib_python.txt
Q: Windows Error: errors happened while running xgettext on __init__.py ,'xgettext' is not recognizad as an internal or external command when running django-admin.py makemessages -l fa based on internationalization documentations in windows i get this error: Windows Error: errors happened while running xgettext on __...
Windows Error: errors happened while running xgettext on __init__.py ,'xgettext' is not recognizad as an internal or external command
when running django-admin.py makemessages -l fa based on internationalization documentations in windows i get this error: Windows Error: errors happened while running xgettext on __init__.py ,'xgettext' is not recognizad as an internal or external command what should I install and which variables add to environment?I ...
[ "This is covered in the documentation.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008181143_django_python.txt
Q: How to use a memory mapped file from Python and pass it to an external API that requires a filename? I have to call, from Python 2.5, an external API (win32) that request me to provide a filename and return a result. In order to speedup the process I don't want to save the data into a classic file and I would pref...
How to use a memory mapped file from Python and pass it to an external API that requires a filename?
I have to call, from Python 2.5, an external API (win32) that request me to provide a filename and return a result. In order to speedup the process I don't want to save the data into a classic file and I would prefer to save it in memory and release it after the API call returns. The external function does need only r...
[ "have you tried using a named pipe ? \non Windows, a named pipe can be accessed using standard file functions (CreateFile(), ReadFile(), WriteFile()...), using a special filename of the form \\\\.\\pipe\\name. your external API may be able to read from the pipe, a pipe that you would create from your python script ...
[ 0 ]
[]
[]
[ "mmap", "python" ]
stackoverflow_0008154986_mmap_python.txt
Q: How to access a block of memory as a file object in Python 2.5? I would like to get a file object for a block of memory in Python 2.5 under Windows.(for some reasons I cannot use newer versions for this tasks.) So as input I do have a pointer and a size and let's assume that I need only read only access. In case y...
How to access a block of memory as a file object in Python 2.5?
I would like to get a file object for a block of memory in Python 2.5 under Windows.(for some reasons I cannot use newer versions for this tasks.) So as input I do have a pointer and a size and let's assume that I need only read only access. In case you'll wonder, I got these by using ctypes and I need to make them ava...
[ "You should use ctypes in there. As of Python 2.5 ctypes where already on the standard library, so a \"win\" situation for you.\nWith ctypes you can construct a python object representing a higher level pointe doing this:\nimport ctypes \ninteger_pointer_type = ctypes.POINTER(ctypes.c_int)\nmy_pointer = integer_...
[ 6, 1 ]
[]
[]
[ "ctypes", "python", "python_2.5" ]
stackoverflow_0008181012_ctypes_python_python_2.5.txt
Q: Converting numbers that start with zeros Can anyone explain the following to me please. i = 700001 z = str(i % 100000) z='1', but i want to z='00001'. How i can get it? A: Do this: z = '{:05}'.format(i % 100000) A: Another solution: >>> z.zfill(5) '00001' A: Use str.rjust >>> s = '1' >>> s.rjust(5, '0') '00...
Converting numbers that start with zeros
Can anyone explain the following to me please. i = 700001 z = str(i % 100000) z='1', but i want to z='00001'. How i can get it?
[ "Do this:\nz = '{:05}'.format(i % 100000)\n\n", "Another solution:\n>>> z.zfill(5)\n'00001'\n\n", "Use str.rjust\n>>> s = '1'\n>>> s.rjust(5, '0')\n'00001'\n\n", "See Python string formatting:\nz = '%05d'%(i % 100000)\n\n" ]
[ 6, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008182012_python.txt
Q: Python LDAP Search I've been reading on how to search LDAP servers using Python, but Ive been stuck for hours and Im not sure why. This is my first time trying to use this sort of API. Heres how I open the connection and try to search: aims_server = '#####.com' base_dn = 'cn=EMPLOYEES,cn=portal,cn=Groups,dc=Compan...
Python LDAP Search
I've been reading on how to search LDAP servers using Python, but Ive been stuck for hours and Im not sure why. This is my first time trying to use this sort of API. Heres how I open the connection and try to search: aims_server = '#####.com' base_dn = 'cn=EMPLOYEES,cn=portal,cn=Groups,dc=Company,dc=com' username = 'cn...
[ "I finally did it and it only took me over 5 hours.\nEvery time I messed around with a configuration I learnt a bit more but I basically had to try every combination to get it to work.\nIt turns out that I was probably being too specific with the base_dn, so I changed that to a higher level\nbase_dn = 'cn=users,dc=...
[ 10, 0 ]
[]
[]
[ "ldap", "python", "search" ]
stackoverflow_0008170924_ldap_python_search.txt
Q: GAE Python bingapi wrapper ImportError So here is my problem: I am trying to use the bing api wrapper available here I basically downloaded the egg file and installed it according to the guidelines. When I run the sample code from command line it works fine. However, I am trying to integrate this wrapper into the...
GAE Python bingapi wrapper ImportError
So here is my problem: I am trying to use the bing api wrapper available here I basically downloaded the egg file and installed it according to the guidelines. When I run the sample code from command line it works fine. However, I am trying to integrate this wrapper into the Python Google App Engine application that I...
[ "dev_appserver.py mimics the production environment, so it blocks access to any libraries that won't be available in production, including anything installed on your system outside of your application directory. To use third-party libraries with App Engine, they must be installed in your application directory, wher...
[ 2 ]
[]
[]
[ "bing_api", "google_app_engine", "python" ]
stackoverflow_0008178565_bing_api_google_app_engine_python.txt
Q: Twisted: how to get error parameters from failure? I have a piece of code: from twisted.web.client import getPage from twisted.internet import reactor class TestError(Exception): def __init__(self, message): self.message = message def __repr__(self): return 'TestError' def gotPage(respons...
Twisted: how to get error parameters from failure?
I have a piece of code: from twisted.web.client import getPage from twisted.internet import reactor class TestError(Exception): def __init__(self, message): self.message = message def __repr__(self): return 'TestError' def gotPage(response): print response reactor.stop() def gotErr(fa...
[ "If by error parameters you mean the exception instances, then Failure.value.\n" ]
[ 1 ]
[]
[]
[ "custom_errors", "deferred", "python", "twisted" ]
stackoverflow_0008181990_custom_errors_deferred_python_twisted.txt
Q: Python print to stderr in generator Building a python fuse fs, in my readdir generator the first line of code is a print statement. This never appeared on my console. I modified it to a print to stderr as i thought it was a buffering issue. Still no output. I added a manual flush to the next line - still nothing....
Python print to stderr in generator
Building a python fuse fs, in my readdir generator the first line of code is a print statement. This never appeared on my console. I modified it to a print to stderr as i thought it was a buffering issue. Still no output. I added a manual flush to the next line - still nothing. I added a time.sleep(3) to the next line...
[ "Your FUSE code runs under the control of FUSE library, so you can't be sure that stdin, stdout and stderr are the ones in your terminal session.\nIt's quite possible that the readdir generator is called with alternate std* streams.\nSince you say that other parts of your FUSE code print without any issues, you mig...
[ 1 ]
[]
[]
[ "fuse", "python" ]
stackoverflow_0007940595_fuse_python.txt
Q: How can I insert html code from outern url in django template? I need something like file_get_contents in PHP. I kwnow it's some like: import urllib2 urllib2.urlopen(url).read() but how can I put it in django html template? Thx for fast answers. A: You cannot put that directly into django's html templating lan...
How can I insert html code from outern url in django template?
I need something like file_get_contents in PHP. I kwnow it's some like: import urllib2 urllib2.urlopen(url).read() but how can I put it in django html template? Thx for fast answers.
[ "You cannot put that directly into django's html templating language. You might consider:\n\nPrefetching the html, store it somewhere and render it to the template.\nUse an ajax call, that triggers a view that does the crawling, then on success you insert your html in the DOM (this is blocking and slow at server-si...
[ 2 ]
[]
[]
[ "django", "html", "python" ]
stackoverflow_0008182942_django_html_python.txt
Q: Popup Dialog in Tkinter/Python I need to add a popup dialog box on my GUI. So, when ever I hover my mouse over a label, it should be able to show a popup( Like the type we get while hovering over a file in windows). It should also disappear as soon i move away the mouse. To start with, I am not even sure which mo...
Popup Dialog in Tkinter/Python
I need to add a popup dialog box on my GUI. So, when ever I hover my mouse over a label, it should be able to show a popup( Like the type we get while hovering over a file in windows). It should also disappear as soon i move away the mouse. To start with, I am not even sure which module or class to use. I tried menu, ...
[ "The little popup window is called a tooltip.\n", "This post may be relevant: http://bytes.com/topic/python/answers/505848-tkinter-button-overrelief\n", "Take a look at the Balloon widget in the Tix package. I think it is just what you are looking for.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "popup", "python", "tk_toolkit", "tkinter", "ttk" ]
stackoverflow_0008163195_popup_python_tk_toolkit_tkinter_ttk.txt
Q: Creating pythonic objects that share memory I'm trying to create an object in python which is composed of smaller objects. Each of the objects has its own meaning - each of the smaller objects and the entire object as a whole. The problem is that I want each of the 3 objects to be seemingly independently addressab...
Creating pythonic objects that share memory
I'm trying to create an object in python which is composed of smaller objects. Each of the objects has its own meaning - each of the smaller objects and the entire object as a whole. The problem is that I want each of the 3 objects to be seemingly independently addressable and to operate as standalone objects and this ...
[ "Two alternatives:\nYou can use C and a CPython wrapper... Or you can use properties:\nclass Control(object):\n def __init__(self, word=0):\n self.word = word\n def get_low(self):\n return self.word & 0xFF\n def set_low(self, x):\n self.word &= 0xFF0...
[ 4, 1 ]
[ "If I understand you correctly, this is extremely easy to achieve in Python.\nmy_obj1 = Object1()\nmy_obj2 = Object2()\nmy_parent_obj = Object3()\nmy_parent_obj.obj1 = my_obj1\nmy_parent_obj.obj2 = my_obj2\n\nNow the object1 and object2 instances are addressable both independently as my_obj1 and as part of the pare...
[ -1 ]
[ "c", "pointers", "python" ]
stackoverflow_0008182714_c_pointers_python.txt
Q: Better way to find existence of arrays in list of arrays I am a newbie to Python and trying out different ways to optimize and simplify my code. I have a list of arrays(necessarily in this format) initially empty, which I need to update with arrays, making sure that duplicate entries are not added. Right now I am ...
Better way to find existence of arrays in list of arrays
I am a newbie to Python and trying out different ways to optimize and simplify my code. I have a list of arrays(necessarily in this format) initially empty, which I need to update with arrays, making sure that duplicate entries are not added. Right now I am doing it the following way, which is the only thing i tried ou...
[ "\nEdit: I see from your comment that you're using numpy arrays. I've never used numpy so I have no idea how they work with sets.\n\nOne option would be to use a set. Sets are like lists but they are unordered and only allow each item to be added once:\n>>> s = set()\n>>> s.add(1)\n>>> s.add(2)\n>>> s.add(2)\n>>> ...
[ 1, 0 ]
[]
[]
[ "arraylist", "numpy", "optimization", "python", "unique" ]
stackoverflow_0008183239_arraylist_numpy_optimization_python_unique.txt
Q: Retrieving characters from a string using google app I have written a small python program inside my google app. I am using it for extracting out specific characters out of a string like this "+CMGL: 14,"REC READ","+918000459019",,"11/11/04,18:27:53+22" C " I am using split function for it but it'...
Retrieving characters from a string using google app
I have written a small python program inside my google app. I am using it for extracting out specific characters out of a string like this "+CMGL: 14,"REC READ","+918000459019",,"11/11/04,18:27:53+22" C " I am using split function for it but it's not splitting the string.Any clues why? it's giving me s...
[ "The splits in the first part of your function ought to work. Here's an experiment I just did in Python 2.6:\n>>> s = '+CMGL: 14,\"REC READ\",\"+918000459019\",,\"11/11/04,18:27:53+22\"\\n C '\n>>> s.split('\\n')\n['+CMGL: 14,\"REC READ\",\"+918000459019\",,\"11/11/04,18:27:53+22\"', ' C ']\n>>> s.split(',')\n['+CM...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008182894_google_app_engine_python.txt
Q: Passing date time in a different format to models.DateTimeField in Django? I have a model that looks something like this class Post(models.Model): id = models.IntegerField(unique=True, primary_key=True) title = models.CharField(max_length=150, blank=True) created = models.DateTimeField(blank=True) ...
Passing date time in a different format to models.DateTimeField in Django?
I have a model that looks something like this class Post(models.Model): id = models.IntegerField(unique=True, primary_key=True) title = models.CharField(max_length=150, blank=True) created = models.DateTimeField(blank=True) ... I have to fill the database with chunks of data. I am getting the data in f...
[ "Subclass DateTimeField and convert the value appropriately:\nclass ConvertingDateTimeField(models.DateTimeField):\n\n def get_prep_value(self, value):\n return str(datetime.strptime(value, FORMAT_STRING))\n\nThen use ConvertingDateTimeField to replace models.DateTimeField.\nThere's probably a better way ...
[ 7, 3, 1, 0 ]
[]
[]
[ "datetime", "django", "django_models", "python" ]
stackoverflow_0008172041_datetime_django_django_models_python.txt
Q: Parse JSON response object in IE8 I am using qq uploader for file uploads with Django. It works fine in modern browsers like FF/Chrome. I have also made some progress in making it work more or less properly in IE8. My issue is that when I upload a file and receive a JSON response from server, looks like this: {"su...
Parse JSON response object in IE8
I am using qq uploader for file uploads with Django. It works fine in modern browsers like FF/Chrome. I have also made some progress in making it work more or less properly in IE8. My issue is that when I upload a file and receive a JSON response from server, looks like this: {"success":true,"url":"/media/campaigns/201...
[ "I tried playing with mimetype on server side. application/json made IE download the response as a file, and 'text/plain' made it surround response with <pre></pre>. Then I tried text/html and now response is evaluated properly so I can get values.\n" ]
[ 3 ]
[]
[]
[ "javascript", "json", "python" ]
stackoverflow_0008182470_javascript_json_python.txt
Q: ValueError: invalid literal for int() with base 10: '01234SS' I'll like to know, why I'm getting "invalid literal for int() with base 10 error" but works pretty well in the interactive mode? fees = {u'nid':u'179', u'type':u'fees', u'jamb_no': u'01234SS'} for fee in fees: # Transaction model try: ...
ValueError: invalid literal for int() with base 10: '01234SS'
I'll like to know, why I'm getting "invalid literal for int() with base 10 error" but works pretty well in the interactive mode? fees = {u'nid':u'179', u'type':u'fees', u'jamb_no': u'01234SS'} for fee in fees: # Transaction model try: txn = Transaction() txn.nid = int(fee.get(u'nid')) ...
[ "The problem has to do with celery. When I make changes to tasks.py, celery need to be restarted. This I didn't do, which obviously is causing a repetitive error messages even when the state has changed.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008168102_django_python.txt
Q: Django, Postgresql & IntegrityErrors I come from a mysql background where if I want to insert a record I can use an INSERT IGNORE command so that I can just bung rows in and if there's a conflict just ignore it. Now, with a Django project I'm working on I'm using postgresql, and issue multiple saves in a loop. Ho...
Django, Postgresql & IntegrityErrors
I come from a mysql background where if I want to insert a record I can use an INSERT IGNORE command so that I can just bung rows in and if there's a conflict just ignore it. Now, with a Django project I'm working on I'm using postgresql, and issue multiple saves in a loop. However, I think if I get an IntegrityError ...
[ "It will depend on how you manage your transaction.\nOn Postgres if one of query in transaction fails all subsequent query will also fail with error \"current transaction is aborted, queries ignored until end of transaction block\".\nTo deal with it you should use transaction.savepoint_rollback in an except block.\...
[ 8, 1 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0008183700_django_postgresql_python.txt
Q: Django: Query where GenericRelation is null I'd like to query a model for instances where the generic relation field is not empty (that is, in the example below I'm looking for instances where document.count() > 0): class Report(models.Model): document = generic.GenericRelation(Document) Something like: Rep...
Django: Query where GenericRelation is null
I'd like to query a model for instances where the generic relation field is not empty (that is, in the example below I'm looking for instances where document.count() > 0): class Report(models.Model): document = generic.GenericRelation(Document) Something like: Report.objects.filter(date__gte=twomonths).exclude(d...
[ "I believe there still may be some contradictions in your question. Note: \"I'm looking for instances where document.count() == 0\" and then later, \"Unfortunately this doesn't work - the query returns objects that have no 'document' (ie. it returns objects where document.count() is 0)\".\nIf you want Reports that ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008184854_django_python.txt
Q: comparing lists python im trying to compare between one list and 3 other lists with the same number of indexes. for example I have this list [A, B, C] and I have created with a certain function another list with random nested lists such as: [[A ,B ,B], [C, B, A], [B, B, C]] but I want to compare each nested l...
comparing lists python
im trying to compare between one list and 3 other lists with the same number of indexes. for example I have this list [A, B, C] and I have created with a certain function another list with random nested lists such as: [[A ,B ,B], [C, B, A], [B, B, C]] but I want to compare each nested list to the original list and...
[ "You can do it like this:\nfrom itertools import izip\ndef matches(input_lists, base_list):\n for l in input_lists:\n yield sum(1 for a, b in izip(l, base_list) if a==b)\n\nand the result will be following:\n>>> for i in matches([[1,2,3],[2,3,1],[0,2,0]], [1,2,4]):\n i\n\n\n2\n0\n1\n\nwhich works as ex...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008184768_python.txt
Q: Callback chain with independent data, not related to the chain I am trying to perform a simple callback sequence in twisted. The idea is that I login to a service, and when the login has succeeded, I start sending commands. This is my code: from twisted.internet import reactor, defer class MyService: ...
Callback chain with independent data, not related to the chain
I am trying to perform a simple callback sequence in twisted. The idea is that I login to a service, and when the login has succeeded, I start sending commands. This is my code: from twisted.internet import reactor, defer class MyService: def __init__ (self): self.handle = None def login(s...
[ "Easy, the handler must have result as its first argument:\ndef sendCommand(self, in_result, command):\n do_the_stuff\n\n" ]
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008167513_python_twisted.txt
Q: Python subprocess Module - Popen method with -exec in bash find command I am using the subprocess module in Python (python 2.6) with the Popen method. What I am trying to achieve: I am trying to use the following bash command with Popen that will return a match if it finds a file with "stderr" string. The code: ba...
Python subprocess Module - Popen method with -exec in bash find command
I am using the subprocess module in Python (python 2.6) with the Popen method. What I am trying to achieve: I am trying to use the following bash command with Popen that will return a match if it finds a file with "stderr" string. The code: bash find . -exec grep "stderr" {} + what I am doing in python from subprocess...
[ "Try making your command a list of arguments:\ncommand = \"find . -exec grep 'stderr' {} +\".split(\" \")\n\nEdit: Sorry, I didn't realize Popen() could take a string. This answer is not correct.\n", "Why are you using the subprocess module?\nWould this code, from Mr. Beazley, do the job?\nimport os\nimport fnmat...
[ 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0008184973_bash_python.txt
Q: What is the good db property, for an keys's array for python with App Engine? For the moments bars represents a String with all the Bar ids with ';' separator like 6;5;9;15 class Foo(db.Model): id = db.StringProperty(multiline=True) name = db.StringProperty(multiline=True) bars = db.TextProperty() ...
What is the good db property, for an keys's array for python with App Engine?
For the moments bars represents a String with all the Bar ids with ';' separator like 6;5;9;15 class Foo(db.Model): id = db.StringProperty(multiline=True) name = db.StringProperty(multiline=True) bars = db.TextProperty() class Bar(db.Model): id = db.StringProperty(multiline=True) name = db.Stri...
[ "For a start, you never want to store multiple values inside a single textfield. AppEngine's datastore supports multi-valued properties (such as ListProperty): you should use those.\nThat said, there's no multi-valued equivalent of ReferenceProperty built in. This article on the AppEngine documentation site gives a...
[ 1, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0008185255_django_google_app_engine_python.txt
Q: Unknown error when submit a REST request to Liferay json API I'm writing an script in Python to automatically update the structures in my Liferay portal and I want to do it via the json REST API. I make a request to get an structure (method getStructure), and it worked. But when I try to do an structure update in ...
Unknown error when submit a REST request to Liferay json API
I'm writing an script in Python to automatically update the structures in my Liferay portal and I want to do it via the json REST API. I make a request to get an structure (method getStructure), and it worked. But when I try to do an structure update in the portal it shows me the following error: ValueError: Content-L...
[ "This might help you. It seems it is python's bug.\n" ]
[ 1 ]
[]
[]
[ "json", "liferay", "python", "rest", "xsd" ]
stackoverflow_0008180476_json_liferay_python_rest_xsd.txt
Q: Only Firefox displays HTML Code and not the page I have this complicated problem that I can't find a answer to. I have a Python HTTPServer running that serves webpages. These webpages are created at runtime with help of Beautiful Soup. Problem is that the Firefox shows HTML Code for the webpage and not the actual ...
Only Firefox displays HTML Code and not the page
I have this complicated problem that I can't find a answer to. I have a Python HTTPServer running that serves webpages. These webpages are created at runtime with help of Beautiful Soup. Problem is that the Firefox shows HTML Code for the webpage and not the actual page? I really don't know know who is causing this pro...
[ "Why are you adding this at the top of the document?\n<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n\nThat will make the browser think the entire document is XML and not XHTML. Removing that line should make it render correctly. I assume Firefox is displaying a page with a bunch of elements which you can expand/...
[ 2, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "simplehttpserver" ]
stackoverflow_0008174757_beautifulsoup_html_python_simplehttpserver.txt
Q: Django-powered library checkout system I am working on a library system to manage certain items in our office, I don't need a full-blown integrated library system so I decided to hand roll one with Django. Below is a simplified version of my model: class ItemObjects(models.Model): # Static Variables IN_STATUS ...
Django-powered library checkout system
I am working on a library system to manage certain items in our office, I don't need a full-blown integrated library system so I decided to hand roll one with Django. Below is a simplified version of my model: class ItemObjects(models.Model): # Static Variables IN_STATUS = 'Available' OUT_STATUS = 'Checke...
[ "Assuming users will log in and check out books to themselves, then what you most likely want is a ForeignKey to User. A book will only have one User at any given time, but presumably Users could check out other items as well. If there is some limit, even if the limit is actually one per user, it would be better to...
[ 3 ]
[]
[]
[ "checkout", "django", "forms", "python" ]
stackoverflow_0008185174_checkout_django_forms_python.txt
Q: reportlab: add background image by using platypus this is a bit related to this post I am trying to place an image on the background, and I want to be able to write text over it. using canvas.drawImage helps, but that's too low level approach for me. My program uses platypus, but canvas.drawImage is part of diffe...
reportlab: add background image by using platypus
this is a bit related to this post I am trying to place an image on the background, and I want to be able to write text over it. using canvas.drawImage helps, but that's too low level approach for me. My program uses platypus, but canvas.drawImage is part of different library. I've been able to insert images with plat...
[ "When you create a page template in Platypus you have the ability to pass a function via the named argument onPage. In that function you can place all your basic page formatting (headers, footers, watermark, background image).\nHere's an example:\ndef AllPageSetup(canvas, doc):\n\n canvas.saveState()\n\n #he...
[ 12 ]
[]
[]
[ "image", "platypus", "python", "reportlab" ]
stackoverflow_0008185438_image_platypus_python_reportlab.txt
Q: Windows WlanApi and Python Ctypes I'm working on a captive portal projet on Windows. I've written this piece of code (similar to this) : from ctypes import wintypes import ctypes WlanApi = ctypes.windll.wlanapi hClientHandle = wintypes.HANDLE() phClientHandle = ctypes.pointer(hClientHandle) dwNegotiatedVersion =...
Windows WlanApi and Python Ctypes
I'm working on a captive portal projet on Windows. I've written this piece of code (similar to this) : from ctypes import wintypes import ctypes WlanApi = ctypes.windll.wlanapi hClientHandle = wintypes.HANDLE() phClientHandle = ctypes.pointer(hClientHandle) dwNegotiatedVersion = wintypes.DWORD() pdwNegotiatedVersion ...
[ "It's just an integer, there is no structure 0 = Not ready, 1 = connected etc.\n", "Hmm it starts to make sense,as most of these structs have a corresponding pointer.\nAccording to the boys at PInvoke\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\npublic struct WLAN_INTERFACE_INFO\n{\n /// G...
[ 0, 0 ]
[]
[]
[ "ctypes", "python", "wifi", "windows" ]
stackoverflow_0008043924_ctypes_python_wifi_windows.txt
Q: How to distribute / access data files in Python egg? I'm writing a Django application that is using pip & virtualenv to manage its development environment. One of the dependencies, pkgme, comes with many data files which are its "backends" and are configured in its setup.py with data_files=$FOO (rather than packag...
How to distribute / access data files in Python egg?
I'm writing a Django application that is using pip & virtualenv to manage its development environment. One of the dependencies, pkgme, comes with many data files which are its "backends" and are configured in its setup.py with data_files=$FOO (rather than package_data). When pkgme looks for its backends, it looks in os...
[ "Your current plan is essentially correct, or is at any rate a workable option.\nWhen setuptools creates an egg, it checks whether code in the egg makes use of __file__, and if so, it marks the egg as not being installable in compressed form. In this way, when the egg is installed by easy_install, it'll get extrac...
[ 2, 1 ]
[]
[]
[ "distutils", "egg", "python", "setuptools" ]
stackoverflow_0008137410_distutils_egg_python_setuptools.txt
Q: How can I parse a line by new lines and colons? I have text like this. I want to split by New Line and Colons. Right now I'm splitting by New Lines.I'm using this code. `data= data.split('\n') and Its giving strange output. Can you please help? thanks A: \t are tabs. To clean things a bit, try this: data = [li...
How can I parse a line by new lines and colons?
I have text like this. I want to split by New Line and Colons. Right now I'm splitting by New Lines.I'm using this code. `data= data.split('\n') and Its giving strange output. Can you please help? thanks
[ "\\t are tabs. To clean things a bit, try this:\ndata = [line.strip().split(':') for line in data.split('\\n') if line.strip()]\n\nit will remove empty lines and strip whitespaces\n", "It's doing just what you're asking, but it's full of tabs. Remove the tabs via strip():\nlines = data.split('\\n')\nlines = [lin...
[ 8, 7, 3, 0, 0 ]
[]
[]
[ "python", "regex", "split" ]
stackoverflow_0008186086_python_regex_split.txt
Q: Resizable divider line in wxpython? I am not sure what they are called, but I would like a resizable divider line, to separate widgets. I would like something like this (except horizontal): http://imm.io/bKgf If you do not know what i am talking about please comment, thanks and sorry for my ignorance. A: You nee...
Resizable divider line in wxpython?
I am not sure what they are called, but I would like a resizable divider line, to separate widgets. I would like something like this (except horizontal): http://imm.io/bKgf If you do not know what i am talking about please comment, thanks and sorry for my ignorance.
[ "You need, maybe, a splitterwindow:\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent):\n wx.Frame.__init__(self, parent)\n self.splitter = wx.SplitterWindow(self)\n\n pan1 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)\n pan1.SetBackgroundColour(\"yellow\")\n ...
[ 7, 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008182621_python_wxpython.txt
Q: compare object to empty tuple with the 'is' operator in Python 2.x I'm used to seeing if obj is None: in Python, and I've recently come across if obj is ():. Since tuples are not mutable, it sounds like a reasonable internal optimization in the Python interpreter to have the empty tuple be a singleton, therefore ...
compare object to empty tuple with the 'is' operator in Python 2.x
I'm used to seeing if obj is None: in Python, and I've recently come across if obj is ():. Since tuples are not mutable, it sounds like a reasonable internal optimization in the Python interpreter to have the empty tuple be a singleton, therefore allowing the use of is rather than requiring ==. But is this guaranteed ...
[ "From the Python 2 docs and Python 3 docs:\n\n... two occurrences of the empty tuple may or may not yield the same object.\n\nIn other words, you can't count on () is () to evaluate as true. \n", "Let's use the id() method to get the internal id of the () :\n>>> id(())\n140180995895376\n>>> empty_tuple = ()\n>>> ...
[ 12, 0, 0 ]
[ "It's not about optimization. It's about objects comparisons. Python \"is\" is used to test object identity, then compare empty tuple \"()\" is not required to use \"==\" operator. In fact, anything in python can be compared with \"is\".\n>>> obj = ()\n>>> obj is ()\nTrue\n>>> isinstance(obj, tuple)\nTrue\n>>> obj ...
[ -1 ]
[ "python" ]
stackoverflow_0008185776_python.txt
Q: What does the Python error "name 'self' is not defined" mean? I can't figure out what's wrong with this very simple snippet: class A(object): def printme(self): print "A" self.printme() a = A() Error output: Traceback (most recent call last): File "prog.py", line 1, in <modul...
What does the Python error "name 'self' is not defined" mean?
I can't figure out what's wrong with this very simple snippet: class A(object): def printme(self): print "A" self.printme() a = A() Error output: Traceback (most recent call last): File "prog.py", line 1, in <module> class A(object): File "prog.py", line 5, in A self.p...
[ "The following should explain the problem. Maybe you will want to try this?\nclass A(object):\n def printme(self):\n print \"A\"\na = A()\na.printme()\n\nThe name self is only defined inside methods that explicitly declare a parameter called self. It is not defined at the class scope.\nThe class scope is...
[ 14, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008186311_python.txt
Q: How to create a Python class decorator that is able to wrap instance, class and static methods? I'd like to create a Python class decorator (*) that would be able to seamlessly wrap all method types the class might have: instance, class and static. This is the code I have for now, with the parts that break it comm...
How to create a Python class decorator that is able to wrap instance, class and static methods?
I'd like to create a Python class decorator (*) that would be able to seamlessly wrap all method types the class might have: instance, class and static. This is the code I have for now, with the parts that break it commented: def wrapItUp(method): def wrapped(*args, **kwargs): print "This method call was wr...
[ "Because methods are wrappers for functions, to apply a decorator to a method on a class after the class has been constructed, you have to:\n\nExtract the underlying function from the method using its im_func attribute.\nDecorate the function.\nRe-apply the wrapper.\nOverwrite the attribute with the wrapped, decora...
[ 4, 4 ]
[]
[]
[ "decorator", "instrumentation", "python", "reflection" ]
stackoverflow_0008185375_decorator_instrumentation_python_reflection.txt
Q: How to pass path names to Python script by "dropping" files/folders over script icon I am working in Mac OS X and have been writing simple file/folder copy scripts in Python. Is there a way to drag and drop a folder on top of a Python script icon and pass the file or folder's path as an argument in the script? Cur...
How to pass path names to Python script by "dropping" files/folders over script icon
I am working in Mac OS X and have been writing simple file/folder copy scripts in Python. Is there a way to drag and drop a folder on top of a Python script icon and pass the file or folder's path as an argument in the script? Currently, I have an AppleScript droplet (which supports drag and drop) that passes the paths...
[ "Just use the \"Build Applet\" utility:\n/Developer/Applications/Utilities/MacPython\\ 2.5/Build\\ Applet.app\n\nand the dropped file paths will be available thru sys.argv.\nNote that you may have to use Python2.5 (or a patched version) -- \nSee this note: https://bitbucket.org/ronaldoussoren/py2app/issue/16/argv-e...
[ 3, 1 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0008185244_macos_python.txt
Q: How do you parse nested XML tags with python? Please excuse me if I'm using the wrong terminology, but here's what I'm trying to accomplish. I'm trying to pull attribute and text information from nested tags in such as alias, payment, amount, and etc... However my example code block is only able to pull info from...
How do you parse nested XML tags with python?
Please excuse me if I'm using the wrong terminology, but here's what I'm trying to accomplish. I'm trying to pull attribute and text information from nested tags in such as alias, payment, amount, and etc... However my example code block is only able to pull info from and not anything from the subelements in . How do...
[ "subelement.getchildren()\n\nor \nfor subelement in rootElement:\n ...\n for subsub in subelement:\n print subsub.tag\n\n" ]
[ 4 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0008186343_elementtree_python_xml.txt