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: Dynamic module loading in python Possible Duplicate: Dynamic module import in Python I have a list of modules, like so: modules = ['ModuleA', 'ModuleB', 'ModuleC'] Each .py for the module resides in a subdirectory that I've added to the include paths. What I'm looking for is a way to load the modules and build ...
Dynamic module loading in python
Possible Duplicate: Dynamic module import in Python I have a list of modules, like so: modules = ['ModuleA', 'ModuleB', 'ModuleC'] Each .py for the module resides in a subdirectory that I've added to the include paths. What I'm looking for is a way to load the modules and build a list of references to said loaded m...
[ "This should answer your question:\nreferences = map(__import__, modules)\n\nor if you prefer dictionary with modules' names as keys:\nreferences = dict(zip(modules, map(__import__, modules)))\n\nDoes it answer your question?\n", "import importlib\n\nimports = {}\n\nfor i in modules:\n imports[i] = importlib.im...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008652136_python.txt
Q: appengine console for in-development application? Is there a possibility of having a remote_api_shell.py like feature for the application under development. The remote_api_shell.py asks us to point to deployed application and gives the repl console. I found a following limitation while using remote_api_shell, if I...
appengine console for in-development application?
Is there a possibility of having a remote_api_shell.py like feature for the application under development. The remote_api_shell.py asks us to point to deployed application and gives the repl console. I found a following limitation while using remote_api_shell, if I os.chdir to my development directory, I was not able t...
[ "Doh! I found the answer as soon I as posted this question. \nStep 1: Run your app under-development in one shell session\npython dev_appserver.py app\n\nthe application by default runs under port 8080\nStep 2: Open another shell session and use the remote_api_shell.py to connect to the running instance.\nPYTHONPAT...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008652375_google_app_engine_python.txt
Q: Python: What is the difference between a global variable, vs. a variable with the prefix "self.", vs. a local variable? I've been exposed to C/C++/Java like syntax over the years, and the way that Python variables are defined just sort of confuses me. Can anyone describe what the differences are among the three me...
Python: What is the difference between a global variable, vs. a variable with the prefix "self.", vs. a local variable?
I've been exposed to C/C++/Java like syntax over the years, and the way that Python variables are defined just sort of confuses me. Can anyone describe what the differences are among the three mentioned in the q?
[ "A global variable is just that -- a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition. An instance variable (e.g.: when using the self. prefix) is data that is associated with a specific insta...
[ 7, 3, 3 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0008641200_python_variables.txt
Q: A way to avoid repetitive codes tkinter I am trying to display images using tkinter. I notice that there are repetitive codes here. I am trying to get rid of these codes to display images. My goal is to display a number of images not in a discrete way but to display them dynamically in quantities. please help than...
A way to avoid repetitive codes tkinter
I am trying to display images using tkinter. I notice that there are repetitive codes here. I am trying to get rid of these codes to display images. My goal is to display a number of images not in a discrete way but to display them dynamically in quantities. please help thank you. def __init__(self): Frame.__init__...
[ "It's not clear exactly what your pattern is, but if it's what I suspect, the below should work:\nfor index in range(<your range>):\n if index % 4 == 0:\n self._playerCardImage = PhotoImage(file=str(blackjack._player._cards[index].fileName))\n self._playerCardLabel = Label(self, image = self._playe...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0008652432_python_tkinter.txt
Q: Python3 subprocess communicate example I'm new to subprocessing. I just need a really simple win32 example of communicate() between a parent.py and child.py. A string sent from parent.py to child.py, altered by child.py and sent back to parent.py for print() from parent.py. I'm posting this because examples I hav...
Python3 subprocess communicate example
I'm new to subprocessing. I just need a really simple win32 example of communicate() between a parent.py and child.py. A string sent from parent.py to child.py, altered by child.py and sent back to parent.py for print() from parent.py. I'm posting this because examples I have found end up either not being win32 or no...
[ "Here is a simple example as per your requirements. This example is Python 3.x (slight modifications are required for 2.x).\nparent.py\nimport subprocess\nimport sys\n\ns = \"test\"\np = subprocess.Popen([sys.executable, \"child.py\"],\n stdin=subprocess.PIPE,\n stdout=subpro...
[ 21 ]
[]
[]
[ "communicate", "pipe", "python", "subprocess" ]
stackoverflow_0008652767_communicate_pipe_python_subprocess.txt
Q: xlrd python library import xlrd wb = xlrd.open_workbook("file.xls") wb.sheet_names() sh = wb.sheet_by_index(0) for item in sh.col(0): value = unicode(item.value) if value.startswith("cheap"): print value when i trying this code, interpritator return me: AttributeError: 'module' object has no at...
xlrd python library
import xlrd wb = xlrd.open_workbook("file.xls") wb.sheet_names() sh = wb.sheet_by_index(0) for item in sh.col(0): value = unicode(item.value) if value.startswith("cheap"): print value when i trying this code, interpritator return me: AttributeError: 'module' object has no attribute 'open_workbook' w...
[ "The most likely explanation is that you've accidentally created your own xlrd.py file that is being found before the real one. \nThe solution is to find the imposter and delete it. Try import xlrd; print xlrd.__file__ to find the culprit :-)\nP.S. You will need to delete both the .py file and its .pyc cached ve...
[ 7 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0008652821_python_xlrd.txt
Q: Why does numpy.apply_along_axis seem to be slower than Python loop? I'm confused about when numpy's numpy.apply_along_axis() function will outperform a simple Python loop. For example, consider the case of a matrix with many rows, and you wish to compute the sum of each row: x = np.ones([100000, 3]) sums1 = np.arr...
Why does numpy.apply_along_axis seem to be slower than Python loop?
I'm confused about when numpy's numpy.apply_along_axis() function will outperform a simple Python loop. For example, consider the case of a matrix with many rows, and you wish to compute the sum of each row: x = np.ones([100000, 3]) sums1 = np.array([np.sum(x[i,:]) for i in range(x.shape[0])]) sums2 = np.apply_along_ax...
[ "np.sum take an axis parameter, so you could compute the sum simply using \nsums3 = np.sum(x, axis=1)\n\nThis is much faster than the 2 methods you posed.\n$ python -m timeit -n 1 -r 1 -s \"import numpy as np;x=np.ones([100000,3])\" \"np.apply_along_axis(np.sum, 1, x)\"\n1 loops, best of 1: 3.21 sec per loop\n\n$ p...
[ 10 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008652785_numpy_python.txt
Q: Does a Zope Component Architecture component need to state the interfaces it implements? Note: I am new to ZCA, so the code may be incorrect; however, I am somewhat familiar with the way ZCA works. Given for example: class I1(Interface): def c1(): pass class U1(object): implements(I1) #is this nec...
Does a Zope Component Architecture component need to state the interfaces it implements?
Note: I am new to ZCA, so the code may be incorrect; however, I am somewhat familiar with the way ZCA works. Given for example: class I1(Interface): def c1(): pass class U1(object): implements(I1) #is this necessary? def c1(): #do some things here Is the implements(I1) line needed, or can ...
[ "The component does not need to state it. The interface for a component is mostly important when it is registered in the component registry, as the component lookup is done on the interfaces.\nYou can tell the component registry which interface a component implements in several ways. One way, the most common one, i...
[ 4 ]
[]
[]
[ "python", "zope", "zope.component", "zope.interface" ]
stackoverflow_0008652813_python_zope_zope.component_zope.interface.txt
Q: HTTP proxy servlet is so slow Let me describe my working env first. I am a university students. My lab has four machines, A, B, C and D connected by 1Gb/s Ethernet. I have a clustering system which uses B and C as computing slaves. This clustering computing system has a Python HTTP server running on machine A. I w...
HTTP proxy servlet is so slow
Let me describe my working env first. I am a university students. My lab has four machines, A, B, C and D connected by 1Gb/s Ethernet. I have a clustering system which uses B and C as computing slaves. This clustering computing system has a Python HTTP server running on machine A. I want to expose this Python HTTP serv...
[ "That seems pretty slow, and my first thought is, what is that servlet doing? Do you have the source? \nNext thought is that Jetty apparently provides a ProxyServlet of their own. Perhaps they did a better job. Maybe you should try that instead.\n", "You say that machine A has a \"Python HTTP server\". Is it a ha...
[ 0, 0 ]
[]
[]
[ "http", "jetty", "proxy", "python", "servlets" ]
stackoverflow_0008652140_http_jetty_proxy_python_servlets.txt
Q: How to filter lines without Sobel filter in OpenCV I'm trying to detect lines just with linear filters. My first try was rotate a kernel like this but wouldn't work: kernel = zeros((13,13)) kernel60 = zeros((13,13)) kernel[4] = [0,0,0,0,-1,-1,-1,-1,-1,0,0,0,0] #kernel[5] = [0,0,0,0,0] kernel[6] = [0,0,0,0,2,2,2,2...
How to filter lines without Sobel filter in OpenCV
I'm trying to detect lines just with linear filters. My first try was rotate a kernel like this but wouldn't work: kernel = zeros((13,13)) kernel60 = zeros((13,13)) kernel[4] = [0,0,0,0,-1,-1,-1,-1,-1,0,0,0,0] #kernel[5] = [0,0,0,0,0] kernel[6] = [0,0,0,0,2,2,2,2,2,0,0,0,0] #kernel[7] = [0,0,0,0,0] kernel[8] = [0,0,0,...
[ "You can use Canny algorithm for edge detection (which uses Sobel anyway) and Hough transform for line detection. Performing blur before Canny can help eliminate outlier lines. This is the classic approach. You can use OpenCV that implements both parts. \nSee the following:\nhttp://en.wikipedia.org/wiki/Hough_trans...
[ 0 ]
[]
[]
[ "computer_vision", "opencv", "python" ]
stackoverflow_0007517208_computer_vision_opencv_python.txt
Q: django HttpResponseRedirect will add '/' to the end of url I am using django HttpResponseRedirect(url) to redirect the user to a new url, but I found this function will add a '/' to the end of url, which breaks my current design. eg) some of urls is something like: /life/?ret=12344 If a '/' is appended, the url wi...
django HttpResponseRedirect will add '/' to the end of url
I am using django HttpResponseRedirect(url) to redirect the user to a new url, but I found this function will add a '/' to the end of url, which breaks my current design. eg) some of urls is something like: /life/?ret=12344 If a '/' is appended, the url will be /life/?ret=12344/ which makes my prior code confused. How ...
[ "Be aware that Django has APPEND_SLASH option, So APPEND_SLASH = False should be helpful. But in case /life/?ret=12344/ as mentioned @DrTyrsa django should be smart enough\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008653535_django_python.txt
Q: Fast Car implementation in python I want to print numbers from 1 to 100, but for multiples of 3 I want to print "Fast" ,for multiples of 7 I want to print "Car" and for multiples of both 3 & 7 I want to print "Fast Car" instead of that number. Here I'm trying to implement it using Python. This is my 1st program in...
Fast Car implementation in python
I want to print numbers from 1 to 100, but for multiples of 3 I want to print "Fast" ,for multiples of 7 I want to print "Car" and for multiples of both 3 & 7 I want to print "Fast Car" instead of that number. Here I'm trying to implement it using Python. This is my 1st program in Python. Here I'm getting syntax error....
[ "The error log should give you some tips on the line where you get the error.\nYet, you forgot to use : at the end of your for statement and your if statements:\nfor num in range(1,100):\n if num%3==0 and num%7==0:\n print \"Fast Car\"\n elif num%3==0:\n print\"Fast\"\n elif num%7==0:\n print \...
[ 5, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008653969_python.txt
Q: Use a db hash table stored in memcache combined with a cron job to write to google app engine Datastore I have a large pipeline in google app engine that stores intermediate work on the Datastore. This quickly fills my daily quota writes. Instead I am thinking of having a hash table db object stored in memcache th...
Use a db hash table stored in memcache combined with a cron job to write to google app engine Datastore
I have a large pipeline in google app engine that stores intermediate work on the Datastore. This quickly fills my daily quota writes. Instead I am thinking of having a hash table db object stored in memcache that the pipeline uses to store all intermediate results and have cron jobs that loop through all entries of th...
[ "Reading your case, I am under the opinion that Objectify for GAE/J might be suitable for your need. It has a Global Cache option that back up your datastore entities in the memcache to reduce the number of reads to the datastore.\nKeep in mind that the cache only works for put/get/delete operations, so a query wou...
[ 0 ]
[]
[]
[ "google_app_engine", "java", "memcached", "python" ]
stackoverflow_0008650129_google_app_engine_java_memcached_python.txt
Q: wxPython GUI on a web page? Is it possible to embed a wxPython based GUI in an HTML page? If not, is there any other option other than Java applets to make GUIs that can be embedded onto an HTML page? A: take a look at gtk3 html backend http://blogs.gnome.org/alexl/2011/03/15/gtk-html-backend-update/ A: You ca...
wxPython GUI on a web page?
Is it possible to embed a wxPython based GUI in an HTML page? If not, is there any other option other than Java applets to make GUIs that can be embedded onto an HTML page?
[ "take a look at gtk3 html backend http://blogs.gnome.org/alexl/2011/03/15/gtk-html-backend-update/\n", "You can use Javascript to create your own GUI to show. Maybe Google's NaCl is far enough advanced but it won't give you the cross browser compatibility you'll probably like.\nIf you look at broadway (which is l...
[ 0, 0 ]
[]
[]
[ "html", "python", "wxpython" ]
stackoverflow_0008654165_html_python_wxpython.txt
Q: Google Local Search API + Python I am trying to crate a program (in python) that will output query Google’s Local Search and print results to the console. I want to be able to search for “café in London” and get the company names addresses and phone number printed on screen. I found an easy-to-use Python wrapper ...
Google Local Search API + Python
I am trying to crate a program (in python) that will output query Google’s Local Search and print results to the console. I want to be able to search for “café in London” and get the company names addresses and phone number printed on screen. I found an easy-to-use Python wrapper for the Google Maps and Local Search A...
[ "Google allows only 32 on 4 pages. The URLs you get are for pagination. Check this link \nhttp://code.google.com/apis/maps/documentation/localsearch/devguide.html\nand search \n\"There is no way to get more than\" on that page using ctrl-F\n", "Are you sure your use of the Google API complies with the TOS? Im no ...
[ 1, 0 ]
[]
[]
[ "ajax", "google_local_search", "json", "python", "urllib2" ]
stackoverflow_0008650162_ajax_google_local_search_json_python_urllib2.txt
Q: Caught TypeError while rendering: Decimal('51.8') is not JSON serializable I am using Python 2.6.5 and Django 1.3 .while running the below code i am getting the above error if chart_list is not None: if isinstance(chart_list, (Chart, PivotChart)): chart_list = [chart_list] chart_list = [c.hcoptio...
Caught TypeError while rendering: Decimal('51.8') is not JSON serializable
I am using Python 2.6.5 and Django 1.3 .while running the below code i am getting the above error if chart_list is not None: if isinstance(chart_list, (Chart, PivotChart)): chart_list = [chart_list] chart_list = [c.hcoptions for c in chart_list] render_to_list = [s.strip() for s in render_to.split...
[ "Use of custom JSONEncoder should help\nclass DecimalEncoder(json.JSONEncoder):\n def default(self, o):\n if isinstance(o, decimal.Decimal):\n return float(o)\n super(DecimalEncoder, self).default(o)\n\n# and then:\njson.dumps(chart_list,..., cls=DecimalEncoder)\n\n\nUpdated\nUpdated acc...
[ 8 ]
[ "An easy and quick solution is, Convert this decimal object to string before passing to dumps method\ndecimal_value = Decimal('51.8')\nsimplejson.dumps(str(decimal_value))\n\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0008652497_django_python.txt
Q: How can one shorten mongo ids for better use in URLs? I've built a number of python driven sites that utilize mongodb as a database backend and am very happy with it's ObjectId system, however, I'd love to be able encode the ids in a shorter fashion without building a mapping collection or utilizing a url-shortene...
How can one shorten mongo ids for better use in URLs?
I've built a number of python driven sites that utilize mongodb as a database backend and am very happy with it's ObjectId system, however, I'd love to be able encode the ids in a shorter fashion without building a mapping collection or utilizing a url-shortener service. Suggestions? Success stories?
[ "You could compress them as Base62 numbers. This doesn't save a lot of space, but it does save you a few bytes per ID. My example's Ruby, but similar usage in Python wouldn't be hard.\nree-1.8.7-2010.02 > User.first._id.to_s\n => \"4c76f3dd98db74697500003b\"\n\nree-1.8.7-2010.02 > User.first._id.to_s.to_i(16).base6...
[ 12, 7, 1, 1, 0 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0004261129_mongodb_python.txt
Q: Pythonic way to fetch all elements in a dictionary, falling between two keys? I have a dictionary object, and I want to extract a subset of the dictionary (i.e. return another dictionary), which contains all elements of the parent dictionary where the key matches a certain criteria. For example: parent_dict = {1:...
Pythonic way to fetch all elements in a dictionary, falling between two keys?
I have a dictionary object, and I want to extract a subset of the dictionary (i.e. return another dictionary), which contains all elements of the parent dictionary where the key matches a certain criteria. For example: parent_dict = {1: 'Homer', 2: 'Bart', 3: 'Lisa', 4: 'Ma...
[ "Solution\nStarting from python 2.7, you can use dictionary comprehension. There are like list comprehensions, but applied to a dictionary:\n>>> parent_dict = {1: 'Homer',\n... 2: 'Bart',\n... 3: 'Lisa',\n... 4: 'Marge',\n... 5: 'Maggie'\n... ...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008654637_python.txt
Q: Whats wrong with this python code? I get an error after I input while print('Type ROLL to roll for your stats.'): roll = input() # I get my error right after I input if roll == "roll" or roll == "ROLL": strength = random.randint(1, 100) defense = random.randint(1, 100) attack = rand...
Whats wrong with this python code? I get an error after I input
while print('Type ROLL to roll for your stats.'): roll = input() # I get my error right after I input if roll == "roll" or roll == "ROLL": strength = random.randint(1, 100) defense = random.randint(1, 100) attack = random.randint(1, 100) print('Your attack level is ' + attack + '.') ...
[ "A few things here and there:\n\nYour while loop won't work, since the return value of print is None. It won't execute, which I don't think is what was intended. You can change that to an indefinite loop by while True or while 1. Your code will, in theory, break out of the loop when someone enters 'no', but we'l...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "string", "variables" ]
stackoverflow_0008651865_python_string_variables.txt
Q: What should I do if socket.setdefaulttimeout() is not working? I'm writing a script(multi-threaded) to retrieve contents from a website, and the site's not very stable so every now and then there's hanging http request which cannot even be time-outed by socket.setdefaulttimeout(). Since I have no control over that...
What should I do if socket.setdefaulttimeout() is not working?
I'm writing a script(multi-threaded) to retrieve contents from a website, and the site's not very stable so every now and then there's hanging http request which cannot even be time-outed by socket.setdefaulttimeout(). Since I have no control over that website, the only thing I can do is to improve my codes but I'm run...
[ "While socket.setsocketimeout will set the default timeout for new sockets, if you're not using the sockets directly, the setting can be easily overwritten. In particular, if the library calls socket.setblocking on its socket, it'll reset the timeout.\nurllib2.open has a timeout argument, hovewer, there is no timeo...
[ 24, 2, 0 ]
[ "I suggest a simple workaround - move the request to a different process and if it fails to terminate kill it from the calling process, this way:\n checker = Process(target=yourFunction, args=(some_queue))\n timeout = 150\n checker.start()\n counter = 0\n while checker.is_alive() == True:\n ...
[ -1 ]
[ "http", "mechanize", "python", "urllib", "urllib2" ]
stackoverflow_0008464391_http_mechanize_python_urllib_urllib2.txt
Q: Python programming, writing your own functions or difficulty in finding built-in functions In C#, there exists Structured Query Expression and with it, it's fun to play with collections and arrays. I am not sure if such a module exist in python. However SQE implements lambda, lambda expression also exist in python...
Python programming, writing your own functions or difficulty in finding built-in functions
In C#, there exists Structured Query Expression and with it, it's fun to play with collections and arrays. I am not sure if such a module exist in python. However SQE implements lambda, lambda expression also exist in python: Let's imagine I need to get only distinct values from collection: c# ex: List<int> arr = new...
[ "Python has built-in support for sets:\narr = range(10) + [2,4,3]\nfor x in set(arr):\n print (x)\n\nNote that sets are by nature without order; the order you get depends on the implementation of set, and is subject to change. In the rare case that you need to preserve the order, you should adapt your distinct m...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008654869_python.txt
Q: Where to find documentations about Django ORM's return types/possible exceptions raised Is there any documentation about how django handles different ORM problems/errors for methods: MyModel.objects.get(name='myname') myModel.save() myModel.delete() I have read the documentation on https://docs.djangoproject.com...
Where to find documentations about Django ORM's return types/possible exceptions raised
Is there any documentation about how django handles different ORM problems/errors for methods: MyModel.objects.get(name='myname') myModel.save() myModel.delete() I have read the documentation on https://docs.djangoproject.com/en/dev/ref/models/instances/ and find that some problems seem to raise exception, is this th...
[ "Take a look at django.core.exceptions.\nhttps://docs.djangoproject.com/en/1.3/ref/exceptions/#module-django.core.exceptions\n" ]
[ 1 ]
[]
[]
[ "django", "error_handling", "orm", "python" ]
stackoverflow_0008654674_django_error_handling_orm_python.txt
Q: Draw dynamic graph on python I am trying to draw a dynamic graph which I want to control ( moving edges or nodes, update data of edges or nodes, click on edge to show more information...). I have tried several programs and packages like prefuse, networkx and also processing. But with these, we cannot control edges...
Draw dynamic graph on python
I am trying to draw a dynamic graph which I want to control ( moving edges or nodes, update data of edges or nodes, click on edge to show more information...). I have tried several programs and packages like prefuse, networkx and also processing. But with these, we cannot control edges (onClick listener for exemple) we...
[ "Take a look at this example \nhttp://developer.qt.nokia.com/doc/qt-4.8/graphicsview-elasticnodes.html\nYou should be able to make the same using Python Binding for C++/Qt aka PyQt or Pyside. It should run and render much faster.\n" ]
[ 0 ]
[]
[]
[ "graph", "python", "user_interface" ]
stackoverflow_0006019302_graph_python_user_interface.txt
Q: Novice Python/Regex: pull strings between tags using regex Need to pull strings between href attribute tags in Python using the re module. I've tried numerous patterns such as: patFinderLink = re.compile('\>"(CVE.*)"\<\/a>') Example: I need to pull what is between the tags (in this case "CVE-2010-3718") from: <p...
Novice Python/Regex: pull strings between tags using regex
Need to pull strings between href attribute tags in Python using the re module. I've tried numerous patterns such as: patFinderLink = re.compile('\>"(CVE.*)"\<\/a>') Example: I need to pull what is between the tags (in this case "CVE-2010-3718") from: <pre> <a href="https://www.redhat.com/security/data/cve/CVE-2010-37...
[ "Do you need to use regex? I don't think you do, you can't parse SGML with regular expressions because SGML itself is not regular, see this famous stackoverflow answer for the reasoning: https://stackoverflow.com/a/1732454/88123\nAnyhow. You should use the lxml Python module and its xpath implementation. xpath supp...
[ 6, 2, 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0008644741_beautifulsoup_python_regex.txt
Q: Creating a list using mutable sequence methods in Python fails These work: >>> print [1,2,3] + [4,5] [1,2,3,4,5] >>> 'abc'.upper() 'ABC' This doesn't: >>> print [1,2,3].extend([4,5]) None Why? You can use string methods on bare strings, so why can't you use methods on bare sequence types such as lists? Even this...
Creating a list using mutable sequence methods in Python fails
These work: >>> print [1,2,3] + [4,5] [1,2,3,4,5] >>> 'abc'.upper() 'ABC' This doesn't: >>> print [1,2,3].extend([4,5]) None Why? You can use string methods on bare strings, so why can't you use methods on bare sequence types such as lists? Even this doesn't work: >>> print list([1,2,3]).extend([4,5]) None N.B. For ...
[ "extend works, just doesn't return any value as it's modifying the object it works on. That's a python convention to not return any value from methods that modify the object they're called on.\nTry:\n a = [1,2,3]\n a.extend([4,5])\n print a\n\nedit:\nAs for why one reason for this could be that it's sometimes ambig...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008655816_python.txt
Q: How can I integrate in cylindrical coordinates with Scipy? I know how to integrate a function with Scipy. I do it in this way: from scipy import * from scipy import integrate integral = integrate.simps(y,x) In this way I integrate with the Simpsons' rule the function y(x), but what if I want to integr...
How can I integrate in cylindrical coordinates with Scipy?
I know how to integrate a function with Scipy. I do it in this way: from scipy import * from scipy import integrate integral = integrate.simps(y,x) In this way I integrate with the Simpsons' rule the function y(x), but what if I want to integrate this function in cylindrical coordinates? I mean, instead of...
[ "You should try\nintegral = integrate.simps(y*x*2*pi,x)\n\nwhere y should be an array of function values at the positions x. Note that 2*pi*x is the necessary factor to add to your integrand (as you pointed out yourself).\n" ]
[ 1 ]
[]
[]
[ "integration", "python", "scipy" ]
stackoverflow_0008655370_integration_python_scipy.txt
Q: Profiling memory in python 3 Possible Duplicate: Is there any working memory profiler for Python3 I'd like to know how much memory used for my objects. I used guppy for this before, but now I work with python 3, but guppy works under python 2. What can I use for memory profiling in python 3? (I makes standalone ...
Profiling memory in python 3
Possible Duplicate: Is there any working memory profiler for Python3 I'd like to know how much memory used for my objects. I used guppy for this before, but now I work with python 3, but guppy works under python 2. What can I use for memory profiling in python 3? (I makes standalone application not web-based)
[ "objgraph works in Python 3\n" ]
[ 8 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008656124_python_python_3.x.txt
Q: Get containing context of a function In Python, how can I get the containing context of an object (a function, in my case), so I can modify it? For example, if it's a method, its context is the class; if it's a free function, its context is the module. Related question: Can a Python decorator of an instance metho...
Get containing context of a function
In Python, how can I get the containing context of an object (a function, in my case), so I can modify it? For example, if it's a method, its context is the class; if it's a free function, its context is the module. Related question: Can a Python decorator of an instance method access the class?
[ "I think you're going to need to roll your own version, but the standard-library inspect module will get you most of what you need here.\ninspect.ismethod() and inspect.isfunction() will help determine if the function is bound (defined in a class) or not, and thus whether you're looking for a class or a module (you...
[ 1, 0 ]
[]
[]
[ "inspect", "metaprogramming", "python" ]
stackoverflow_0008655133_inspect_metaprogramming_python.txt
Q: Let site administrator manage default values in Django I need to let the site administrator set few defaults, without embedding them to settings.py. For example the admin sets some value, that will be default in some models for 3 months, after that admin changes it to another. How to implement it nicely in Djang...
Let site administrator manage default values in Django
I need to let the site administrator set few defaults, without embedding them to settings.py. For example the admin sets some value, that will be default in some models for 3 months, after that admin changes it to another. How to implement it nicely in Django, those defaults being able to be used in other models ?
[ "I think you are looking for django-livesettings, which is used in satchmo project.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008648849_django_python.txt
Q: Python 3 String Method? Is there anyway to strip or replace or anything like that from one index to another index within a single string? For example, if I have a string like "first - second - third" and I want to remove the middle part (" - second - "), how could I do this? Thanks in advance. A: Your string: ...
Python 3 String Method?
Is there anyway to strip or replace or anything like that from one index to another index within a single string? For example, if I have a string like "first - second - third" and I want to remove the middle part (" - second - "), how could I do this? Thanks in advance.
[ "Your string:\ns = 'first - second - third'\n\nand the possible solutions:\ns.replace(' - second - ', '')\n\nor\n''.join(s.split(' - ')[::2])\n\nor\n''.join(s.split(' - second - '))\n\nor if you know the indices:\ns[:5] + s[-5:]\n\nor just searching for the first and last space:\ns[:s.index(' ')] + s[s.rindex(' ')+...
[ 7, 1, 1 ]
[]
[]
[ "python", "python_3.x", "string", "strip" ]
stackoverflow_0008656469_python_python_3.x_string_strip.txt
Q: ImportError: No module named _tkinter I want to use python in c++ code, but it got an error, it is the simplest "hello word" program. It is Ok to import PIL.Image, but for Tkinter, it will output "ImportError: No module named _tkinter". I had print the sys.path, but no clue. Following snapshot show you the detail ...
ImportError: No module named _tkinter
I want to use python in c++ code, but it got an error, it is the simplest "hello word" program. It is Ok to import PIL.Image, but for Tkinter, it will output "ImportError: No module named _tkinter". I had print the sys.path, but no clue. Following snapshot show you the detail infomation: http://i.minus.com/iWoCUlidmq5M...
[ "It is possible that your exe can't access the DLLs (or PYDs that's the same) in C:\\Python27\\DLLs. You should add this folder to your Windows path. See https://stackoverflow.com/a/428217/117092\n", "i had solved this problem, because i used the debug python_d.dll, it will find the debug version pyd file, so it ...
[ 0, 0 ]
[]
[]
[ "c++", "importerror", "python", "tkinter", "visual_studio" ]
stackoverflow_0008470412_c++_importerror_python_tkinter_visual_studio.txt
Q: Django 1.0 Testing: how do I get a session to persist between test code and view being tested? I am trying to test how a view behaves when there is certain data stored in the session. To do so I have created the session in the test method and invoked an interactive shell at the very beginning of the view: Test Met...
Django 1.0 Testing: how do I get a session to persist between test code and view being tested?
I am trying to test how a view behaves when there is certain data stored in the session. To do so I have created the session in the test method and invoked an interactive shell at the very beginning of the view: Test Method: def test_user_with_unused_tests(self): "User is given a test and sent to test start" # ...
[ "Looks like you need a setUp method, please lookup http://docs.python.org/library/unittest.html for setUp and tearDown method documentation. The setUp will be run for all tests, the code for each individual test will be destroyed at the end of each test run.\nEssentially, you need to put your login logic in the set...
[ 0 ]
[]
[]
[ "django", "python", "testing" ]
stackoverflow_0001515446_django_python_testing.txt
Q: Polymorphism with built-in types in Python I have a collection of variables in Python, some of which are normal Python numbers and some of which are instances of a class I've written called Property, which represents a range of possible values (e.g. between 0 and 4.2). I want to iterate over this collection and d...
Polymorphism with built-in types in Python
I have a collection of variables in Python, some of which are normal Python numbers and some of which are instances of a class I've written called Property, which represents a range of possible values (e.g. between 0 and 4.2). I want to iterate over this collection and do something different depending on whether each ...
[ "Without knowing enough about what you're doing, I'm going to go ahead and agree with your statement\n\nPerhaps I'm just making a mistake by having a collection that mixes class instances with built-in types\n\nIf you only need to compare the sign between built-in numbers and your Property instances, it wouldn't be...
[ 1, 0 ]
[]
[]
[ "polymorphism", "python" ]
stackoverflow_0008656662_polymorphism_python.txt
Q: How to modify rc.local in shell script? I want to add a line(such as '*/data/mod/myservice start some_parameter*'.) to /etc/rc.d/rc.local file in shell script. If there exists a line start with '*/data/mod/myservice start*', then replace it by new one. In my script, it execute the next python method. def excuteCmd...
How to modify rc.local in shell script?
I want to add a line(such as '*/data/mod/myservice start some_parameter*'.) to /etc/rc.d/rc.local file in shell script. If there exists a line start with '*/data/mod/myservice start*', then replace it by new one. In my script, it execute the next python method. def excuteCmd(cmd): import commands output = comma...
[ "This means that you don't have permission to either write to or delete the file. Also, you won't be able to run the sudo command like that without typing in a password, so ideally the script itself would be run using sudo python scriptname.\n", "sudo command > filename executes command using sudo (with root priv...
[ 2, 2 ]
[]
[]
[ "bash", "linux", "python", "rc", "shell" ]
stackoverflow_0008656881_bash_linux_python_rc_shell.txt
Q: Determine if variable is defined in Python How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in P...
Determine if variable is defined in Python
How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby. if co...
[ "try:\n thevariable\nexcept NameError:\n print(\"well, it WASN'T defined after all!\")\nelse:\n print(\"sure, it was defined.\")\n\n", "'a' in vars() or 'a' in globals()\nif you want to be pedantic, you can check the builtins too\n'a' in vars(__builtins__)\n", "I think it's better to avoid the situatio...
[ 753, 441, 157, 24, 6, 5 ]
[]
[]
[ "defined", "python", "variables" ]
stackoverflow_0001592565_defined_python_variables.txt
Q: How to get Intellij-idea close Flask dev server properly? I use IDEA 10.5 for my Flask experimentation. Flask has en embedded test server (like Django does) When I launch my test class, the dev server launches as well on port 5000. All good. * Running on http://127.0.0.1:5000/ When I click on the "Stop process...
How to get Intellij-idea close Flask dev server properly?
I use IDEA 10.5 for my Flask experimentation. Flask has en embedded test server (like Django does) When I launch my test class, the dev server launches as well on port 5000. All good. * Running on http://127.0.0.1:5000/ When I click on the "Stop process" button (red square), I get the message saying the process is ...
[ "I guess what happens is that you start your flask app which then is forking the development server as a new process. If you stop the app the forked process is still running.\nThis looks like a problem, that cannot easily be solved within the means of your IDE. You could add something to your main to kill the alrea...
[ 0, 0 ]
[]
[]
[ "flask", "intellij_idea", "macos", "pycharm", "python" ]
stackoverflow_0006565871_flask_intellij_idea_macos_pycharm_python.txt
Q: Xcode's output different to IDLE's when using UTF-8 (Python 3) I am using Xcode 4.2 and IDLE under Mac OS 10.7 to compile Python 3 code, which is as follows: #coding=utf-8 print("ľťď") In spite of using the same interpreter, which is python 3.2.2, while IDLE returns the expected string ľťď (in fact, it works even...
Xcode's output different to IDLE's when using UTF-8 (Python 3)
I am using Xcode 4.2 and IDLE under Mac OS 10.7 to compile Python 3 code, which is as follows: #coding=utf-8 print("ľťď") In spite of using the same interpreter, which is python 3.2.2, while IDLE returns the expected string ľťď (in fact, it works even without the first line—if I understand correctly, this version of P...
[ "I have found the solution thanks to this article.\nIn case you experience the same issue, all you have to do is create a standard XML property list ~/.MacOSX/environment.plist (case sensitive, extension sensitive) with the key of PYTHONIOENCODING and string value utf-8. Do not forget to log out and log in before t...
[ 0, 0 ]
[]
[]
[ "python", "utf_8", "xcode" ]
stackoverflow_0008636795_python_utf_8_xcode.txt
Q: Building Python 2.5 with full Sqlite3 as a user on linux This is a bit of a complex problem, at least for me. Here it goes: I'm working as a user on linux server and it's safe to assume that installing any package not already installed is simply impossible. Also I need to set up working Python 2.5 (not installed) ...
Building Python 2.5 with full Sqlite3 as a user on linux
This is a bit of a complex problem, at least for me. Here it goes: I'm working as a user on linux server and it's safe to assume that installing any package not already installed is simply impossible. Also I need to set up working Python 2.5 (not installed) with working SQLite3 library (Sqlite in any form not installed...
[ "First download, build and install sqlite3 with a --prefix. Then build python with same prefix , it will find sqlite installation and will build _sqlite3 module.\n$ mkdir -p ~/applications/src\n$ cd ~/applications/src\n$ wget http://www.sqlite.org/sqlite-autoconf-3070900.tar.gz\n$ tar xvvf sqlite-autoconf-3070900.t...
[ 6 ]
[]
[]
[ "gcc", "pysqlite", "python", "shared_libraries", "sqlite" ]
stackoverflow_0008656158_gcc_pysqlite_python_shared_libraries_sqlite.txt
Q: What is the Python/PyDev equivalent to org.eclipse.jdt.core.IJavaElement? I am interested in modifying an existing plugin -- rabbit-eclipse -- that tracks time spent editing different java elements (classes, methods, etc.). The plugin currently tracks Java elements via the org.eclipse.jdt.core.IJavaElement interfa...
What is the Python/PyDev equivalent to org.eclipse.jdt.core.IJavaElement?
I am interested in modifying an existing plugin -- rabbit-eclipse -- that tracks time spent editing different java elements (classes, methods, etc.). The plugin currently tracks Java elements via the org.eclipse.jdt.core.IJavaElement interface. I would like to add the ability to track the different Python elements. I h...
[ "PyDev doesn't provide an actual replacement for IJavaElement... (i.e.: it does not provide selection based on that).\nStill, there may be different approaches which may work... one choice would be hearing regular text selections and doing what's done in org.python.pydev.editor.actions.PyMethodNavigation, which is ...
[ 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0008645370_eclipse_pydev_python.txt
Q: Update a Git Repository through a Git Hook in Python I'm using python to write a post-receive hook that will hopefully serve for automatic deployment of all of the updated files in my project. Essentially, every time the "deploy" branch is pushed, it will upload the changed files over FTP to my server. Here's wha...
Update a Git Repository through a Git Hook in Python
I'm using python to write a post-receive hook that will hopefully serve for automatic deployment of all of the updated files in my project. Essentially, every time the "deploy" branch is pushed, it will upload the changed files over FTP to my server. Here's what I have so far: def deploy(old, new): fileList = ...
[ "The git diff ... is failing because it's not aware you're inside a bare repo.\nTry git --bare diff ... instead or setting $GIT_DIR.\n" ]
[ 0 ]
[]
[]
[ "git", "git_bare", "githooks", "python" ]
stackoverflow_0008650031_git_git_bare_githooks_python.txt
Q: Interpolating periodic data in Python I have a module that collects stats in an inconsistent time interval. Unfortunately, to use it nicely in a graph, I need the x values interpolated to a consistent interval. Given the following x, y pairs, what's the most Pythonic way to do this? (1, 23), (2, 42), (3.5, 89), (...
Interpolating periodic data in Python
I have a module that collects stats in an inconsistent time interval. Unfortunately, to use it nicely in a graph, I need the x values interpolated to a consistent interval. Given the following x, y pairs, what's the most Pythonic way to do this? (1, 23), (2, 42), (3.5, 89), (5, 73), (7, 54), (8, 41), (8.5, 37), (9, 23...
[ "Use numpy.interp:\nimport numpy as np\n\na = np.array([(1, 23), (2, 42), (3.5, 89), (5, 73), (7, 54), (8, 41), (8.5, 37), (9, 23)])\n\nx = np.arange(1, 10) # target x values\n\nb = zip(x, np.interp(x, a[:,0], a[:,1]))\n\n# b == [(1, 23.0),\n# (2, 42.0),\n# (3, 73.333333333333329),\n# (4, 83.66666...
[ 7 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0008657612_python_statistics.txt
Q: Pros and cons of using web2py as GUI interface instead of Tkinter, What do you think, I am not going to build app for sell, but just to build app for the company i work for, app to automate MS office tasks and developing standalone database app to keep track of company equipments Thanks A: Not a bad idea. You ca...
Pros and cons of using web2py as GUI interface instead of Tkinter,
What do you think, I am not going to build app for sell, but just to build app for the company i work for, app to automate MS office tasks and developing standalone database app to keep track of company equipments Thanks
[ "Not a bad idea. You can package your web2py app as a standalone binary for Windows and Mac, including its own Python interpreter, web server (Rocket), and database (SQLite). Just click to run (no command line needed).\n", "In my opinion, browser based UIs make your job as the maintainer easier because deployment...
[ 4, 3, 2 ]
[]
[]
[ "python", "tkinter", "user_interface", "web2py" ]
stackoverflow_0008655192_python_tkinter_user_interface_web2py.txt
Q: How to save output of a generated text I am using the following code to generate a text: for i in xrange(300): sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) and I would like to know how to store the same text (in the variable text1) so that I can use it later in this code: for i in xrange(3...
How to save output of a generated text
I am using the following code to generate a text: for i in xrange(300): sys.stdout.write(alphabet[bisect.bisect(f_list, random.random()) and I would like to know how to store the same text (in the variable text1) so that I can use it later in this code: for i in xrange(300): text1=sys.stdout.write(alphabet[bis...
[ "Something like this?\ntext1 = [alphabet[bisect.bisect(f_list, random.random())] for i in xrange(300)]\n\n", "In this line:\ntext1=sys.stdout.write(alphabet[bisect.bisect(f_list, random.random())])\n\nYou are just overwriting (changing) the value of the variable text1. In adittion, as @eumiro said, you are assign...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008657738_python.txt
Q: Is it possible to convert this map/filter code into list comprehension? I have a list of regular expressions I want to run over a single string. I don't care which expressions matched, I just want their results (re.Match objects). Of course it's easy with the for loop, but I wanted something more pythonic. This is...
Is it possible to convert this map/filter code into list comprehension?
I have a list of regular expressions I want to run over a single string. I don't care which expressions matched, I just want their results (re.Match objects). Of course it's easy with the for loop, but I wanted something more pythonic. This is what I've got now: all_matches = map(lambda x: x.match(domain), ...
[ "It is possible to write this as a simple list comprehension. However, the r.match(domain) will have to be evaluated twice:\nmatches = [r.match(domain) for r in (first_re, second_re, third_re) if r.match(domain)]\n\nOr you will have to write a double list comprehension:\nmatches = [a for a in (r.match(domain) for r...
[ 3, 1 ]
[]
[]
[ "filter", "map", "python" ]
stackoverflow_0008657643_filter_map_python.txt
Q: How to make Eclipse inherit $PYTHONPATH on Mac OS X I'm attempting to get Eclipse + PyDev set up so I don't need to alter the PYTHONPATH from within Eclipse, but rather it will inherit the PYTHONPATH from the .profile document from inside my home directory. Is that possible, or do I need to actually add the PYTHON...
How to make Eclipse inherit $PYTHONPATH on Mac OS X
I'm attempting to get Eclipse + PyDev set up so I don't need to alter the PYTHONPATH from within Eclipse, but rather it will inherit the PYTHONPATH from the .profile document from inside my home directory. Is that possible, or do I need to actually add the PYTHONPATH locations using Eclipse's PYTHONPATH editor? I ask b...
[ "You need to configure it inside Eclipse. Now, provided have a shell that has the PYTHONPATH properly setup, you should be able to start Eclipse from it and when adding an interpreter (you may want to remove your currently configured interpreter), it should automatically pick all of the PYTHONPATH you had setup fro...
[ 0 ]
[]
[]
[ "eclipse", "python", "pythonpath" ]
stackoverflow_0008569486_eclipse_python_pythonpath.txt
Q: use of self argument I am a newcomer to Python. I don't understand how/why the self argument is used: class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.name p = Person('Swaroop') p.sayHi() This code is from a Byte of Python. This cod...
use of self argument
I am a newcomer to Python. I don't understand how/why the self argument is used: class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.name p = Person('Swaroop') p.sayHi() This code is from a Byte of Python. This code could have just as easil...
[ "It seems you are oversimplifying a not so simple thing.\nIn object-oriented programming, a Class is a Declarative Construct which gives a blueprint as to what an object (a manifestation of this blueprint) would contain (properties) and how it would behave (members). \nEvery manifestation of such a Class is called ...
[ 6, 4, 2, 0, 0 ]
[]
[]
[ "python", "self" ]
stackoverflow_0008658012_python_self.txt
Q: Extracting specific information from text I'd like to get some data from text file. I've decided to do it using Natural Language Toolkit, but I'm open to suggestions if there is a better way to do this. Here is an example: I need a flight from New York NY to San Francisco CA. From this text, I'd like to get cit...
Extracting specific information from text
I'd like to get some data from text file. I've decided to do it using Natural Language Toolkit, but I'm open to suggestions if there is a better way to do this. Here is an example: I need a flight from New York NY to San Francisco CA. From this text, I'd like to get city and state for origin and destination. Here i...
[ "Perhaps you're better off reading the file in line by line?\nThen something as simple as:\ncityState = dataAfterTo.split(\",\")\ncity = cityState[0]\nstate = cityState[1].split()[0]\n\nUnless you're dealing with user generated content of course.\n" ]
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0008657670_nltk_python.txt
Q: Install MySQLdb on snow leopard without XCode Is it possible to install the MySQLdb python module on Snow Leopard without XCode? I am not a member of the $99/year developer programs, so I do not have XCode. A: XCode 4.2 is a free download from the App Store (which you have if you've upgraded to latest Snow Leopa...
Install MySQLdb on snow leopard without XCode
Is it possible to install the MySQLdb python module on Snow Leopard without XCode? I am not a member of the $99/year developer programs, so I do not have XCode.
[ "XCode 4.2 is a free download from the App Store (which you have if you've upgraded to latest Snow Leopard versions)\nhttp://itunes.apple.com/us/app/xcode/id448457090?mt=12\nI think on SL they may charge you something like $4 for it, but there is really no way around this as you need the whole compiler+libs stack t...
[ 1 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0008647964_macos_mysql_python.txt
Q: Script-driven automation of Google refine with ruby python perl java or otherwise BACKGROUND: Co-worker Adam has been using Google refine to process database downloads with much success over the last year or so, but Adam got a new job offer and consequently all of his work and expertise he has done in Google refin...
Script-driven automation of Google refine with ruby python perl java or otherwise
BACKGROUND: Co-worker Adam has been using Google refine to process database downloads with much success over the last year or so, but Adam got a new job offer and consequently all of his work and expertise he has done in Google refine is going away. Ben would like to have Adam package all of his work that she has done ...
[ "There's a Python client library for driving the Refine server which may be useful for what you're trying to do.\nhttp://pypi.python.org/pypi/refine-client\nhttps://github.com/maxogden/refine-python\n" ]
[ 4 ]
[]
[]
[ "google_refine", "java", "python", "ruby" ]
stackoverflow_0008598510_google_refine_java_python_ruby.txt
Q: setup.py that pulls in non-Python github repos and puts them in the correct directory? Is it possible to create a setup.py file that: Pulls in a github repository places the files from that repository into a specified folder I'm setting up a django package/app that uses third-party JavaScript frameworks availab...
setup.py that pulls in non-Python github repos and puts them in the correct directory?
Is it possible to create a setup.py file that: Pulls in a github repository places the files from that repository into a specified folder I'm setting up a django package/app that uses third-party JavaScript frameworks available on github. I'd like to be able to have setup.py pull the latest version from github and t...
[ "If you are using setuptool (setup.py) you can use the dependency requirement:\nhttps://stackoverflow.com/a/3481388/496445\nOtherwise as comments have suggested, set up your django project as an actual git repo and then add the github repo as a submodule\ncd myProject\ngit init\ngit submodule add git://path/to/repo...
[ 2, 2 ]
[]
[]
[ "django", "git", "github", "python", "setup.py" ]
stackoverflow_0008657959_django_git_github_python_setup.py.txt
Q: Differences when opening sockets with Python and Java I am running into a really weird problem when opening and closing multiple sequential connections to the same host using Java. I am trying to run a for cycle to open a tcp socket, send some data, receive a response and close the connection. After the third iter...
Differences when opening sockets with Python and Java
I am running into a really weird problem when opening and closing multiple sequential connections to the same host using Java. I am trying to run a for cycle to open a tcp socket, send some data, receive a response and close the connection. After the third iteration of this cycle, it stops working. Opening and writing ...
[ "You are not showing the value of command used in the Python code. Maybe you are sending different commands?\nThe only other difference I can see is that in Python you use socket.send' while in java you useOutputStream.write`:\nThe different behavior happens when there is not enough buffer space to write all the da...
[ 0 ]
[]
[]
[ "java", "python", "sockets" ]
stackoverflow_0008655187_java_python_sockets.txt
Q: Completely lost: Python configure script runs with errors I downloaded tarball of python 2.7.2 to install on Suse Linux server--it comes with 2.6 and 3.1. Untarred it (I know--wrong lingo, sorry) to a directory. When trying to run ./configure, which should create a valid makefile I can't get past the step one: th...
Completely lost: Python configure script runs with errors
I downloaded tarball of python 2.7.2 to install on Suse Linux server--it comes with 2.6 and 3.1. Untarred it (I know--wrong lingo, sorry) to a directory. When trying to run ./configure, which should create a valid makefile I can't get past the step one: the script reports that it can't find a compiler on the path. But...
[ "Sounds like you simply don't have the compiler installed. Do:\nsudo zypper install gcc\n\nIf a ./configure fails, there's no point in running make.\n", "Suse has a package manager called Yast. It would do your installation with no fuss.\n" ]
[ 0, 0 ]
[]
[]
[ "configure", "linux", "python" ]
stackoverflow_0008640781_configure_linux_python.txt
Q: python syntax error in script, fine in REPL When I put this python code into the REPL for python (the interactive shell), it works as expected: >>> def get_header(): ... return (None,None,None) ... >>> get_header() (None, None, None) Note that the return statement is indented by four spaces, and I have check...
python syntax error in script, fine in REPL
When I put this python code into the REPL for python (the interactive shell), it works as expected: >>> def get_header(): ... return (None,None,None) ... >>> get_header() (None, None, None) Note that the return statement is indented by four spaces, and I have checked to ensure there are no extraneous spaces. when...
[ "The reason this is not working is that you don’t have anything telling bash that this is a Python script, so it tries to execute it as a shell script, then throws an error when the syntax isn’t right.\nWhat you need is to start the file with a shebang line, telling it what it should be run with. So your file becom...
[ 11 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0008658812_python_syntax_error.txt
Q: postgis split polygon using points I would like to extract polygon parts using points to cut it. I have seen ST_Dump and ST_Split but they do not seem to do the trick. Should I create more points in order to create a line segment and use st_split to cut them? I think thats too much but I would do it if necessary ...
postgis split polygon using points
I would like to extract polygon parts using points to cut it. I have seen ST_Dump and ST_Split but they do not seem to do the trick. Should I create more points in order to create a line segment and use st_split to cut them? I think thats too much but I would do it if necessary :) Any suggestions would be nice :) Chee...
[ "So, you want a linestring from each edge a polygon? I think I have an answer if that is true.\nFirst: I would create a view that has all you polygons as linestrings. As you've pointed out, you can use ST_Boundary. (So that the second query is easy to write and read)\nCREATE VEIW my_linestrings as \n SELECT id,....
[ 0 ]
[]
[]
[ "polygon", "postgis", "python" ]
stackoverflow_0008619424_polygon_postgis_python.txt
Q: file download dialog in firefox iam working on selenium+python programming by using firefox, automatically start the download and save file.i have done every thing but unable to download the csv file. my python version is 2.6.6 and my selenium version is latest version. i tried by using the following link al...
file download dialog in firefox
iam working on selenium+python programming by using firefox, automatically start the download and save file.i have done every thing but unable to download the csv file. my python version is 2.6.6 and my selenium version is latest version. i tried by using the following link also(i.e) fp = webdriver.FirefoxProfile...
[ "Here is a complete example that works for me using Firefox 3.6.24 and 8.0.1. \n#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7\nfrom selenium import webdriver\n\nprofile = webdriver.FirefoxProfile()\nprofile.set_preference('browser.download.dir',\"/tmp/webdriver-downloads\")\nprofile.set_prefere...
[ 2 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0008656056_python_selenium.txt
Q: Python Values in Lists I am using Python 3.0 to write a program. In this program I deal a lot with lists which I haven't used very much in Python. I am trying to write several if statements about these lists, and I would like to know how to look at just a specific value in the list. I also would like to be inform...
Python Values in Lists
I am using Python 3.0 to write a program. In this program I deal a lot with lists which I haven't used very much in Python. I am trying to write several if statements about these lists, and I would like to know how to look at just a specific value in the list. I also would like to be informed of how one would find the...
[ "Check out the documentation on sequence types and list methods.\nTo look at a specific element in the list you use its index:\n>>> x = [4, 2, 1, 0, 1, 2]\n>>> x[3]\n0\n\nTo find the index of a specific value, use list.index():\n>>> x.index(1)\n2\n\nSome more information about exactly what you are trying to do woul...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008659049_python.txt
Q: multiprocessing Listeners and Clients between python and pypy Is it possible to have a Listener server process and a Client process where one of them uses a python interpreter and the other a pypy interpreter? Would conn.send() and conn.recv() interoperate well? A: I tried it out to see: import sys from multipro...
multiprocessing Listeners and Clients between python and pypy
Is it possible to have a Listener server process and a Client process where one of them uses a python interpreter and the other a pypy interpreter? Would conn.send() and conn.recv() interoperate well?
[ "I tried it out to see:\nimport sys\nfrom multiprocessing.connection import Listener, Client\n\naddress = ('localhost', 6000)\n\ndef client():\n conn = Client(address, authkey='secret password')\n print conn.recv_bytes()\n conn.close()\n\ndef server():\n listener = Listener(address, authkey='secret pass...
[ 11 ]
[]
[]
[ "multiprocessing", "pypy", "python" ]
stackoverflow_0008659180_multiprocessing_pypy_python.txt
Q: Pyramid under virtualenv: can't import simplejson module When I use the usual Python console, the import works well, but when I run pserve (Pyramid server) I get an error: No module named simplejson A: You probably created your virtualenv without site-packages. Run pip install simplejson from your virtualenv to ...
Pyramid under virtualenv: can't import simplejson module
When I use the usual Python console, the import works well, but when I run pserve (Pyramid server) I get an error: No module named simplejson
[ "You probably created your virtualenv without site-packages. Run pip install simplejson from your virtualenv to install the package.\n" ]
[ 4 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008659397_pyramid_python.txt
Q: Redirection from one server(port) to another Is there a way to redirect from one server port to another? I have two servers running on my system: Apache on port 80 and Python CGI on port 8000 How can I create a redirect from a page running on Apache to one on CGI and vice-versa? <body onload="document.location='12...
Redirection from one server(port) to another
Is there a way to redirect from one server port to another? I have two servers running on my system: Apache on port 80 and Python CGI on port 8000 How can I create a redirect from a page running on Apache to one on CGI and vice-versa? <body onload="document.location='127.0.0.1'"> did not work.
[ "Actually it has nothing to do with different ports, it is just all about redirection. Here are two methods for you.\nRedirction with .htaccess: create a file named .htaccess and write a line like\nRedirect /redirect.html http://127.0.0.1:8000\n\nin it. Then all access to /redirect.html will be redirected to http:/...
[ 1 ]
[]
[]
[ "apache", "cgi", "python" ]
stackoverflow_0008659221_apache_cgi_python.txt
Q: Counting and summing values of records, filtered by a dictionary of foreign keys in Django I am having trouble with a Django query for this simplified model: class Client(models.Model): user_name = models.CharField class Task(models.Model): client = models.ForeignKey( 'Clien...
Counting and summing values of records, filtered by a dictionary of foreign keys in Django
I am having trouble with a Django query for this simplified model: class Client(models.Model): user_name = models.CharField class Task(models.Model): client = models.ForeignKey( 'Client', ) task_type = models.ForeginKey( ...
[ "Count all tasks that have task_type by the name of \"XYZ\", limited to clients in queryset\nTask.objects.filter(client__in=clients, task_type__name='XYZ').count()\n\nSum all the value_num for all the tasks by the name of \"ABC\", limited to clients in the queryset.\nfrom django.db.models import Sum\n\nTask.objects...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008656749_django_django_models_python.txt
Q: Detecting black images on Android or python I have an Android application that has user contributed images. There are a lot of users that submit black or really dark images to the backend application, that I want to filter out. Best solution would be to filter the images already at the phone and notify the user to...
Detecting black images on Android or python
I have an Android application that has user contributed images. There are a lot of users that submit black or really dark images to the backend application, that I want to filter out. Best solution would be to filter the images already at the phone and notify the user to make more light and retake the picture. Another ...
[ "You can try using a histogram of the image as a first approximation.\nAn example using PIL that alerts you if there are more 'dark' pixels (first 128 values in a greyscale representation) than 'light' ones:\nimport Image\n\nimg = Image.open('m.jpg') \ngsimg = im.convert(mode='L')\nhg = gsimg.histogram()\n# count ...
[ 7, 2, 0, 0 ]
[]
[]
[ "android", "image_processing", "python" ]
stackoverflow_0008659663_android_image_processing_python.txt
Q: python mysql custom re-connect class does not hold server connection open I have a custom class written in python to re-establish a mysql connection, if the current connection is dead. The only problem is, the current one always seems to be dead and is always entering into the except block of my try-except. class...
python mysql custom re-connect class does not hold server connection open
I have a custom class written in python to re-establish a mysql connection, if the current connection is dead. The only problem is, the current one always seems to be dead and is always entering into the except block of my try-except. class DB: conn = None def connect( self ): try: s...
[ "\nThe first time you make a call to db.query, self.conn is equal to\nNone. So indeed, you will always get a exception generated during sql connection\nmessage the first time you call db.query. However, subsequent calls\nto db.query will not produce that message. \nIf you add\ndef __init__(self):\n self.connect(...
[ 2 ]
[]
[]
[ "connection", "database", "exception", "mysql", "python" ]
stackoverflow_0008659513_connection_database_exception_mysql_python.txt
Q: Stackless Python - profile single tasklet execution time In my server written in Stackless Python, I occasionally am getting large spikes in CPU usage for 5-10 seconds durations. This happens sporadically so I'm having trouble tracking it down. I've used cProfile to try and determine where these spikes are comi...
Stackless Python - profile single tasklet execution time
In my server written in Stackless Python, I occasionally am getting large spikes in CPU usage for 5-10 seconds durations. This happens sporadically so I'm having trouble tracking it down. I've used cProfile to try and determine where these spikes are coming from but cProfile gives an overall picture of where time is...
[ "I haven't found an explicit function to hook into when a tasklet blocks/resumes, but since Channel.receive() is typically when the block/resume occurs, I hooked into every occurrence of that happening.\n" ]
[ 0 ]
[]
[]
[ "green_threads", "profiling", "python", "stackless" ]
stackoverflow_0008631091_green_threads_profiling_python_stackless.txt
Q: Iterating through a list of Form Objects with a for loop Possible Duplicate: Changing variable names with Python for loops I have created a form that has 24 line edit boxes (objects) in it. I want to update an attribute on each object based upon data entered by the user (I want to enable or disable the line edi...
Iterating through a list of Form Objects with a for loop
Possible Duplicate: Changing variable names with Python for loops I have created a form that has 24 line edit boxes (objects) in it. I want to update an attribute on each object based upon data entered by the user (I want to enable or disable the line edit box). So I am trying to do something like: if self.cmbS...
[ "There's nothin preventing you from putting your lblFxsLine into a dictionary or list.\nself.lblFxsLines = [lblFxsLine for i in range(1,25)]\n\n...\n\nif self.cmbSelectDevice.currentText() == 'Adtran 904' :\n for enableLine in range(1, 5) :\n self.lblFxsLines[enableLine].setEnabled(1)\n for disableLin...
[ 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0008659951_for_loop_python.txt
Q: Markov chain on letter scale and random text I would like to generate a random text using letter frequencies from a book in a .txt file, so that each new character (string.lowercase + ' ') depends on the previous one. How do I use Markov chains to do so? Or is it simpler to use 27 arrays with conditional frequenci...
Markov chain on letter scale and random text
I would like to generate a random text using letter frequencies from a book in a .txt file, so that each new character (string.lowercase + ' ') depends on the previous one. How do I use Markov chains to do so? Or is it simpler to use 27 arrays with conditional frequencies for each letter?
[ "\nI would like to generate a random text using letter frequencies from a\n book in a txt file\n\nConsider using collections.Counter to build-up the frequencies when looping over the text file two letters at a time.\n\nHow do I use markov chains to do so? Or is it simpler to use 27 arrays\n with conditional frequ...
[ 8, 1 ]
[]
[]
[ "markov_chains", "python" ]
stackoverflow_0008660015_markov_chains_python.txt
Q: TaggedCorpusReader and UnigramTagger in nltk (python) I'm trying to use nltk to auto-categorize news articles in a very lo-fi way. I've created a custom corpus of word/tag pairs correlating to my categories (ie. teacher/EDU, computer/TECH, etc.) I've been reading around and this question got me pretty close, but I...
TaggedCorpusReader and UnigramTagger in nltk (python)
I'm trying to use nltk to auto-categorize news articles in a very lo-fi way. I've created a custom corpus of word/tag pairs correlating to my categories (ie. teacher/EDU, computer/TECH, etc.) I've been reading around and this question got me pretty close, but I'm still stuck. Based on my code so far, how do I use my ta...
[ "Taggers are for part-of-speech tagging, not text classification. Take a look at the reuters corpus - it categorizes news articles into multiple categories using a category file. Then look at the nltk.classify module and read up on how to train text classifiers.\n" ]
[ 2 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0008659490_nltk_python.txt
Q: recursively create tuples from lists I have a list of lists such as: [[1,2,3],[4,5,6],[7,8,9]] I'm trying to create tuples of the form (1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(2,4),(2,5),(4,7),(4,8),... In other words, items in the first list should be tuples with items in subsequent lists, items in the second list, t...
recursively create tuples from lists
I have a list of lists such as: [[1,2,3],[4,5,6],[7,8,9]] I'm trying to create tuples of the form (1,4),(1,5),(1,6),(1,7),(1,8),(1,9),(2,4),(2,5),(4,7),(4,8),... In other words, items in the first list should be tuples with items in subsequent lists, items in the second list, tuples with items from its subsequent lists...
[ "You have a list of list (lol), then, pop first item from list of list and make cartesian product with concatenate remaining lists:\nimport itertools\nlol = [[1,2,3],[4,5,6],[7,8,9]]\nresult = list()\nwhile lol:\n l=lol.pop(0)\n o=itertools.chain(*lol)\n result += itertools.product( l,o )\n\nresult\n[(1, 4...
[ 4, 2, 1, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0008658995_python_tuples.txt
Q: Run a python script in perl I have two scripts, a python script and a perl script. How can I make the perl script run the python script and then runs itself? A: Something like this should work: system("python", "/my/script.py") == 0 or die "Python script returned error $?"; If you need to capture the output of ...
Run a python script in perl
I have two scripts, a python script and a perl script. How can I make the perl script run the python script and then runs itself?
[ "Something like this should work:\nsystem(\"python\", \"/my/script.py\") == 0 or die \"Python script returned error $?\";\n\nIf you need to capture the output of the Python script:\nopen(my $py, \"|-\", \"python2 /my/script.py\") or die \"Cannot run Python script: $!\";\nwhile (<$py>) {\n # do something with the i...
[ 9, 2, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0008659226_perl_python.txt
Q: reverse() is not working I am trying to pass the id through reverse. But it's not working. I'm getting this error Reverse for 'reg.views.thanks' with arguments '(20,)' and keyword arguments '{}' not found. Here is my views.py: from django.http import HttpResponse, Http404, HttpResponseRedirect from django.core.url...
reverse() is not working
I am trying to pass the id through reverse. But it's not working. I'm getting this error Reverse for 'reg.views.thanks' with arguments '(20,)' and keyword arguments '{}' not found. Here is my views.py: from django.http import HttpResponse, Http404, HttpResponseRedirect from django.core.urlresolvers import reverse from ...
[ "from this links (django tutorial):\nhttps://docs.djangoproject.com/en/dev/topics/http/urls/#django.core.urlresolvers.reverse \nexample:\ndef myview(request):\n return HttpResponseRedirect(reverse('arch-summary', args=[1945]))\n\nso your code goes to: \nin urls.py: \nurl(r'^thanks/(?P<id>\\d+)$', 'reg.views.t...
[ 5, 3 ]
[]
[]
[ "django", "django_urls", "django_views", "python" ]
stackoverflow_0008648196_django_django_urls_django_views_python.txt
Q: Extract video from .swf using Python I've written code that generated the links to videos such as the one below. Once obtained, I try to download it in this manner: import urllib.request import os url = 'http://www.videodetective.net/flash/players/?customerid=300120&playerid=351&publishedid=319113&playlistid=0&vi...
Extract video from .swf using Python
I've written code that generated the links to videos such as the one below. Once obtained, I try to download it in this manner: import urllib.request import os url = 'http://www.videodetective.net/flash/players/?customerid=300120&playerid=351&publishedid=319113&playlistid=0&videokbrate=750&sub=RTO&pversion=5.2%22%20wi...
[ "With your code, you aren't downloading the encoded video file here, but the flash application (in CWS-format) that is used to play the video. It is executed in the browser and dynamically loads and plays the video. You'd need to apply some reverse-engineering to figure out the actual video source. The following is...
[ 17 ]
[]
[]
[ "python", "screen_scraping", "web_scraping" ]
stackoverflow_0008660526_python_screen_scraping_web_scraping.txt
Q: Trouble installing mysql-python I downloaded MySQL-python-1.2.3.tar.gz, unzipped and untarred it, and ran sudo python setup.py build. I get this error: Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() File "/Users/me/sources/MySQL-python-1.2.3/setup...
Trouble installing mysql-python
I downloaded MySQL-python-1.2.3.tar.gz, unzipped and untarred it, and ran sudo python setup.py build. I get this error: Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() File "/Users/me/sources/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config ...
[ "Looks like what you're trying to install is just a MySQL API for Python. You should install MySQL on your system first and then this library.\n" ]
[ 3 ]
[]
[]
[ "macos", "mysql", "osx_lion", "python" ]
stackoverflow_0008660428_macos_mysql_osx_lion_python.txt
Q: multiprocess a function with a element of list as argument I am trying to acheive multi processing in python. I might have a minimum of 500 elements in the list at least. I have a function to which each element of a list needs to be passed as an argument. Then each of this function should be executed as a seperate...
multiprocess a function with a element of list as argument
I am trying to acheive multi processing in python. I might have a minimum of 500 elements in the list at least. I have a function to which each element of a list needs to be passed as an argument. Then each of this function should be executed as a seperate process using mutli processing either starting a new interprett...
[ "The multiprocessing module contains all sorts of basic classes which can be helpful for this:\nfrom multiprocessing import Pool\ndef f(x):\n return x*x\n\np = Pool(5)\np.map(f, [1,2,3])\n\nAnd the work will be distributed among 3 processes.\nThis is fairly simple, but you can achieve much more using an externa...
[ 4 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008660677_python_python_3.x.txt
Q: How to import another external python module? this is probably a dumb question, but wasnt too sure what else to do. main.py import module2 global x hello="Hello" x=module2.message() x.say() module2.py class message: def say(): print hello When I print hello, i am referring to the hello variable in m...
How to import another external python module?
this is probably a dumb question, but wasnt too sure what else to do. main.py import module2 global x hello="Hello" x=module2.message() x.say() module2.py class message: def say(): print hello When I print hello, i am referring to the hello variable in main.py however this method will return an error. Do...
[ "The only reliable solution is called encapsulation.\nSo, basically, you could change your code to look like that:\nmain.py\nimport module2\n\nglobal x\nhello=\"Hello\"\nx=module2.message(hello)\nx.say()\n\nmodule2.py\nclass message:\n def __init__(self, hello):\n self.hello = hello\n def say():\n ...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008660746_python.txt
Q: Need suggestion about MMORPG data model design, database access and stackless python I'm engaged in developing a turn-based casual MMORPG game server. The low level engine(NOT written by us) which handle networking, multi-threading, timer, inter-server communication, main game loop etc, was written by C++. The hig...
Need suggestion about MMORPG data model design, database access and stackless python
I'm engaged in developing a turn-based casual MMORPG game server. The low level engine(NOT written by us) which handle networking, multi-threading, timer, inter-server communication, main game loop etc, was written by C++. The high level game logic was written by Python. My question is about the data model design in ou...
[ "I've worked with one MMO engine that operated in a somewhat similar fashion. It was written in Java, however, not Python.\nWith regards to your first set of points:\n1) async db access We actually went the other route, and avoided having a “main game logic thread.” All game logic tasks were spawned as new threads....
[ 6, 2 ]
[]
[]
[ "database", "python", "python_stackless" ]
stackoverflow_0008660622_database_python_python_stackless.txt
Q: Python, Numpy, and OLS The code below works as intended, but it's not quite what I need. I want to to change c[1] to c[1:] so that I regress against all of the x variables instead of just one. When I make that change (and add the appropriate x labels), I get the following error: ValueError: matrices are not aligne...
Python, Numpy, and OLS
The code below works as intended, but it's not quite what I need. I want to to change c[1] to c[1:] so that I regress against all of the x variables instead of just one. When I make that change (and add the appropriate x labels), I get the following error: ValueError: matrices are not aligned. Can someone explain why t...
[ "I don't know anything about the ols module you're using. But if you try the following with scikits.statsmodels, it should work:\nimport numpy as np\nimport scikits.statsmodels.api as sm\n\na = np.array([[.001,.05,-.003,.014,.035,-.01,.032,-.0013,.0224,.005],[-.011,.012,.0013,.014,-.0015,.019,-.032,.013,-.04,-.056...
[ 2 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0008643332_matrix_numpy_python.txt
Q: Script doesn't download large images i use this script to download images from the same html page. But if images large enough, this script doesnt download properly - all images are 1,15 Kb and dont display. How can i fix it? what's wrong? A: If you download and inspect the HTML in http://tema.ru/travel/new-york...
Script doesn't download large images
i use this script to download images from the same html page. But if images large enough, this script doesnt download properly - all images are 1,15 Kb and dont display. How can i fix it? what's wrong?
[ "If you download and inspect the HTML in http://tema.ru/travel/new-york.2011.11/, you see things like\n<img src=\"IMG_5072.jpg\" alt=\"\" width=\"1000\" height=\"667\" border=\"1\" />\n\nSo this page is using relative links.\nThe line\nparsed[2] = image[\"src\"]\n\nchanges parsed from \n['http', 'tema.ru', '/travel...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0008660419_python.txt
Q: How do you integrate HTML with Django? I have an HTML file that has a web page design with a single form, for a user to enter his name. I want to create an six entry array for every submission (to later be filled with information on another page) Is Django the proper utility to use for this? I would like to have t...
How do you integrate HTML with Django?
I have an HTML file that has a web page design with a single form, for a user to enter his name. I want to create an six entry array for every submission (to later be filled with information on another page) Is Django the proper utility to use for this? I would like to have the html design file and the python back end ...
[ "Django may be overkill for this. If all you want is a way to link a form to some backend Python code, a micro framework like Flask might be a better choice.\nHere is how you do a simple form with Flask:\nCreate a directory project and inside it, a directory templates\nYour template is simple:\n{% if name %}\n H...
[ 9, 2, 1 ]
[]
[]
[ "css", "django", "html", "python" ]
stackoverflow_0008649720_css_django_html_python.txt
Q: django - does not save to database immediately another newbie question, Right after I save an item to database, I tried to access its primary key to redirect its page. But I could not get it done. I tried manually handling the transaction as it explains in this document. Could that be because of using admin mode?...
django - does not save to database immediately
another newbie question, Right after I save an item to database, I tried to access its primary key to redirect its page. But I could not get it done. I tried manually handling the transaction as it explains in this document. Could that be because of using admin mode? I get this error : invalid literal for int() with...
[ "Remove the id field from your Model class.\nDjango will insert an AutoField called id automatically if you don't specify a primary key, so you don't need it.\nBecause you have specifically said that your id field is an integer primary key, Django is expecting you to manage it yourself. It's an IntField, as you dec...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008660472_django_python.txt
Q: to_python being called every time data is loaded from DB I have various database fields that are decrypted using the to_python method. The problem I'm having is that every time I access the admin section (admin.ModelAdmin list) for this particular model, the page takes ages to load. I don't need the to_python meth...
to_python being called every time data is loaded from DB
I have various database fields that are decrypted using the to_python method. The problem I'm having is that every time I access the admin section (admin.ModelAdmin list) for this particular model, the page takes ages to load. I don't need the to_python method to decrypt fields on the list page, as the fields or the co...
[ "So the issue is that the admin will load the entire model instance for each row, even though you're only displaying a few fields. The solution should be to override the queryset method in your ModelAdmin subclass so that instead of using the standard get_query_set method of the default manager, it uses the only me...
[ 5 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0008661010_django_django_admin_python.txt
Q: Creating n-ary tree with weights for each branch In Python, I want to create a n-ary tree with any number of branches where each branch gets a weight. Here is the example: Node A has three children B, C, D with weights 100, -200, 250; B is leaf node; C has two children E, F with weights 150, 200; E...
Creating n-ary tree with weights for each branch
In Python, I want to create a n-ary tree with any number of branches where each branch gets a weight. Here is the example: Node A has three children B, C, D with weights 100, -200, 250; B is leaf node; C has two children E, F with weights 150, 200; E and F are leaf nodes; D has two children G and H ...
[ "This should be enough to get your started:\nclass TreeNode():\n def __init__(self,initWeight=<default>):\n self.children = List()\n self.weight = initWeight\n\n def addChild(self, weight):\n self.children.append(TreeNode(weight))\n\nYou just need a list of children and a weight field. Y...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "tree" ]
stackoverflow_0008660755_python_tree.txt
Q: How to use readline() with a pipe returned by subprocess.Popen I'm calling a child process using subprocess.Popen (Python 2.x on a POSIX system). I want to be able to read the output of the child process using Python's readline() file object function. However, the stream available in Popen.stdout does not appear t...
How to use readline() with a pipe returned by subprocess.Popen
I'm calling a child process using subprocess.Popen (Python 2.x on a POSIX system). I want to be able to read the output of the child process using Python's readline() file object function. However, the stream available in Popen.stdout does not appear to have a readline() method. Using the idea from Python readline from...
[ "The solution is to use os.dup() to create another file descriptor referring to the same pipe:\nstatus = os.fdopen(os.dup(p.stdout.fileno()))\n\nThis way, status has its own file descriptor to close.\n" ]
[ 2 ]
[]
[]
[ "pipe", "python", "readline", "subprocess" ]
stackoverflow_0008661710_pipe_python_readline_subprocess.txt
Q: Button content into the Entry my question is how can i implement it when i click the button â it will paste inside the Entry â as character or more of those buttons I don't need the code for it. What i need is the idea to do this. A: This shows how to do it for two buttons, using a tkinter Entry widget: from Tki...
Button content into the Entry
my question is how can i implement it when i click the button â it will paste inside the Entry â as character or more of those buttons I don't need the code for it. What i need is the idea to do this.
[ "This shows how to do it for two buttons, using a tkinter Entry widget:\nfrom Tkinter import *\n\nclass Application(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n\n self.text = Entry(self)\n self.text.pack({\"side\": \"left\"})\n\n self.but1 = Button(self)...
[ 1 ]
[]
[]
[ "python", "tk_toolkit", "tkinter" ]
stackoverflow_0008661197_python_tk_toolkit_tkinter.txt
Q: Qt/QSqlQuery: Binary data is interpreted as string when binding to BLOB field I'm reading binary data from files and try to store it in a LONGBLOB field in a MySql database. I'm using Python and PySide for this. My problem is, that the binary data is interpreted as a string, meaning the data is truncated when a ne...
Qt/QSqlQuery: Binary data is interpreted as string when binding to BLOB field
I'm reading binary data from files and try to store it in a LONGBLOB field in a MySql database. I'm using Python and PySide for this. My problem is, that the binary data is interpreted as a string, meaning the data is truncated when a newline occurs in the data. This seems to be a Python or PySide problem, because if I...
[ "The data is really truncated when a NULL Character ('\\0') is found in the data. In C++ you have to Create the QByteArray in this way:\nQByteArray data = QByteArray(\"start\\n\\0\\n\\0\\n\\0\\nend\", 15);\n\nI do not know python but I think that you have to create a QByteArray too.\n" ]
[ 6 ]
[]
[]
[ "blob", "mysql", "pyside", "python", "qt" ]
stackoverflow_0008657086_blob_mysql_pyside_python_qt.txt
Q: gai error at /home [Errno -2] Name or service not known per the example in the httplib docs: >>> import httplib, urllib >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) >>> headers = {"Content-type": "application/x-www-form-urlencoded", ... "Accept": "text/plain"} >...
gai error at /home [Errno -2] Name or service not known
per the example in the httplib docs: >>> import httplib, urllib >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) >>> headers = {"Content-type": "application/x-www-form-urlencoded", ... "Accept": "text/plain"} >>> conn = httplib.HTTPConnection("bugs.python.org") >>> conn....
[ "You've misunderstood the documentation to httplib. The parameter to instantiate the HTTPSConnection is just the hostname. You then pass the actual path as the second param to request. So:\nconnection = httplib.HTTPSConnection('rpxnow.com')\nconnection.request('POST', '/api/v2/auth_info', params)\n\n", "I don't k...
[ 4, 0, 0 ]
[]
[]
[ "django", "django_views", "httplib", "https", "python" ]
stackoverflow_0008661730_django_django_views_httplib_https_python.txt
Q: Custom CSS classes for SQLFORM widget input in web2py Given this SQLFORM in the controller: form = SQLFORM.factory(db.source_server, db.target_server) with the following table definition: db.define_table('target_server', Field('target_url', 'string'), Field('target_user', 'string')...
Custom CSS classes for SQLFORM widget input in web2py
Given this SQLFORM in the controller: form = SQLFORM.factory(db.source_server, db.target_server) with the following table definition: db.define_table('target_server', Field('target_url', 'string'), Field('target_user', 'string'), Field('target_password', 'password')) db....
[ "Note, all widgets already have a class named for the type of widget (e.g., \"string\", \"integer\", \"date\", etc.) as well as an id of the form \"tablename_fieldname\", so you might be able to make use of those in your CSS without needing to add custom classes. See here for more details.\nIf you do need to custom...
[ 8 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0008661166_python_web2py.txt
Q: Optimizing `in` I am using such constructs to test whether a needed key is pressed: def eventFilter(self, tableView, event): if event.type() == QtCore.QEvent.KeyPress: key = event.key() if event.modifiers() in (QtCore.Qt.NoModifier, QtCore.Qt.KeypadModifier): if key in (QtCore.Qt.Ke...
Optimizing `in`
I am using such constructs to test whether a needed key is pressed: def eventFilter(self, tableView, event): if event.type() == QtCore.QEvent.KeyPress: key = event.key() if event.modifiers() in (QtCore.Qt.NoModifier, QtCore.Qt.KeypadModifier): if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Ke...
[ "Your code:\ndef eventFilter(self, tableView, event): \n if event.type() == QtCore.QEvent.KeyPress: \n key = event.key() \n if event.modifiers() in (QtCore.Qt.NoModifier, QtCore.Qt.KeypadModifier): \n if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): \n self.menu.edit...
[ 3, 2, 1, 0 ]
[]
[]
[ "optimization", "pyqt", "pyqt4", "python", "python_3.x" ]
stackoverflow_0008655224_optimization_pyqt_pyqt4_python_python_3.x.txt
Q: How do you make an object return a sorted array instead of an empty one in python? I'm trying to create a library of some common algorithms so that people will be able to use them easily. I created an object called Compare, which has some methods that would be useful in these algorithms. Code for Compare: class C...
How do you make an object return a sorted array instead of an empty one in python?
I'm trying to create a library of some common algorithms so that people will be able to use them easily. I created an object called Compare, which has some methods that would be useful in these algorithms. Code for Compare: class Compare(list): def __init__(self,arr): self.arr = arr def __compare(sel...
[ "I'm pretty sure this is what is happening. When you call :\narray = Compare(array)\n\nYou overwrite the reference to the original array. Array is now a reference to a Compare object. Replace array with array.arr (or name array something better) and this should work I think! :)\nRemember that python is loosely type...
[ 1, 1, 0 ]
[]
[]
[ "arrays", "python", "sorting" ]
stackoverflow_0008661783_arrays_python_sorting.txt
Q: in Python, how to separate Local Hard Drives from Network and Floppy in Windows? I've been looking for this info for awhile, and I have a number of ways to retrieve a list of local drives under Windows. Here are two examples: print win32api.GetLogicalDriveStrings().split("\x00") and def getDriveLetters(self): ...
in Python, how to separate Local Hard Drives from Network and Floppy in Windows?
I've been looking for this info for awhile, and I have a number of ways to retrieve a list of local drives under Windows. Here are two examples: print win32api.GetLogicalDriveStrings().split("\x00") and def getDriveLetters(self): self.drvs = [] n_drives = win32api.GetLogicalDrives() for i in range(0,25):...
[ "You can try the win32 GetDriveType function.\nimport win32file\n>>> win32file.GetDriveType(\"C:/\") == win32file.DRIVE_FIXED ##hardrive\nTrue\n>>> win32file.GetDriveType(\"Z:/\") == win32file.DRIVE_FIXED ##network\nFalse\n>>> win32file.GetDriveType(\"D:/\") == win32file.DRIVE_FIXED ##cd-rom\nFalse\n\n", "Thank y...
[ 10, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0004491601_python_winapi.txt
Q: Trouble with named groups in Django I'm playing with django urls.py and have some problems with the named groups syntax Like this without named groups it works... urlpatterns = patterns('', (r'^$',index), (r'^admin/', include(admin.site.urls)), (r'^',test), ) but with named groups i have a syntax...
Trouble with named groups in Django
I'm playing with django urls.py and have some problems with the named groups syntax Like this without named groups it works... urlpatterns = patterns('', (r'^$',index), (r'^admin/', include(admin.site.urls)), (r'^',test), ) but with named groups i have a syntax error, which i can't solve urlpatterns =...
[ "That's quite obviously a syntax error. For a start, you have most of the characters outside the quote marks, and secondly, the syntax you have for your \"named groups\" is not even close to correct.\nYou should read the documentation more closely, followed by an introduction to regular expressions.\n(r'^(?P<requrl...
[ 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008662042_django_python.txt
Q: Yield sub combinations with limit I'm working with python 3. The function I'm working with is as follows: def sub_combinations(segment): if len(segment) == 1: yield (segment,) else: for j in sub_combinations(segment[1:]): yield ((segment[0],),)+j for k in range(len(j)): yield (((s...
Yield sub combinations with limit
I'm working with python 3. The function I'm working with is as follows: def sub_combinations(segment): if len(segment) == 1: yield (segment,) else: for j in sub_combinations(segment[1:]): yield ((segment[0],),)+j for k in range(len(j)): yield (((segment[0],)+j[k]),) + (j[:k]) +(j[k+1:]...
[ "I think the following change results in the output you are looking for:\ndef sub_combinations(segment, max_offset=None):\n data = tuple([e] for e in segment)\n def _sub_combinations(segment):\n if len(segment) == 1:\n yield (segment,)\n else:\n for j in _sub_combinations(segment[1:]):...
[ 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008661959_algorithm_python.txt
Q: mod_wsgi isn't honoring WSGIPythonHome I'm trying to get WSGI to run with a virtualenv setup. I have the virtualenv all working right: (virtualenv)dev:/var/www/app$ which python /var/www/virtualenv/bin/python (virtualenv)dev:/var/www/app$ python Python 2.6.1 (r261:67515, Dec 5 2008, 22:09:34) [GCC 4.1.2] on linux...
mod_wsgi isn't honoring WSGIPythonHome
I'm trying to get WSGI to run with a virtualenv setup. I have the virtualenv all working right: (virtualenv)dev:/var/www/app$ which python /var/www/virtualenv/bin/python (virtualenv)dev:/var/www/app$ python Python 2.6.1 (r261:67515, Dec 5 2008, 22:09:34) [GCC 4.1.2] on linux2 Type "help", "copyright", "credits" or "li...
[ "Your mod_wsgi is likely compiled against a different Python version than you are trying to force it to use. For example, you can not use mod_wsgi compiled against Python 2.4 with a virtual environment constructed using Python 2.6.\nValidate what version of Python mod_wsgi was built for in the first place.\n" ]
[ 20 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0008660896_apache_mod_wsgi_python.txt
Q: Python 2.7.2 install on Suse Linux Server 11.3 can't find tkinter dependencies I've spent hours on this. Seems like our job on Linux is to debug scripts that don't work across the fragmented distros rather than getting work done. Setup.py tries to find what it needs and build the c modules used to wrap certain de...
Python 2.7.2 install on Suse Linux Server 11.3 can't find tkinter dependencies
I've spent hours on this. Seems like our job on Linux is to debug scripts that don't work across the fragmented distros rather than getting work done. Setup.py tries to find what it needs and build the c modules used to wrap certain dependencies if it can find what it needs. This makes the script super fragile relati...
[ "I found many distribution points for sets of rpm packages. This enabled me to install individual packages such as the headers for tcl. But, this was a bad approach because the full dependency hierarchy to build Python support for tkinter is something on the order of 60 packages.\nI found that the OpenSuSE reposi...
[ 0 ]
[]
[]
[ "build", "python", "suse" ]
stackoverflow_0008650079_build_python_suse.txt
Q: Plotting Complex Numbers in Python? For a math fair project I want to make a program that will generate a Julia set fractal. To do this i need to plot complex numbers on a graph. Does anyone know how to do this? Remember I am using complex numbers, not regular coordinates. Thank You! A: You could plot the real p...
Plotting Complex Numbers in Python?
For a math fair project I want to make a program that will generate a Julia set fractal. To do this i need to plot complex numbers on a graph. Does anyone know how to do this? Remember I am using complex numbers, not regular coordinates. Thank You!
[ "You could plot the real portion of the number along the X axis and plot the imaginary portion of the number along the Y axis. Plot the corresponding pixel with whatever color makes sense for the output of the Julia function for that point.\n", "Julia set renderings are generally 2D color plots, with [x y] repres...
[ 2, 0 ]
[]
[]
[ "complex_numbers", "fractals", "graph", "python" ]
stackoverflow_0008662501_complex_numbers_fractals_graph_python.txt
Q: Shared binary format between iOS and Python Is there a shared binary format between iOS and Python? I found binary property lists. I have a list of UIBeziarPaths in an array that I want to be able to send to Python. I am just looking for something that will very efficiently be able to do that. I looked into the t...
Shared binary format between iOS and Python
Is there a shared binary format between iOS and Python? I found binary property lists. I have a list of UIBeziarPaths in an array that I want to be able to send to Python. I am just looking for something that will very efficiently be able to do that. I looked into the text based formats like JSON except they seem less...
[ "Python has a struct standard module that allows easy manipulation of simple binary formats with conversion to python types (struct.unpack) or in the opposite direction (struct.pack).\n", "There are no formats specifically designed for iOS/Python. There are numerous data interchange formats you could use, includi...
[ 1, 1 ]
[]
[]
[ "binary", "ios", "python" ]
stackoverflow_0008662519_binary_ios_python.txt
Q: Install Python 3.0, now I cannot get my functions to work I installed Python 3.0 and now I can't get my code to work. Does anyone have any suggestions? def print_multiples(n, high): for i in range(1, high+1): print(n * i, end=' ') print() def print_mult_table(high): for i in range(1, high+1)...
Install Python 3.0, now I cannot get my functions to work
I installed Python 3.0 and now I can't get my code to work. Does anyone have any suggestions? def print_multiples(n, high): for i in range(1, high+1): print(n * i, end=' ') print() def print_mult_table(high): for i in range(1, high+1): print_multiples(i, high) print print_mult_table(7) ...
[ "In Python 3 print() is a function not a statement so you should use:\n print(print_mult_table(7))\n\n", "This is a syntax error because print is no longer a statement in Python3\nProbably \nprint_mult_table(7)\n\nwithout the print in front will do what you want. Since the function does some printing itself, unle...
[ 4, 3 ]
[]
[]
[ "function", "python" ]
stackoverflow_0008662695_function_python.txt
Q: rvmsudo analog for python/virtualenv As anyone who knows what virtualenv does for python there is an analog for ruby. What's interesting about the ruby installation is that there is a "rvmsudo" that projects the current rvm environment on the root/sudo user before executing the requested command. virtualenv does n...
rvmsudo analog for python/virtualenv
As anyone who knows what virtualenv does for python there is an analog for ruby. What's interesting about the ruby installation is that there is a "rvmsudo" that projects the current rvm environment on the root/sudo user before executing the requested command. virtualenv does not offer an obvious implementation of the ...
[ "One work around is to use \"sudo -E\". This will preserve the calling user's environment across the sudo. Note that if the adversary controls your environment this is an immediate root exploit (via LD_LIBRARY_PATH and similar).\n" ]
[ 1 ]
[]
[]
[ "python", "rvm", "virtualenv" ]
stackoverflow_0008630305_python_rvm_virtualenv.txt
Q: How to run multiple python commands at the same time? I've read that subprocess should be used but all the examples i've seen on it shows that it runs only command-line commands. I want my program to run a python command along with another command. The command i want to run is to send an email to a user while a us...
How to run multiple python commands at the same time?
I've read that subprocess should be used but all the examples i've seen on it shows that it runs only command-line commands. I want my program to run a python command along with another command. The command i want to run is to send an email to a user while a user plays a game i created. i have to have the python comman...
[ "It sounds like you are looking for threading, which is a relatively deep topic, but this should help you get started: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/\n", "Threading is talked about in another answer, but you can get basically what you want by using subprocess's Popen command: http://...
[ 3, 2 ]
[]
[]
[ "email", "python", "subprocess" ]
stackoverflow_0008662887_email_python_subprocess.txt
Q: Update google map position based on gps coords I have an Arduino w/ GPS chip, processing NMEA strings w/ python. I have a HTML file that I open and have auto refresh every x-seconds s.t. the marker updates, but I'd really like to be able to update the position information without doing a refresh. I know it can b...
Update google map position based on gps coords
I have an Arduino w/ GPS chip, processing NMEA strings w/ python. I have a HTML file that I open and have auto refresh every x-seconds s.t. the marker updates, but I'd really like to be able to update the position information without doing a refresh. I know it can be done w/ drag and drop as demoed here: http://gmaps...
[ "Instead of doing refreshes, you could setup ajax short polling - essentially have your page check with an end point that returns the position of the marker every few seconds. Here's a post talking about it and linking to a tutorial: Real-time data on webpage with jQuery\nAnother alternative would be to setup a lon...
[ 1 ]
[]
[]
[ "google_maps", "html", "javascript", "python" ]
stackoverflow_0008662402_google_maps_html_javascript_python.txt
Q: having problems when dumps dict to json? Here, I want to dump a "big" dict into json, as following: #!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json doc = {} # appending the doc, so that the doc is more than 2G ..... json_doc = json.dumps(doc) Then i got the following error message: Fi...
having problems when dumps dict to json?
Here, I want to dump a "big" dict into json, as following: #!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json doc = {} # appending the doc, so that the doc is more than 2G ..... json_doc = json.dumps(doc) Then i got the following error message: File "C:\Python27\lib\site-packages\simplejson\_...
[ "If there is barely enough memory you could try to encode the object to json incrementally:\nimport json\nimport sys\n\nd = dict.fromkeys(range(10))\nfor chunk in json.JSONEncoder().iterencode(d):\n print(chunk) # print each chunk on a newline for demonstration\n\nDon't accumulate the output in a string use file...
[ 5 ]
[]
[]
[ "dump", "json", "memory", "python", "simplejson" ]
stackoverflow_0008663274_dump_json_memory_python_simplejson.txt
Q: Searching for a string in a multidimentional list and appending the sublist containing match to empty list I have a question that is similar to this question, but mine concerns multidimentional lists like this: myList = [['abc', 'abc-321'], ['def', '789-abc'], ['xyz', 'xyz-123']] newList = [] I want to search thi...
Searching for a string in a multidimentional list and appending the sublist containing match to empty list
I have a question that is similar to this question, but mine concerns multidimentional lists like this: myList = [['abc', 'abc-321'], ['def', '789-abc'], ['xyz', 'xyz-123']] newList = [] I want to search this myList for a certain word/phrase, and if there are matches, the entire sublist to be appended to newList, with...
[ "Try This\ndef foo(myList,key,first=True):\n if first: #First Element Search\n return [x for x in myList if key in x]\n else: #Search Both Element\n return [x for x in myList if key in x or key in x[1]]\n\n>>> foo(myList,'abc',0)\n[['abc', 'abc-321']]\n>>> foo(myList,'abc',1)\n[['abc', 'abc-321'...
[ 1, 1, 0 ]
[]
[]
[ "iterator", "list", "python" ]
stackoverflow_0008663783_iterator_list_python.txt