content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
python - appengine image api error
def embedd_image():
from google.appengine.api import images
img1 = images.Image('/home/ubuntu/a.png') // Here I am getting **error
img2 = images.Image('/home/ubuntu/text.png') // Here I am getting **error ... | python - appengine image api error | def embedd_image():
from google.appengine.api import images
img1 = images.Image('/home/ubuntu/a.png') // Here I am getting **error
img2 = images.Image('/home/ubuntu/text.png') // Here I am getting **error ... | [
"From docs:\n\nclass Image(image_data=None, blob_key=None)\n...\nimage_data The image data, as a bytestring (str). The image\n data can be encoded in JPEG, PNG, WEBP, GIF (including animated), BMP,\n TIFF, or ICO format.\n\nas a bytestring:\nimg1 = images.Image(open('/home/ubuntu/a.png').read()) \n\n"
] | [
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0008544657_django_google_app_engine_python.txt |
Q:
tokenize an email using python
I need to tokenize an email using python
Means, I need the headers, the text, each and everything to be stored in some different variable.
Currently I am trying to do it with this email class of python
Please let me know how to do it even if you know with email class
Thank you
Regar... | tokenize an email using python | I need to tokenize an email using python
Means, I need the headers, the text, each and everything to be stored in some different variable.
Currently I am trying to do it with this email class of python
Please let me know how to do it even if you know with email class
Thank you
Regards,
Puneet
| [
"Look in the standard python library documentation for the email package\nUse email.parser.Parser.parse function to return a email.message.Message object that has the headers in a dictionary like representation\n"
] | [
0
] | [] | [] | [
"email",
"python",
"tokenize"
] | stackoverflow_0008544829_email_python_tokenize.txt |
Q:
Is importing like this legal or not recommended?
Is it legal to make an import like this:
from webapp2_extras.appengine.auth.models import User as webapp2.User
I'd like to refer to the object as webapp2.User even though it technically is not. This is because there are other object named User so I'd proabbly name ... | Is importing like this legal or not recommended? | Is it legal to make an import like this:
from webapp2_extras.appengine.auth.models import User as webapp2.User
I'd like to refer to the object as webapp2.User even though it technically is not. This is because there are other object named User so I'd proabbly name Users with this model something like webapp2_user as d... | [
"from webapp2_extras.appengine.auth.models import User as webapp2.User\n\nis invalid syntax, python doesn't allow you to have a . in as webapp2.User you should use as webapp2_User instead.\n",
"It's both illegal and not recommended.\nIf you'd like your User base class to be used in different applications, you sho... | [
2,
1
] | [] | [] | [
"python",
"webapp2"
] | stackoverflow_0008545078_python_webapp2.txt |
Q:
How to catch auth errors in Fabric and retry?
I have two usernames and corresponding passwords that I use to admin my servers, is there a way to have my fab scripts/modules, use one and then the second if the first one failed, with out having to maintain a full list of credentials for each host or even group of th... | How to catch auth errors in Fabric and retry? | I have two usernames and corresponding passwords that I use to admin my servers, is there a way to have my fab scripts/modules, use one and then the second if the first one failed, with out having to maintain a full list of credentials for each host or even group of them.
I see no way in the docs to doa try/except arou... | [
"run and other commands raise SystemExit\nfrom fabric.api import run,cd,put,sudo,settings\n\ndef do_stuff():\n run('ls derp')\n\ntry:\n with(settings(host_string='%s@localhost' % first_user,password = first_password)):\n do_stuff()\nexcept SystemExit:\n with(settings(host_string='%s@localhost' % sec... | [
1
] | [] | [] | [
"fabric",
"python"
] | stackoverflow_0005481742_fabric_python.txt |
Q:
Design pattern help
I have some algorithms to do that are very similar in very aspects but are all different.
I'll try to give an example of what I mean.
Let's assume I have a Robot class. This class should be the "base" of all classes. It provides basic mechanisms to make the robot work in its environment. It mi... | Design pattern help | I have some algorithms to do that are very similar in very aspects but are all different.
I'll try to give an example of what I mean.
Let's assume I have a Robot class. This class should be the "base" of all classes. It provides basic mechanisms to make the robot work in its environment. It might or not have to work b... | [
"The design patterns I'd probably go with for such a problem are: Dependency Injection and a framework to go with it, the Composite pattern, and the Builder pattern. They should basically let you separate the creation of your Robots from their use. \n",
"I think your robot should have a list of ports i.e. a numbe... | [
5,
4,
1,
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0001899503_design_patterns_python.txt |
Q:
how to do couples of word and its number of occurrence using list generator?
trying to print the words and num of occurrence. like that:
in 1.txt:
a aba aaa
dd ddd dd
my out shold contains:
[[a,1],[dd,2],[aba ,1],[ddd,1],[aaa,1]]
but it is :
[[a,1],[dd,2],[aba ,1],[dd,2],[ddd,1],[aaa,1]]
here is the full code:... | how to do couples of word and its number of occurrence using list generator? | trying to print the words and num of occurrence. like that:
in 1.txt:
a aba aaa
dd ddd dd
my out shold contains:
[[a,1],[dd,2],[aba ,1],[ddd,1],[aaa,1]]
but it is :
[[a,1],[dd,2],[aba ,1],[dd,2],[ddd,1],[aaa,1]]
here is the full code:
import re
def get_words_from_string(s):
return (re.findall(re.compile('\w+'... | [
"from collections import Counter\n\nwith open(\"1.txt\") as f:\n words = f.read().split()\n\nc = Counter(words)\n\nprint [[word,count] for word, count in c.iteritems()]\n\n",
"This line\nout = [[word , l1.count(word)] for word in l1 if (not(-1<l1.index(word)))]\n\nsays \"create a list of word/count lists for ea... | [
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008542248_python.txt |
Q:
Connecting to mongodb in a testable way
I'm planning to write a webapp in python using Flask and MongoDB (and probably Ming as ODM). The problem is I would like to keep my model and controller really well separated, one reason for this would be to be able to run simple unittests on the separate components.
Now her... | Connecting to mongodb in a testable way | I'm planning to write a webapp in python using Flask and MongoDB (and probably Ming as ODM). The problem is I would like to keep my model and controller really well separated, one reason for this would be to be able to run simple unittests on the separate components.
Now here is my problem, at some point in the request... | [
"One approach could be to make use of Python module level singleton pattern. \nCreate a module having 'conn' object, (using just plain PyMongo)\ntry:\n conn = Connection(max_pool_size=20)\nexcept ConnectionFailure:\n app.logger.critical(\"Unable to connect to MongoDB\")\n\nand then just create a wrapper for P... | [
5
] | [] | [] | [
"flask",
"ming",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0008543730_flask_ming_mongodb_pymongo_python.txt |
Q:
How to write a Python console program can output like the top command in Linux?
The output of top command in Linux like bellow:
Tasks: 158 total, 1 running, 157 sleeping, 0 stopped, 0 zombie
Cpu(s): 6.3%us, 3.2%sy, 0.0%ni, 89.9%id, 0.2%wa, 0.0%hi, 0.2%si,
0.0%st Mem: 8264212k total, 2637492k us... | How to write a Python console program can output like the top command in Linux? | The output of top command in Linux like bellow:
Tasks: 158 total, 1 running, 157 sleeping, 0 stopped, 0 zombie
Cpu(s): 6.3%us, 3.2%sy, 0.0%ni, 89.9%id, 0.2%wa, 0.0%hi, 0.2%si,
0.0%st Mem: 8264212k total, 2637492k used, 5626720k free, 299884k buffers Swap: 4192924k total, 0k used, 4192924... | [
"You will need to use a library for handling the interaction with the console, e.g. http://docs.python.org/howto/curses.html\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0008545753_python.txt |
Q:
detect a ctrl-click on taskbar menu
The code below is a simplified version of my task bar icon class, I haven't checked the GetKeyCode() value to see if it's a ctrl as the key press events aren't being fired. Should I be binding key presses to somewhere else?
class TBI(wx.TaskBarIcon):
TBMENU_CTRLCLICK= wx.New... | detect a ctrl-click on taskbar menu | The code below is a simplified version of my task bar icon class, I haven't checked the GetKeyCode() value to see if it's a ctrl as the key press events aren't being fired. Should I be binding key presses to somewhere else?
class TBI(wx.TaskBarIcon):
TBMENU_CTRLCLICK= wx.NewId()
def __init__(self,frame):
... | [
"Use wx.GetKeyState as so:\nimport wx\n\nclass TBI(wx.TaskBarIcon):\n def __init__(self):\n wx.TaskBarIcon.__init__(self)\n icon = wx.ArtProvider.GetIcon(wx.ART_FILE_OPEN, wx.ART_TOOLBAR)\n self.SetIcon(icon, \"Icon\")\n self.Bind(wx.EVT_TASKBAR_RIGHT_UP, self.on_right_up)\n\n def ... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0008493743_python_wxpython.txt |
Q:
How to get all possible combinations
I've got something dict like that:
{'Y': [1, 2, 6, 7],
'X': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
'Z': [0, 3, 6, 9]}
There could be more than 3 variables.
I wan't to get all combination of these variables.
To get somethin... | How to get all possible combinations | I've got something dict like that:
{'Y': [1, 2, 6, 7],
'X': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
'Z': [0, 3, 6, 9]}
There could be more than 3 variables.
I wan't to get all combination of these variables.
To get something like:
[{'Y': 1, 'X': 0, 'Z': 0},
{'Y':... | [
"The other posters are right: itertools.product is very helpful here. However, some care will be needed to ensure you get the original dictionary keys, because of the way your dictionary is formatted.\nimport itertools\n\ndata = {'Y': [1, 2, 6, 7],\n 'X': [0, 1, 2, 3, 4, 5, 6, 7,\n 8, 9, 10, 11,... | [
4,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0008545870_python.txt |
Q:
Searching and writing
I need to write a program which looks for words with the same three middle characters(each word is 5 characters long) in a list, then writes them into a file like this :
wasdy
casde
tasdf
gsadk
csade
hsadi
Between the similar words i need to leave an empty line. I am kinda stuck.
Is there a... | Searching and writing | I need to write a program which looks for words with the same three middle characters(each word is 5 characters long) in a list, then writes them into a file like this :
wasdy
casde
tasdf
gsadk
csade
hsadi
Between the similar words i need to leave an empty line. I am kinda stuck.
Is there a way to do this? I use Pyth... | [
"I would use the itertools.groupby function for this. Assuming wordlist is a list of the words you want to group, this code does the trick.\nimport itertools\n\nfor k, v in itertools.groupby(wordlist, lambda word: word[1:4]):\n # here, k is the key the words are grouped by, i.e. word[1:4]\n # and v is a list/... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008545910_python_python_3.x.txt |
Q:
Authentication in web application
I'm making my first web app (python+webpy+mongodb). What's the best way to make authentication module? Should I save login to cookies, or just keep login/pass in variables? Do i have to make every 'restricted' function check user's rights every time it works? Maybe there are any g... | Authentication in web application | I'm making my first web app (python+webpy+mongodb). What's the best way to make authentication module? Should I save login to cookies, or just keep login/pass in variables? Do i have to make every 'restricted' function check user's rights every time it works? Maybe there are any good articles about these things?
| [
"Here's a good guide with explanations: Form Based Authentication For Websites.\nweb.py has a recipe for basic authentication which can be extended using these techniques.\nUsually you use a persistence mechanism known as sessions to track authenticated users. Have a look at Beaker to see how it can be implemented.... | [
5
] | [] | [] | [
"authentication",
"python",
"web.py"
] | stackoverflow_0008546128_authentication_python_web.py.txt |
Q:
numpy: point sum
>>> from pandac.PandaModules import Vec3
>>> import numpy
>>> l = []
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> Vec3(1,1,1)+Vec3(1,1,1)
Vec3(2, 2, 2)
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsuppor... | numpy: point sum | >>> from pandac.PandaModules import Vec3
>>> import numpy
>>> l = []
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> l.append( Vec3(1,1,1) )
>>> Vec3(1,1,1)+Vec3(1,1,1)
Vec3(2, 2, 2)
>>> sum(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) fo... | [
"Try this:\nsum(l, start=Vec3(0,0,0))\n\nOr, with numpy, this:\nnumpy.sum(l, axis=0)\n\nThe speed depends in the implementation of the vector-addition. You should use timeit to determine which method is fastest. This could look something like this:\npython -m timeit \"import numpy; foo = [[1,1,1],[1,1,1]]\" \"numpy... | [
2
] | [] | [] | [
"numpy",
"panda3d",
"python"
] | stackoverflow_0008546309_numpy_panda3d_python.txt |
Q:
Python Paste script crashes with big template file?
I have a Pyramid application that uses Chameleon as its template engine.
I have one (quite large, but I have had larger) template that will just not work.
Whenever I try to render it to return as a view, paste server development.ini crashes miserably without any ... | Python Paste script crashes with big template file? | I have a Pyramid application that uses Chameleon as its template engine.
I have one (quite large, but I have had larger) template that will just not work.
Whenever I try to render it to return as a view, paste server development.ini crashes miserably without any errors (Mac OS X's terminal tells me "bus error").
When I... | [
"Start by installing yolk so that you can list the versions of all the python packages you have installed with yolk -l.\nNext, you should post your template to gist or pastebin so people can see the template you're working with and try to reproduce the problem. In fact, it would be even more helpful if you can prov... | [
1
] | [] | [] | [
"chameleon",
"crash",
"paste",
"pyramid",
"python"
] | stackoverflow_0007021126_chameleon_crash_paste_pyramid_python.txt |
Q:
py2exe trouble for multiple scripts
I am working on a project on python. I have divided my complete script into 4 modules to make the code better understandable. I need to create a exe of the code which holds the gui.
The problem is that different modules have different dependencies.One module requires pyusb, one... | py2exe trouble for multiple scripts | I am working on a project on python. I have divided my complete script into 4 modules to make the code better understandable. I need to create a exe of the code which holds the gui.
The problem is that different modules have different dependencies.One module requires pyusb, one requires PIL and other requires scipy. H... | [
"By default py2exe should include all your imports into the bundle, but if this doesn't work, you can try false-importing the modules you need. you can do this in the main script that you are passing to py2exe:\nin your main script:\nif False:\n import <module x>, <module y>, <module z>, <etc...>\n\nThis should ... | [
0,
0
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0008530511_py2exe_python.txt |
Q:
decode the result from google in Python
I tried to make programme to get urls from google
but the problem is i got encoded urls ! like this !
`[u'http://www.motorrad-live.de/test.php%3Fid%3D11', u'http://www.autogaleria.pl/
auto_test/test.php%3Fid%3D37', u'http://oculus.ru/test.php%3Fid%3D2', u'http://o
culus.ru... | decode the result from google in Python | I tried to make programme to get urls from google
but the problem is i got encoded urls ! like this !
`[u'http://www.motorrad-live.de/test.php%3Fid%3D11', u'http://www.autogaleria.pl/
auto_test/test.php%3Fid%3D37', u'http://oculus.ru/test.php%3Fid%3D2', u'http://o
culus.ru/test.php%3Fid%3D1', u'http://www.kerrytaylor... | [
"you're searching for the function unquote:\nurllib.unquote(url)\n\n",
"first you need to quote the query string before interpolating it:\n>>> urllib.quote(\"inurl:\\\"test.php?id\\\"\")\n'inurl%3A%22test.php%3Fid%22'\n\n>>> \"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&gl=de&q=%(q)s&rsz=8&start=0\"... | [
3,
0
] | [] | [] | [
"encode",
"python",
"search"
] | stackoverflow_0008546392_encode_python_search.txt |
Q:
Why isn't this login view working? (Django)
I'm trying to create a login view with Django's cache system. Here's my code so far:
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username_exists ... | Why isn't this login view working? (Django) | I'm trying to create a login view with Django's cache system. Here's my code so far:
def login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username_exists = User.objects.filter(username=cd['username1'])
... | [
"The problem is that your final success clause involves checking a password directly vs user.password which is a one way hashed password. So you're likely checking mypassword vs sha1$b322a$7e51a244d45f70d17b0bbca2b7369c1732b09c69\nInstead, use django.contrib.auth.check_password or the authenticate function which w... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008545666_django_python.txt |
Q:
Alternatives to a ManytoManyField for static/hardcoded data?
I'm building a Django app in which I need to represent gender (male/female) for all users. A single user can select that they are interested in males, females, or both. This data will then be used to cross-reference with other users to find similarities.... | Alternatives to a ManytoManyField for static/hardcoded data? | I'm building a Django app in which I need to represent gender (male/female) for all users. A single user can select that they are interested in males, females, or both. This data will then be used to cross-reference with other users to find similarities. A ManytoManyField for gender will clearly work, but since gender ... | [
"Definitely shy away from an M2M - that will get expensive and just plain difficult to query over time with tons of double underscore notation. For static stuff, you specifically want choices.\nOne of the more useful coding practices I've learned over the years is an idea from James Bennets blog is the way he uses ... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0008546043_django_python.txt |
Q:
How To Replace and Append URL in File text with Keyword By Python?
Possible Duplicate:
How to search and replace text from one file to another using Python?
I have file1.txt :
<echo http://photobucket.com/98a267d32b056fb0a5c8c07dd4c35cc5.jpg ?>
http://lincoln.com/view/filename1.jpg
http://lincoln.com/banner1/f... | How To Replace and Append URL in File text with Keyword By Python? |
Possible Duplicate:
How to search and replace text from one file to another using Python?
I have file1.txt :
<echo http://photobucket.com/98a267d32b056fb0a5c8c07dd4c35cc5.jpg ?>
http://lincoln.com/view/filename1.jpg
http://lincoln.com/banner1/filename2.jpg
http://lincoln.com/banner1/filename3.jpg
And I have fil... | [
"This works given your urls are of the type 'http' as in your example.\nimport os\nbase = os.path.basename\n\nf2_lines = [line.strip() for line in open(\"file2.txt\")]\n\nmylines = []\nwith open(\"file1.txt\") as f:\n for line in f:\n line = line.strip()\n if not line.startswith('http'):\n ... | [
1
] | [] | [] | [
"append",
"python",
"replace",
"url"
] | stackoverflow_0008545539_append_python_replace_url.txt |
Q:
Python socket can't receive data
I'm writing interprocess communication using localhost sockets in Python 3.2 and testing it on Windows. Here is some test code with a server and a client, sending messages to each other. Strangely, it fails randomly with the RuntimeError error, raised in the receive function, somew... | Python socket can't receive data | I'm writing interprocess communication using localhost sockets in Python 3.2 and testing it on Windows. Here is some test code with a server and a client, sending messages to each other. Strangely, it fails randomly with the RuntimeError error, raised in the receive function, somewhere around the 5th or 10th connection... | [
"It is because of conn.shutdown(socket.SHUT_WR) in your server_function. What you need is socket.SHUT_RD, or better yet, get rid of the shutdown() call at all. \n"
] | [
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0008546206_python_sockets.txt |
Q:
Python turtle graphics malfunction on a Mac running OSX 10.6
This is the result when I attempt to run Python turtle graphics on my Mac.
Has anyone else seen this. Are there suggestions for fixing this problem. Thanks
in advance!
$ python
Python 2.6.1 (r261:67515, Aug 2 2010, 20:10:18)
[GCC 4.2.1 (Apple Inc. bu... | Python turtle graphics malfunction on a Mac running OSX 10.6 | This is the result when I attempt to run Python turtle graphics on my Mac.
Has anyone else seen this. Are there suggestions for fixing this problem. Thanks
in advance!
$ python
Python 2.6.1 (r261:67515, Aug 2 2010, 20:10:18)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "licen... | [
"Is your current directory /Users/morrison/ when you run this?\nIf so, the problem is that the interpreter's current working directory is being used for looking up python modules at runtime in addition to the standard locations. You have a file copy.py in this directory and it is being imported when the standard li... | [
3
] | [] | [] | [
"macos",
"python",
"tk_toolkit",
"tkinter",
"turtle_graphics"
] | stackoverflow_0008546349_macos_python_tk_toolkit_tkinter_turtle_graphics.txt |
Q:
Why does this socket connection only allow 1 send and receive?
Background
I have a simple socket server setup that I am trying to allow simultaneous connections to and echo back the data. The client side launches several threads each making its own connection to the server. This works fine for the socket.send() ... | Why does this socket connection only allow 1 send and receive? | Background
I have a simple socket server setup that I am trying to allow simultaneous connections to and echo back the data. The client side launches several threads each making its own connection to the server. This works fine for the socket.send() call, but all subsequent calls cause either a "Connection reset by p... | [
"When you return from handle the socket is closed. Use a while loop and return from handle only when self.data == ''. recv returns zero bytes when the client closes the connection. Also don't strip() the result until after testing the return value or you could get a false close. Finally, use ThreadingTCPServer o... | [
8
] | [] | [] | [
"broken_pipe",
"python",
"sockets",
"socketserver",
"tcp"
] | stackoverflow_0008546870_broken_pipe_python_sockets_socketserver_tcp.txt |
Q:
how to let my web-ui communitate(or control) my CLI program
I'm already implement a command line tool used for 802.1x authentication in python. But I want a gui frontend. I want to try a web UI this time, but I don't know how to let my webui communicate with my python app.
I only know that I need to open a socket ... | how to let my web-ui communitate(or control) my CLI program | I'm already implement a command line tool used for 802.1x authentication in python. But I want a gui frontend. I want to try a web UI this time, but I don't know how to let my webui communicate with my python app.
I only know that I need to open a socket in CLI program and receive the message send by the web ui. But I'... | [
"Python official wiki page about web programming and the wikipedia list of the web frameworks written in Python are good places to start from.\n"
] | [
0
] | [] | [] | [
"python",
"sockets",
"webui"
] | stackoverflow_0008546285_python_sockets_webui.txt |
Q:
Python 3 gives an UnicodeDecodeError when accessing a character device
One day I found a page on the web that covers interpreting input from game pads on Linux. The code is this:
import sys
pipe = open('/dev/input/js0','r')
while 1:
for character in pipe.read(1):
sys.stdout.write(repr(character))
... | Python 3 gives an UnicodeDecodeError when accessing a character device | One day I found a page on the web that covers interpreting input from game pads on Linux. The code is this:
import sys
pipe = open('/dev/input/js0','r')
while 1:
for character in pipe.read(1):
sys.stdout.write(repr(character))
sys.stdout.flush()
The program is used to open the character device fil... | [
"You're not going to be receiving characters from a game pad, only bytes. As such, you need to be reading bytes and not characters. Not all byte sequences will translate to a valid character, which is why you're receiving the error.\nSee Python's documentation for the open method at http://docs.python.org/library... | [
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0008547035_python_python_3.x.txt |
Q:
PyQt4 - Custom widget class structure?
During regular intervals of my program, a block (of 3 stacked) widgets need to be added to a horizontal layout. Since the widgets within each block are important to eachother, I wish to encapsulate each stack as it's own widget (making the layout adding business much easier).... | PyQt4 - Custom widget class structure? | During regular intervals of my program, a block (of 3 stacked) widgets need to be added to a horizontal layout. Since the widgets within each block are important to eachother, I wish to encapsulate each stack as it's own widget (making the layout adding business much easier).
I'm having trouble getting PyQt4 to recogni... | [
"When you compile a python module from a ui file with the default options, it will (amongst other things) generate a simple \"setup\" class. In outline, the setup class will look like this:\nclass Ui_ClassCode(object):\n def setupUi(self, ClassCode):\n ClassCode.setObjectName(\"ClassCode\")\n # bun... | [
5,
1
] | [] | [] | [
"custom_widgets",
"pyqt",
"pyqt4",
"python",
"qt_designer"
] | stackoverflow_0008544625_custom_widgets_pyqt_pyqt4_python_qt_designer.txt |
Q:
Python concat string with list
I wanted to build a string from a list.
I used the string.join() command, but if I have :
['hello', 'good', 'morning']
I get : hellogoodmorning
Is there a method that allows me to put a space between every word ? (without the need to write a for loop)
kind regards.
A:
All you need... | Python concat string with list | I wanted to build a string from a list.
I used the string.join() command, but if I have :
['hello', 'good', 'morning']
I get : hellogoodmorning
Is there a method that allows me to put a space between every word ? (without the need to write a for loop)
kind regards.
| [
"All you need to do is add the space in front of join. \n ' '.join(list)\n\n",
">>> ' '.join(['hello', 'good', 'morning'])\n'hello good morning'\n\nThe standard and best way to join a list of strings. I cannot think of anything better than this one.\n",
"This does what you want:\n\" \".join(['hello', 'good', ... | [
85,
24,
6,
4,
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008546245_list_python.txt |
Q:
just curious to know the difference between spring mvc vs django
I would like to ask the masters out there as what are the main differences between java spring mvc and django? and also..which one is preferred most?
A:
From the perspective of developing Web applications, there's only the big difference in the app... | just curious to know the difference between spring mvc vs django | I would like to ask the masters out there as what are the main differences between java spring mvc and django? and also..which one is preferred most?
| [
"From the perspective of developing Web applications, there's only the big difference in the approach towards the architecture of your applications.\nDjango tends to impose a lot of constraints and depends heavily on a fixed set of solutions that are provided internally. What you get from that are conventions and a... | [
32,
11
] | [] | [] | [
"django",
"java",
"model_view_controller",
"python",
"spring_mvc"
] | stackoverflow_0008547226_django_java_model_view_controller_python_spring_mvc.txt |
Q:
boost::python and callback driven execution
I'm having problems on a project that involves a boost::python and callback-driven execution.
My project is using a callback mechanism to run some python code from C++.
As long as the initial function call causing my callback execution is coming from the python interpret... | boost::python and callback driven execution | I'm having problems on a project that involves a boost::python and callback-driven execution.
My project is using a callback mechanism to run some python code from C++.
As long as the initial function call causing my callback execution is coming from the python interpreter, everything is fine. For example:
h = Callback... | [
"I believe you are running afoul of the GIL. My guess is that the callback code is not acquiring the GIL before diving into the Python interpreter.\nIt might also be that all the threads that are going to use the GIL have to register themselves before they can do so. And the thread executing your callback has not r... | [
0
] | [] | [] | [
"boost_python",
"gil",
"multithreading",
"python"
] | stackoverflow_0008545831_boost_python_gil_multithreading_python.txt |
Q:
What can prevent a working (when "opened with" Python) Python application from starting by double-click?
A Python application (having a permission to be executed by the user) doesn't start with double click on it. If I run it (directly, by ./theapp.pyw) in terminal I get ": No such file or directory" error (while ... | What can prevent a working (when "opened with" Python) Python application from starting by double-click? | A Python application (having a permission to be executed by the user) doesn't start with double click on it. If I run it (directly, by ./theapp.pyw) in terminal I get ": No such file or directory" error (while there is no such a string in the application code and the file surely exists (renaming it and using a differen... | [
"pyw files are for windows\nhttp://filext.com/file-extension/PYW\nAnd in windows the shebang line is ignored.\nJust work with the .py script. \nYou can also try creating a bash script that launches your python scripts with the specific flags that you want.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0008548148_python.txt |
Q:
How to bundle files together in a program?
In python i made a file with a lot of different functions, and i imported into another programming(.py) file to use, but then when i tried to make the application using py2app the application couldn't find the function file. How do i make it so that the function file and ... | How to bundle files together in a program? | In python i made a file with a lot of different functions, and i imported into another programming(.py) file to use, but then when i tried to make the application using py2app the application couldn't find the function file. How do i make it so that the function file and the programming file are included in the applica... | [
"You need to make sure you specify an includes for external libs you want to force to be packaged:\nhttp://www.rkblog.rk.edu.pl/w/p/building-mac-os-x-applications-py2app/\nOPTIONS = {'argv_emulation': True, 'includes': ['EXTERNAL LIBRARY'],}\n\n"
] | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0008547973_macos_python.txt |
Q:
Error setting tick positions with matplotlib in python
I'm trying to set tick mark positions in matplotlib. I get errors when running the following minimal example:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
x = 10.*np.random.randn(1000)
y = 10.*np.random.rand... | Error setting tick positions with matplotlib in python | I'm trying to set tick mark positions in matplotlib. I get errors when running the following minimal example:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
x = 10.*np.random.randn(1000)
y = 10.*np.random.randn(1000)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.s... | [
"MultipleLocator is a locator, not a formatter. You want to use\nax.xaxis.set_major_locator(MultipleLocator(1.))\nax.yaxis.set_major_locator(MultipleLocator(1.))\n\nThis works for me (doesn't look too pretty using 1, but it works).\n"
] | [
8
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0008548199_matplotlib_python.txt |
Q:
Quickest/Best way to traverse XML with lxml in Python
I have an XML file that looks like this:
xml = '''<?xml version="1.0"?>
<root>
<item>text</item>
<item2>more text</item2>
<targetroot>
<targetcontainer>
<target>text i want to get</... | Quickest/Best way to traverse XML with lxml in Python | I have an XML file that looks like this:
xml = '''<?xml version="1.0"?>
<root>
<item>text</item>
<item2>more text</item2>
<targetroot>
<targetcontainer>
<target>text i want to get</target>
</targetcontainer>
... | [
"You can use XPath:\nfor x in target.xpath('/root/targetroot/targetcontainer/target'):\n print x.text\n\nWe ask all elements that match a path. In this case, the path is /root/targetroot/targetcontainer/target, which means \n\nall the <target> elements that are inside a <targetcontainer> element, inside a <targe... | [
3
] | [] | [] | [
"lxml",
"python",
"xml_parsing"
] | stackoverflow_0008548531_lxml_python_xml_parsing.txt |
Q:
Custom django comments admin slot
So I am using Djangos builtin comments app (django.contrib.comments) for my blog application. I made several changes to the forms display, etc. (as described in the documentation). One last thing that bothers me is that the Comments model is in it's own category in the admin, like... | Custom django comments admin slot | So I am using Djangos builtin comments app (django.contrib.comments) for my blog application. I made several changes to the forms display, etc. (as described in the documentation). One last thing that bothers me is that the Comments model is in it's own category in the admin, like this:
MyApp
---Model1
---Modle2
C... | [
"You haven't 'overwritten' the Comment class -- by subclassing it, you've actually created a child model using multi table inheritance. This is why another table needs to be created.\nYou could create a proxy model that inherits from the Comment class, then no additional tables need to be created.\nclass MyAppComme... | [
0
] | [] | [] | [
"django",
"django_comments",
"python"
] | stackoverflow_0008545748_django_django_comments_python.txt |
Q:
Working with the Python graphics module: is there any way to save the current window as an image?
I'm working with the python graphics module. What I am trying to do is save the current window as an image. In the module there is an option to save an "image" as an image (image.save()). But that isn't helpful becaus... | Working with the Python graphics module: is there any way to save the current window as an image? | I'm working with the python graphics module. What I am trying to do is save the current window as an image. In the module there is an option to save an "image" as an image (image.save()). But that isn't helpful because it just saves an image you have already loaded. OR if you load a blank image like I did in hopes draw... | [
"The objects you are drawing are based on Tkinter. I don't believe you are actually drawing on the base image, but rather simply creating Tkinter objects by using the \"graphics\" library. I also don't believe you can save a Tkinter to a \"gif\" file, though you can definitely save them in postscript format, then c... | [
2
] | [] | [] | [
"graphics",
"python"
] | stackoverflow_0008530524_graphics_python.txt |
Q:
2D Interpolation of Large Irregular Grid to Regular Grid
I have 2048x2048 mesh of irregular data zi = f(xi, yi) which are essentially three independent sets of 2048 real values. I need to smoothly interpolate (perhaps bicubic spline) that into a regular mesh of wi = f(ui, vi) where ui and vi are integer values fr... | 2D Interpolation of Large Irregular Grid to Regular Grid | I have 2048x2048 mesh of irregular data zi = f(xi, yi) which are essentially three independent sets of 2048 real values. I need to smoothly interpolate (perhaps bicubic spline) that into a regular mesh of wi = f(ui, vi) where ui and vi are integer values from 0 to 2047.
I have tried griddata which seems to work well... | [
"I tried to reproduce your errors without success. Are you on a 32 bit system? I had problems with scipy/numpy and large arrays so switched to 64 bit, and have had no problems since then.\nHere's the code I used to try to reproduce your error (it will generate nothing useful, but should at least experience the sa... | [
2
] | [] | [] | [
"grid",
"interpolation",
"numpy",
"python",
"scipy"
] | stackoverflow_0007068126_grid_interpolation_numpy_python_scipy.txt |
Q:
Instead of using several if statements I want to use a boolean algebra,
I want to use boolean algebra instead of several conditionals, for example
def boo(x,y):
if x==3 and y==1: return 4
if x==3 and y==4: return 1
if x==4 and y==1: return 2
if x==4 and y==2: return 1
if x==5 and y==1: return 3... | Instead of using several if statements I want to use a boolean algebra, | I want to use boolean algebra instead of several conditionals, for example
def boo(x,y):
if x==3 and y==1: return 4
if x==3 and y==4: return 1
if x==4 and y==1: return 2
if x==4 and y==2: return 1
if x==5 and y==1: return 3
what I want to do is
def simple(x,y):
return x#y
and there are total 1... | [
"You can find the right expression that yields the same values as your conditionals, but such code becomes harder to read and maintain.\nA better solution is to use a nested list or dictionary which you can index with input values. This way you turn code into data which is a clear and fast representation of your ma... | [
2,
1,
0
] | [] | [] | [
"algebra",
"boolean",
"conditional",
"if_statement",
"python"
] | stackoverflow_0008548744_algebra_boolean_conditional_if_statement_python.txt |
Q:
Is pyEphem 'sublat' and 'sublong' given in Geocentric or Geodetic?
The documentation says that if pyEpehm is given a TLE and a time it will return the following. However, I'm having no luck converting the returned 'sublat' and 'sublon' to ECEF XYZ and back to LLA coordinates to verify. When I convert back the long... | Is pyEphem 'sublat' and 'sublong' given in Geocentric or Geodetic? | The documentation says that if pyEpehm is given a TLE and a time it will return the following. However, I'm having no luck converting the returned 'sublat' and 'sublon' to ECEF XYZ and back to LLA coordinates to verify. When I convert back the longitude is preserved but the latitude is off by about ~20 degrees for diff... | [
"They're in geocentric coordinates.\n"
] | [
1
] | [] | [] | [
"latitude_longitude",
"pyephem",
"python"
] | stackoverflow_0008548628_latitude_longitude_pyephem_python.txt |
Q:
'command not found' error when using subprocess in apache
I am trying to move my django project from a development server to a production server. I have ironed out almost everything with one (BIG) exception. When I run the following code in the terminal (using python manage.py shell) it works fine, however running... | 'command not found' error when using subprocess in apache | I am trying to move my django project from a development server to a production server. I have ironed out almost everything with one (BIG) exception. When I run the following code in the terminal (using python manage.py shell) it works fine, however running through my apache server (with mod_wsgi) it does not run fine.... | [
"When running under Apache/mod_wsgi you MUST use a full path name to program being run, or any files being access for that matter. This is because your user PATH is not inherited or used by Apache. The current working directory of the process could also be anything, so can't rely on relative paths either.\nSo, inst... | [
4
] | [] | [] | [
"apache",
"django",
"mod_wsgi",
"python",
"subprocess"
] | stackoverflow_0008544953_apache_django_mod_wsgi_python_subprocess.txt |
Q:
How to render image to templates?
Possible Duplicate:
How to load Blobproperty image in Google App Engine?
I am reading an image as a byte string. I am saving it into database.
in models image field is :
image = db.BlobProperty(required=False)
I am rendering it to template using:
context['image_obj'] = image_... | How to render image to templates? |
Possible Duplicate:
How to load Blobproperty image in Google App Engine?
I am reading an image as a byte string. I am saving it into database.
in models image field is :
image = db.BlobProperty(required=False)
I am rendering it to template using:
context['image_obj'] = image_obj (object of the Image models)
in te... | [
"You can use this snippet here as Django doesn't support blob type:\nhttp://djangosnippets.org/snippets/1597/\n"
] | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0008548971_django_google_app_engine_python.txt |
Q:
problem running hello world with tornado web server (Python 2.5,Win 7)
I am using Python 2.5 on Windows 7 (64bit).
I installed pycurl-7.15.5.1 (with win binaries) and tornado (using pip).
When I run the following hello world code:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandl... | problem running hello world with tornado web server (Python 2.5,Win 7) | I am using Python 2.5 on Windows 7 (64bit).
I installed pycurl-7.15.5.1 (with win binaries) and tornado (using pip).
When I run the following hello world code:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello World!")
if __name__=='__... | [
"Tornado has some IPv6 confusion on windows apparently. You can fix it by specifiyig the IP you want it to listen on like this:\napplication.listen(8888,'127.0.0.1')\n\nor maybe\napplication.listen(8888,'0.0.0.0')\n\n",
"from tornado web page (http://www.tornadoweb.org/)\nPlatforms: Tornado should run on any Unix... | [
4,
0
] | [] | [] | [
"ipv6",
"python",
"tornado"
] | stackoverflow_0007503039_ipv6_python_tornado.txt |
Q:
Mocking urllib2.urlopen and lxml.etree.parse using pymox
I'm trying to test some python code that uses urllib2 and lxml.
I've seen several blog posts and stack overflow posts where people want to test exceptions being thrown, with urllib2. I haven't seen examples testing successful calls.
Am I going down the corre... | Mocking urllib2.urlopen and lxml.etree.parse using pymox | I'm trying to test some python code that uses urllib2 and lxml.
I've seen several blog posts and stack overflow posts where people want to test exceptions being thrown, with urllib2. I haven't seen examples testing successful calls.
Am I going down the correct path?
Does anyone have a suggestion for getting this to wor... | [
"I wouldn't delve into urllib2 internals at all. It's beyond the scope of what you care about I think. Here's a simple way to do it with StringIO. The key thing here is that what you intent to parse as XML just needs to be file-like in terms of duck typing, it doesn't need to be an actual addinfourl instance.\ni... | [
4,
2,
0
] | [] | [] | [
"lxml",
"mox",
"python",
"unit_testing",
"urllib2"
] | stackoverflow_0003145519_lxml_mox_python_unit_testing_urllib2.txt |
Q:
using urllib.request to get stock data
I wrote the following code to retrieve data about stocks in the S&P 500. The code works, but it is very slow due to the number of urlopen requests. What strategies can I use to speed this up?
from urllib.request import urlopen
import csv
class StockQuote:
"""gets stock... | using urllib.request to get stock data | I wrote the following code to retrieve data about stocks in the S&P 500. The code works, but it is very slow due to the number of urlopen requests. What strategies can I use to speed this up?
from urllib.request import urlopen
import csv
class StockQuote:
"""gets stock data from Yahoo Finance"""
def __init... | [
"If all of your requests are going to the same domain, I would suggest using urllib3. It's not in the standard python install, but it implements connection pooling so all the individual requests are faster. \n",
"You can request info for multiple stocks with one call to request.urlopen:\nimport urllib.request as ... | [
3,
3,
2
] | [] | [] | [
"multithreading",
"performance",
"python",
"urllib2"
] | stackoverflow_0008548954_multithreading_performance_python_urllib2.txt |
Q:
Error installing selenium python
Getting this error when running pip install -U selenium. Mid way through the script, it gets the following SyntaxError:
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "C:\Python32\Scripts\build\rdflib\setup.py", line 6, in <module>
... | Error installing selenium python | Getting this error when running pip install -U selenium. Mid way through the script, it gets the following SyntaxError:
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "C:\Python32\Scripts\build\rdflib\setup.py", line 6, in <module>
from rdflib import __version__
... | [
"Selenium does not support Python 3. Use Python 2.7 instead.\nSadly, almost all Python software requires Python 2.x.\n[Update]\nSelenium supports Python 3.x now.\n"
] | [
4
] | [] | [] | [
"python",
"python_3.x",
"selenium"
] | stackoverflow_0008549205_python_python_3.x_selenium.txt |
Q:
Is there a way for BaseRequestHandler classes to be stateful?
Short Question
Using my examples below, is there a Pythonic way to share my_object's actual instance with with the BaseRequestHandler class?
Background
By definition, the BaseRequestHandler class creates a new instance for each request. Because of th... | Is there a way for BaseRequestHandler classes to be stateful? | Short Question
Using my examples below, is there a Pythonic way to share my_object's actual instance with with the BaseRequestHandler class?
Background
By definition, the BaseRequestHandler class creates a new instance for each request. Because of this, I am struggling to try find a solution on how to get data from ... | [
"You could pass the object through the server instance: \nself.server = SocketServer.TCPServer((self.host, self.port), ProtocolHandler)\nself.server.my_object = self.my_object\n\nThe documentation indicates that you can have access to the server instance in handle() as self.server.\n"
] | [
8
] | [] | [] | [
"namespaces",
"python",
"sockets",
"socketserver"
] | stackoverflow_0008549177_namespaces_python_sockets_socketserver.txt |
Q:
PyQt4 TextEdit.clear causes crash
I have a deque type list (a queue) which I'd like to show and update in QTextEdit.
There is a function uuenda_kama in class MyForm which should do this (and some other s*** too). First pass of this function when textEdit is empty, it works like a charm, all necessary fields are up... | PyQt4 TextEdit.clear causes crash | I have a deque type list (a queue) which I'd like to show and update in QTextEdit.
There is a function uuenda_kama in class MyForm which should do this (and some other s*** too). First pass of this function when textEdit is empty, it works like a charm, all necessary fields are updated. But on second pass as there has ... | [
"You should not be creating a standard python thread outside of the entire app that runs methods on your qwidgets. Instead you should have a QThread that runs non-gui related logic and then emits a signal when it wants the main thread to affect the GUI\nRefer to this other question for a good example: Howto change ... | [
1
] | [] | [] | [
"crash",
"pyqt4",
"python",
"qtextedit"
] | stackoverflow_0008549231_crash_pyqt4_python_qtextedit.txt |
Q:
Dynamically updated instance class method throws error when called by another class method
I think my example will make this easier to follow:
class x():
def a(self):
return "hello"
def b(self):
return self.a() + " world"
test = x()
print test.b() # prints "hello world" as expected
te... | Dynamically updated instance class method throws error when called by another class method | I think my example will make this easier to follow:
class x():
def a(self):
return "hello"
def b(self):
return self.a() + " world"
test = x()
print test.b() # prints "hello world" as expected
test.a = lambda(self): "hola"
print test.b() # throws error:
# Traceback (m... | [
"You can see the problem if you do \nprint type(test.a) # <type 'function'>\nprint type(test.b) # <type 'instancemethod'>\n\nIf you really want to patch a only on test (not on all instances of x), you can do:\nimport types\ntest.a = types.MethodType((lambda self: \"hola\"), test, x)\n\nTo create an object of type... | [
1,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0008548362_lambda_python.txt |
Q:
Python Berkeley DB/Sqlite
Since BerkeleyDB can use the SQLite api, can python use sqlite module to connect to BerkeleyDB.
This post suggests using something else, but could have been written pre-Api sync.
Best Python module for Berkeley DB?
Can get a simple connection string. If there known problem, PLEASE post.... | Python Berkeley DB/Sqlite | Since BerkeleyDB can use the SQLite api, can python use sqlite module to connect to BerkeleyDB.
This post suggests using something else, but could have been written pre-Api sync.
Best Python module for Berkeley DB?
Can get a simple connection string. If there known problem, PLEASE post. I am exploring this topic.
Usi... | [
"As suggested here https://forums.oracle.com/forums/thread.jspa?threadID=2302793\nI've tried on linux x86_64 with python27, here the steps to make a static version since\nI doubt your distribution has bdb sqlite api.\nDownload db-5.2.36.tar.gz\ntar xzvf db-5.2.36.tar.gz\ncd db-5.2.36/build_unix/\nCFLAGS=\"-fPIC\" .... | [
4,
4,
3
] | [] | [] | [
"berkeley_db",
"python",
"sqlite"
] | stackoverflow_0008418473_berkeley_db_python_sqlite.txt |
Q:
Django is not accepting arguments in Windows
I have installed django on my windows vista computer and can add the django library to a python script, but cannot seem to ge teh following to work correctly from the command line:
django-admin.py startproject mysite
When I try to run this or the help command I always g... | Django is not accepting arguments in Windows | I have installed django on my windows vista computer and can add the django library to a python script, but cannot seem to ge teh following to work correctly from the command line:
django-admin.py startproject mysite
When I try to run this or the help command I always get the default message that shows all the commands... | [
"try\npython django-admin.py startproject mysite\n\nyou may cd to the dir which the django-admin.py in\n",
"The biggest headache I've run into with developing on Windows is path issues. I use virtualenv and David Marble's port of virtualenvwrapper As such, I fully qualify the path to django-admin.py. Of course, t... | [
0,
0,
0,
0
] | [] | [] | [
"django",
"python",
"windows"
] | stackoverflow_0008394141_django_python_windows.txt |
Q:
Why won't LD_PRELOAD work with Python?
Using function interposition for open() with Python doesn't seem to work after the first few calls. I suspect Python is doing some kind of initialization, or something is temporarily bypassing my function.
Here the open call is clearly hooked:
$ cat a
hi
$ LD_PRELOAD=./libint... | Why won't LD_PRELOAD work with Python? | Using function interposition for open() with Python doesn't seem to work after the first few calls. I suspect Python is doing some kind of initialization, or something is temporarily bypassing my function.
Here the open call is clearly hooked:
$ cat a
hi
$ LD_PRELOAD=./libinterpose_python.so cat a
sandbox_init()
open()... | [
"There are open() and open64() functions, you might need to redefine both.\n",
"You should be able to find out what your python process is actually doing by running it under strace (probably without your pre-load).\nMy python3.1 (on AMD64) does appear to use open:\naxa@ares:~$ strace python3.1 -c 'open(\"a\",\"r+... | [
8,
2,
1
] | [] | [] | [
"c",
"function_interposition",
"interposing",
"linux",
"python"
] | stackoverflow_0006421784_c_function_interposition_interposing_linux_python.txt |
Q:
Python: Writing File after modifying contents
I just would like to delete HTML tag and then re-save file in same file..
text files have html tags..
import shutil
import os
import nltk
low_firm=['C:/a1.txt','C:/a2.txt']
for aa in low_firm:
f= open (aa,'r+')
for bb in f:
raw = nltk.clean_html(bb)
... | Python: Writing File after modifying contents | I just would like to delete HTML tag and then re-save file in same file..
text files have html tags..
import shutil
import os
import nltk
low_firm=['C:/a1.txt','C:/a2.txt']
for aa in low_firm:
f= open (aa,'r+')
for bb in f:
raw = nltk.clean_html(bb)
raw2=str(raw)
f.write(low_firm)
but... | [
"I would open a file to read, read all its content as lines in a list, close the file and then reopen it to write on it:\nfor aa in all_firm:\n r = open (aa,'r+')\n lines = r.readlines()\n r.close()\n w = open (aa,'w')\n for bb in lines:\n raw = nltk.clean_html(bb)\n raw2=str(raw)\n ... | [
1,
0
] | [] | [] | [
"nltk",
"python"
] | stackoverflow_0008549918_nltk_python.txt |
Q:
python function returns multiple dicts instead of one
Why does this recursive function keep returning multiple dictionaries instead of just one.
def retFiles(dir):
data = {}
root = set()
os.chdir(dir)
cwd = os.getcwd()
for i in os.listdir(cwd):
if os.path.isfile(i):
data.set... | python function returns multiple dicts instead of one | Why does this recursive function keep returning multiple dictionaries instead of just one.
def retFiles(dir):
data = {}
root = set()
os.chdir(dir)
cwd = os.getcwd()
for i in os.listdir(cwd):
if os.path.isfile(i):
data.setdefault(i, set())
root.add(os.path.relpath(dir)... | [
"There are two problems:\n\nYour function isn't recursive (unless preisci calls retFiles, but you haven't shown that code).\nIt doesn't return anything, let alone multiple dictionaries as you claim.\n\nI wouldn't actually use recursion here. Instead consider using the os.walk function that can recursively walk down... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0008550034_python.txt |
Q:
Need help troubleshooting paramiko issue
I can ssh to a server using pexpect and have no problems logging in and running commands. However, I would like to switch to using paramiko to make the ssh connections so I can take advantage of some of the other paramiko modules. However, when I use paramiko I get the erro... | Need help troubleshooting paramiko issue | I can ssh to a server using pexpect and have no problems logging in and running commands. However, I would like to switch to using paramiko to make the ssh connections so I can take advantage of some of the other paramiko modules. However, when I use paramiko I get the error:
sock.connect((hostname, port))
File "<str... | [
"It would be helpful if you could post a simplified example of the code you're using.\nCheck to make sure that name resolution is happening properly:\nsocket.gethostbyname(hostname)\n\nAlso, I'm not sure why you're using socket directly? Or is that part of the stacktrace and error message you get when you \nYou sho... | [
1
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0008427665_paramiko_python_ssh.txt |
Q:
writing a check program in python for other python files
I am writing a check.py file which reads a file that maps a python file to an output. That file looks something like this
001.py 233168
002.py 4613732
This means 001.py when ran should print out 233168. What is the best way to capture stdout from 00*.py? Ov... | writing a check program in python for other python files | I am writing a check.py file which reads a file that maps a python file to an output. That file looks something like this
001.py 233168
002.py 4613732
This means 001.py when ran should print out 233168. What is the best way to capture stdout from 00*.py? Overriding stdout and using execfile? or using a subprocess?
I h... | [
"A subprocess. That way the script being executed cannot disrupt the calling script too badly.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0008550244_python.txt |
Q:
Formatting text output with Scrapy in Python
I'm trying to scrape pages using a Scrapy spider and then save those pages into a .txt file in a readable form. The code I'm using to do this is:
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSel... | Formatting text output with Scrapy in Python | I'm trying to scrape pages using a Scrapy spider and then save those pages into a .txt file in a readable form. The code I'm using to do this is:
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSelector(response)
title = hxs.select('/html... | [
"My answer in comments for code:\nimport re\nimport codecs\n\n#...\n#...\n#extract() returns list, so you need to take first element\ntitle = hxs.select('/html/head/title/text()').extract() [0]\ncontent = hxs.select('//*[@id=\"content\"]')\n#instead of using BeautifulSoup for this task, you can use folowing\nconten... | [
8
] | [] | [] | [
"python",
"scrapy",
"text",
"web_scraping"
] | stackoverflow_0008549875_python_scrapy_text_web_scraping.txt |
Q:
Mysterious issue with Django + uWSGI + send email
I'm here to write you after about 1.5 hour of hard debugging.
First of all, these are the interested files:
/project/app/utils.py
from django.core.mail import EmailMultiAlternatives
import threading
class EmailThread(threading.Thread):
def __init__(self, subj... | Mysterious issue with Django + uWSGI + send email | I'm here to write you after about 1.5 hour of hard debugging.
First of all, these are the interested files:
/project/app/utils.py
from django.core.mail import EmailMultiAlternatives
import threading
class EmailThread(threading.Thread):
def __init__(self, subject, body, from_email, recipient_list, fail_silently, h... | [
"have you enabled threads in uWSGI with --enable-threads ?\n",
"As the threading having activating issue with uWSGI you can try to add this to your app's uwsgi configuration:\nlazy = true\n\nSo your code will be loaded after child workers forked.\n"
] | [
3,
0
] | [] | [] | [
"amazon_ses",
"django",
"django_email",
"python",
"uwsgi"
] | stackoverflow_0008549371_amazon_ses_django_django_email_python_uwsgi.txt |
Q:
How do setuptools, distribute, and pip relate to one another?
I've been teaching myself Python through the book "Learn Python The Hard Way" (2nd Edition). In exercise 46 it told me to read up on Pip, Distribute, and a few other packages.
The documentation for pip was clear enough. It allows me to install/uninsta... | How do setuptools, distribute, and pip relate to one another? | I've been teaching myself Python through the book "Learn Python The Hard Way" (2nd Edition). In exercise 46 it told me to read up on Pip, Distribute, and a few other packages.
The documentation for pip was clear enough. It allows me to install/uninstall, and upgrade packages. Reading the documentation for distribute... | [
"[2014-10 TL;DR:\ndistribute is dead, use pip, the new setuptools, and, for binary distributions, wheels. More below.]\n\n[Original answer]\nDistribute is was a fork of the older setuptools so nearly all comments that follow apply equally to Distribute and setuptools. Setuptools was an attempt to fill in a number... | [
85
] | [] | [] | [
"distribute",
"pip",
"python",
"setuptools"
] | stackoverflow_0008550062_distribute_pip_python_setuptools.txt |
Q:
Bundle Text file in py2app Application (python)
I recently learned Python (2.7) and have been making some simple board games with AIs and such as practice. I am currently making an intelligent hangman game which necessitates the inclusion of a dictionary file. (I have a text file which has a new word on each lin... | Bundle Text file in py2app Application (python) | I recently learned Python (2.7) and have been making some simple board games with AIs and such as practice. I am currently making an intelligent hangman game which necessitates the inclusion of a dictionary file. (I have a text file which has a new word on each line). I used py2app successfully for other stuff such a... | [
"Specify a resources key in your options that contains a list of resources to include. This will be the current directory when your app runs\noptions = { \"resources\": [\"myfile.txt\"] }\nhttp://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html#option-reference\nIf you use the resources flag with py2applet it w... | [
2,
1,
0
] | [] | [] | [
"osx_snow_leopard",
"py2app",
"python"
] | stackoverflow_0008550374_osx_snow_leopard_py2app_python.txt |
Q:
Python urllib2 Tor 514 Authentication Required
I am trying to use Tor with python and urllib2 and am stuck. The following
print opener.open('http://check.torproject.org/').read()
And
telnet 127.0.0.1 9051
gives me the following error:
514 Authentication Required.
Here is the code I want to use: But I receive th... | Python urllib2 Tor 514 Authentication Required | I am trying to use Tor with python and urllib2 and am stuck. The following
print opener.open('http://check.torproject.org/').read()
And
telnet 127.0.0.1 9051
gives me the following error:
514 Authentication Required.
Here is the code I want to use: But I receive the same 514 Authentication Error on the urllib2.urlop... | [
"Google search suggests (and Tor manual confirms) that 9051 is Tor's default control port. Actual proxy is running on port 9050 by default, which is the one you need to use. However, Vidalia does not use the default ports without extra configuration.\nThe other problem is that urllib2 is by default unable to work w... | [
1
] | [] | [] | [
"python",
"tor",
"urllib2"
] | stackoverflow_0008550249_python_tor_urllib2.txt |
Q:
HttpResponseRedirect question
Cant we send a dictionary variable when using HttpResponseRedirect
render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpRe... | HttpResponseRedirect question | Cant we send a dictionary variable when using HttpResponseRedirect
render_to_response('edited/display.html',context_instance=RequestContext(request,{'newlist': newlist}))
//How can the dictionary and the request sent back again
//sumthing like this
return HttpResponseRedirect('edited/display.html... | [
"Response redirect as name suggests, redirects the user's browser to new URL, so it doesn't make any sense to pass anything else except the new location in HttpResponseRedirect\nIf you want to pass some data, so that in the view of new location url you can check for that data, pass it as url arguments e.g.\nreturn ... | [
4,
2,
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0002577306_django_django_views_python.txt |
Q:
String matches in python
There are four files, a.txt, b.txt, c.txt, d.txt.
Each file has only one column of data that consists of names of shops/malls/restaurants etc. Essentially they are just names.
I need a program that can match the names in a.txt to names in each of the other three files (b.txt, c.txt, d.txt)... | String matches in python | There are four files, a.txt, b.txt, c.txt, d.txt.
Each file has only one column of data that consists of names of shops/malls/restaurants etc. Essentially they are just names.
I need a program that can match the names in a.txt to names in each of the other three files (b.txt, c.txt, d.txt). By match, we mean the progra... | [
"import contextlib\n\nwith contextlib.nested(open('b.txt', 'r'), open('c.txt', 'r'), open('d.txt', 'r')) as (b_fp, c_fp, d_fp):\n data = set(b_fp.readlines() +\n c_fp.readlines() +\n d_fp.readlines())\n\nwith open('a.txt', 'r') as fp:\n for line in fp:\n if line in data:\n ... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0008550511_python.txt |
Q:
How to execute a method after a response is complete in Pyramid?
Using Pyramid with Akhet, how do I execute a method after a response has been returned to the client? I believe this was done with the __after__ method in Pylons. I'm trying to execute a DB query and don't want it to block the request response.
A:... | How to execute a method after a response is complete in Pyramid? | Using Pyramid with Akhet, how do I execute a method after a response has been returned to the client? I believe this was done with the __after__ method in Pylons. I'm trying to execute a DB query and don't want it to block the request response.
| [
"You can use a response callback for your case.\nEDITED after Michael Merickel's comment: The response callback blocks the request to which is added, but you shouldn't worry about that callback blocking other requests since each request runs in a different thread. If you still need not to block the request with the... | [
1
] | [] | [] | [
"akhet",
"pyramid",
"python"
] | stackoverflow_0008549869_akhet_pyramid_python.txt |
Q:
Dictionary of dictionaries in Python?
From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4).
I need to write a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{f... | Dictionary of dictionaries in Python? | From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4).
I need to write a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}...}
The f... | [
"If it is only to add a new tuple and you are sure that there are no collisions in the inner dictionary, you can do this:\ndef addNameToDictionary(d, tup):\n if tup[0] not in d:\n d[tup[0]] = {}\n d[tup[0]][tup[1]] = [tup[2]]\n\n",
"Using collections.defaultdict is a big time-saver when you're buildi... | [
16,
12,
8
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008550912_dictionary_python.txt |
Q:
sklearn (scikit-learn) logistic regression package -- set trained coefficients for classification.
So I read the scikit-learn package webpate:
http://scikit-learn.sourceforge.net/dev/modules/generated/sklearn.linear_model.LogisticRegression.html
I can use logistic regression to fit the data, and after I obtain a... | sklearn (scikit-learn) logistic regression package -- set trained coefficients for classification. | So I read the scikit-learn package webpate:
http://scikit-learn.sourceforge.net/dev/modules/generated/sklearn.linear_model.LogisticRegression.html
I can use logistic regression to fit the data, and after I obtain an instance of LogisticRegression, I can use it to classify new data points. So far so good.
Is there a w... | [
"The coefficients are attributes of the estimator object--that you created when you instantiated the Logistic Regression class--so you can access them in the normal python way:\n>>> import numpy as NP\n>>> from sklearn import datasets\n>>> from sklearn import datasets as DS\n>>> digits = DS.load_digits()\n>>> D = d... | [
7,
5
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"scikits"
] | stackoverflow_0008539141_machine_learning_python_scikit_learn_scikits.txt |
Q:
Python desktopcouch storing dict
First of all, one strange behavior of desktopcouch.records.server.CouchDatabase:
db.get_record(id) returns:
<desktopcouch.records.RecordDict object at 0x9198f2c>
db.get_records('mytype', True) returns array of:
<Row id='5rMlni6ZYudp5gvSADve1Y', key='mytype', ...>
Where db is Couc... | Python desktopcouch storing dict | First of all, one strange behavior of desktopcouch.records.server.CouchDatabase:
db.get_record(id) returns:
<desktopcouch.records.RecordDict object at 0x9198f2c>
db.get_records('mytype', True) returns array of:
<Row id='5rMlni6ZYudp5gvSADve1Y', key='mytype', ...>
Where db is CouchDatabase('mydb', create=True)
Why thi... | [
"By looking into its code, I find that it's not a normal dict, but you can get it to be dict anyway.\nTry this:\nprint dict(tmp['logs'].items())\n\nEDIT:\nAs for the confusion, when you set the converted dict back to a Record object, it runs\nsuper(Record, self).__setitem__(key, item)\n\nSo according to its inherit... | [
1
] | [] | [] | [
"couchdb",
"dictionary",
"nosql",
"python",
"record"
] | stackoverflow_0008548998_couchdb_dictionary_nosql_python_record.txt |
Q:
How exactly do hex color codes work? / How to implement something like a heat map
I am working on a simple program to just draw circles around some fixed points using the Python turtle package; however, I wanted to make it somewhat like a heat map where the colors get "cooler" as they get farther from the original... | How exactly do hex color codes work? / How to implement something like a heat map | I am working on a simple program to just draw circles around some fixed points using the Python turtle package; however, I wanted to make it somewhat like a heat map where the colors get "cooler" as they get farther from the original point. My idea was to take the base white color, #FFFFFF, and subtract a percentage ba... | [
"You want to use HSV instead of RGB for the colors; slide across the hue dimension for your distances. colorsys can help.\n",
"The trick is to work on the three bytes individually. I'll give a shot at re-writing your function the way I think it ought to work:\ndef findColor(dist):\n base = 0xFFFFFF\n percen... | [
4,
1,
1
] | [] | [] | [
"colors",
"python",
"turtle_graphics"
] | stackoverflow_0008550436_colors_python_turtle_graphics.txt |
Q:
Index based string matches in python
I have two lists
list1 = ['this', 'is', 'the', 'right', 'string']
list2 = ['this', 'is', 'right']
After comparison I need to find out another list include only
list3 = ['this', 'is']
I have tried it up using intersection, I know it is not the proper solution in my case.
>>> l... | Index based string matches in python | I have two lists
list1 = ['this', 'is', 'the', 'right', 'string']
list2 = ['this', 'is', 'right']
After comparison I need to find out another list include only
list3 = ['this', 'is']
I have tried it up using intersection, I know it is not the proper solution in my case.
>>> list(set(list1) & set(list2))
['this', 'is'... | [
"[x for (x, y) in zip(list1, list2) if x == y]\n\n",
"If you like noob-style then try this. Easy to understand. That other answer is very much like functional programming, which can be confusing.\nlist3 = list()\nfor x in range(min(len(list1),len(list2)):\n if list1[x] == list2[x]:\n list3.append(list1[... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008550303_python.txt |
Q:
How should I prevent abuse when using web.py's web.database?
I'm writing a quick web.py app and take data from web.input...
import web
urls = (
'/', 'something',
)
app = web.application(urls, globals())
db = web.database(dbn='postgres', db='database', user='username', password='password', host='127.0.0.1')
cla... | How should I prevent abuse when using web.py's web.database? | I'm writing a quick web.py app and take data from web.input...
import web
urls = (
'/', 'something',
)
app = web.application(urls, globals())
db = web.database(dbn='postgres', db='database', user='username', password='password', host='127.0.0.1')
class something:
def GET(self):
i = web.input()
r... | [
"http://webpy.org/cookbook/query says:\n\nTo prevent SQL injection attacks, db.query also accepts the \"vars\"\n syntax as described in db.select:\nresults = db.query(\"SELECT * FROM users WHERE id=$id\", vars={'id':10})\n\nThis will escape user input, if you're trusting them for the \"id\"\n variable.\n\nSo I gu... | [
6,
4
] | [
"Yes because some one can alter the variable especially if it comes from a url to say something like \"selecte * from table where id = [ variable + DELETE TABLE[. This is an example of sql injection. This is especially critical if the user has any idea of what your back end data objects are named.\nI'm not exactly ... | [
-1
] | [
"psycopg2",
"python",
"python_2.4",
"sql_injection",
"web.py"
] | stackoverflow_0008447920_psycopg2_python_python_2.4_sql_injection_web.py.txt |
Q:
What is the correct import statement to use for a Select object in webdriver 2.4 under python?
I am writing tests with selenium webdriver 2.4 on python 2.7.
The documentation (http://seleniumhq.org/docs/03_webdriver.html) demonstrates the ability to manipulate select form elements as follows:
Select select = new S... | What is the correct import statement to use for a Select object in webdriver 2.4 under python? | I am writing tests with selenium webdriver 2.4 on python 2.7.
The documentation (http://seleniumhq.org/docs/03_webdriver.html) demonstrates the ability to manipulate select form elements as follows:
Select select = new Select(driver.findElement(By.xpath("//select")));
select.deselectAll();
select.selectByVisibleText("E... | [
"\nHowever I cannot figure out what to import to successfully instantiate the Select object.\n\nIt is available as:\nfrom selenium.webdriver.support.ui import Select\nSee also: http://selenium.googlecode.com/svn/trunk/docs/api/py/webdriver_support/selenium.webdriver.support.select.html#module-selenium.webdriver.sup... | [
1,
0
] | [] | [] | [
"python",
"selenium",
"testing",
"webdriver"
] | stackoverflow_0007601270_python_selenium_testing_webdriver.txt |
Q:
Passing a Django Form Class variable to the nested class Meta, how?
G'day there. I've currently got a bit of an annoyance more than anything. The code below works fully, as expected. Basically it's a ModelForm that dynamically bases it's model on a string received in the url, or based on the class of an instance i... | Passing a Django Form Class variable to the nested class Meta, how? | G'day there. I've currently got a bit of an annoyance more than anything. The code below works fully, as expected. Basically it's a ModelForm that dynamically bases it's model on a string received in the url, or based on the class of an instance if that's provided.
My question is whether it's possible to abstract this ... | [
"The answer was pretty obvious when I thought about it. A function returning a class works fine. This is what's left at the start of views.py. I'm thinking this is likely the best way to do this, or at least the most concise.\n@user_passes_test(lambda u: u.is_staff, login_url=\"%slogin/\" % NINJA_ADMIN_URL_PREFIX)\... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0008549582_django_django_forms_python.txt |
Q:
Default Values for Models in Google App Engine
Is it possible to set default values for models ? For example consider this model from Appengine Documentation
from google.appengine.ext import db
class Pet(db.Model):
name = db.StringProperty(required=True)
type = db.StringProperty(required=True, choices=set... | Default Values for Models in Google App Engine | Is it possible to set default values for models ? For example consider this model from Appengine Documentation
from google.appengine.ext import db
class Pet(db.Model):
name = db.StringProperty(required=True)
type = db.StringProperty(required=True, choices=set(["cat", "dog", "bird"]))
birthdate = db.DatePro... | [
"Use the default attribute, e.g.\nclass Pet(db.Model):\n name = db.StringProperty(required=True, default=\"(unnamed)\") \n\n"
] | [
9
] | [] | [] | [
"default_value",
"google_app_engine",
"model",
"python"
] | stackoverflow_0008551602_default_value_google_app_engine_model_python.txt |
Q:
need a dictionary from another function
If I have a dictionary from another function, how can I pass the dictionary within a new function?
Eg.
From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I have a function that make a dictionary like this... | need a dictionary from another function | If I have a dictionary from another function, how can I pass the dictionary within a new function?
Eg.
From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I have a function that make a dictionary like this:
D={realName:{falseName:[positionOfMistake],... | [
"def your_new_function(d, falseNames):\n # ... get data from d\n return {realname:(falseName1, falseName2)}\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0008551595_dictionary_python.txt |
Q:
How to use High Replication Datastore
Okay, I have watched the video and read the articles in the App Engine documentation (including Using the High Replication Datastore). However I am still completely confused on the practical usage of it. I understand the benefits (from the video) and they sound great. But what... | How to use High Replication Datastore | Okay, I have watched the video and read the articles in the App Engine documentation (including Using the High Replication Datastore). However I am still completely confused on the practical usage of it. I understand the benefits (from the video) and they sound great. But what I am lacking is a few practical examples. ... | [
"I'm not sure why you think you need to change your queries at all. The documentation that you link to clearly states:\n\nThe back end changes, but the datastore API does not change at all. You'll use the same programming interfaces no matter which datastore you're using.\n\nThe point of that page is just to say th... | [
3,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0008551605_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python value/reference/I don't even know
I've tried to implement the diamond-square algorithm in python, but I seem to be bogged down in the workings of the language... I have a 'quad' class that has 9 2D (custom) points inside it:
top left
top right
top middle
bottom left
bottom right
bottom middle
left middle
c... | Python value/reference/I don't even know | I've tried to implement the diamond-square algorithm in python, but I seem to be bogged down in the workings of the language... I have a 'quad' class that has 9 2D (custom) points inside it:
top left
top right
top middle
bottom left
bottom right
bottom middle
left middle
centre
right middle
These 9 are held in a dict... | [
"I'm not a Python expert, but I believe you need to define the Points and Children variables inside the init method if you want them to be instance variables. As it stands now, I think all instances would share the same dictionaries.\nSee http://legacy.python.org/doc/essays/ppt/acm-ws/sld051.htm\nAnother example: ... | [
3,
0
] | [] | [] | [
"2d",
"algorithm",
"python"
] | stackoverflow_0008550390_2d_algorithm_python.txt |
Q:
Compare List Similarity Python
S = ['hom']
L = ['home','honda','Hammer','Elephant']
I want to get output to show similarity
hom = home
and
print home
How I can do this? I want to use approximate matching to change "hom" to "home".
A:
For something built-in, you have difflib.
It can (as said in the docs): Re... | Compare List Similarity Python | S = ['hom']
L = ['home','honda','Hammer','Elephant']
I want to get output to show similarity
hom = home
and
print home
How I can do this? I want to use approximate matching to change "hom" to "home".
| [
"For something built-in, you have difflib.\nIt can (as said in the docs): Return a list of the best “good enough” matches. word is a sequence for which close matches are desired (typically a string), and possibilities is a list of sequences against which to match word (typically a list of strings).\nThe example in ... | [
4
] | [] | [] | [
"approximate",
"python"
] | stackoverflow_0008551840_approximate_python.txt |
Q:
python function returns more dicts
Why is this recursive function returning more than 1 dictionary aka printing them each time it cycles why isn't it adding new findings to the existing dictionary.
And no i dont want to use os.walk and yes i am aware theres no return
def retFiles(dir):
data = {}
root = set... | python function returns more dicts | Why is this recursive function returning more than 1 dictionary aka printing them each time it cycles why isn't it adding new findings to the existing dictionary.
And no i dont want to use os.walk and yes i am aware theres no return
def retFiles(dir):
data = {}
root = set()
os.chdir(dir)
cwd = os.getcwd... | [
"You're creating a new dictionary with each call to retfiles() when you set data = {}. Therefore it can't append to the data dictionary in the caller's scope.\n",
"Your solution has several problems:\n1) The recursive call changes the directory during the loop: Remaining files/directories will not be found any mo... | [
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0008551562_python.txt |
Q:
Splitting texts python
thanks for answering my questions, I just want to clarify what I was asking.
I'm trying to split the following string using str.split('+'), I'm reading in the strings from a text file:
['\A'+'ABBOTT\s|\s'+'ABBOTT\s|\s'+'ABBOTT$|\A'+'ABBOTT LABORATORIES\s|\s'+'ABBOTT LABORATORIES\s|\s'+'ABBO... | Splitting texts python | thanks for answering my questions, I just want to clarify what I was asking.
I'm trying to split the following string using str.split('+'), I'm reading in the strings from a text file:
['\A'+'ABBOTT\s|\s'+'ABBOTT\s|\s'+'ABBOTT$|\A'+'ABBOTT LABORATORIES\s|\s'+'ABBOTT LABORATORIES\s|\s'+'ABBOTT LABORATORIES$']
the desi... | [
"If you print the array directly it will look as if the value of the first entry is ['\\\\A', this is also how the value should be written when dealing with it in your script.\nThat is because print in that context will wrap the string inside \"\" and escape characters such as \\ inside (turning them into \\\\ in t... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0008551856_python.txt |
Q:
python recursive directory reading
I wish to avoid os.walk, i am using a recursive function to read files and folders and store files to a dictionary
I got rid of the os.chdir but for some reason function is now joining path + file as well and its generating an error :
WindowsError: [Error 267] The directory name ... | python recursive directory reading | I wish to avoid os.walk, i am using a recursive function to read files and folders and store files to a dictionary
I got rid of the os.chdir but for some reason function is now joining path + file as well and its generating an error :
WindowsError: [Error 267] The directory name is invalid: 'c:\data\foo\notes\*.*'
Its ... | [
"This seems to work for me\nimport os\n\nop = os.path\n\ndef fileRead(mydir):\n data = {}\n root = set()\n for i in os.listdir(mydir):\n path = op.join(mydir, i)\n print(path)\n if op.isfile(path):\n data.setdefault(i, set())\n root.add(op.relpath(mydir).replace(\... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0008552131_python.txt |
Q:
Accessing a variable's name
I'm trying to access a variable's name. For example, if I call a function to print a list (printL)
and want to print my list's name "A_minus_B":
def printL (xlist):
print "****************************"
print "name of list"
print (" entries : "),len(xlist)
print xlist
... | Accessing a variable's name | I'm trying to access a variable's name. For example, if I call a function to print a list (printL)
and want to print my list's name "A_minus_B":
def printL (xlist):
print "****************************"
print "name of list"
print (" entries : "),len(xlist)
print xlist
print "*********************... | [
"You can't.* The detailed reasons are discussed in the Python language reference, but basically what Python does when you call printL(A_minus_B) is take the value that has been labeled A_minus_B and create a new label, xlist, that happens to refer to the same thing. From that point on, the label xlist has absolutel... | [
1,
0
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0008547635_python_variables.txt |
Q:
Any Python ORM make full use of NoSQL's schema-less feature?
I tried Django-nonrel(which is a NoSQL fork of Django project) with MongoDB. In it's ORM, class can only inherit from abstract class, so even two class are inherit from the same base class, they are saved into different collections in MongoDB.
This desig... | Any Python ORM make full use of NoSQL's schema-less feature? | I tried Django-nonrel(which is a NoSQL fork of Django project) with MongoDB. In it's ORM, class can only inherit from abstract class, so even two class are inherit from the same base class, they are saved into different collections in MongoDB.
This design added a pre-defined schema to the schema-less database, every co... | [
"The goal of Django-nonrel is to maintain the same behaviors as Django's ORM has, but to allow use of non-relational storage backends. Since Django doesn't permit multiple different models to be stored in the same (relational) table, I'm not surprised to learn that Django-nonrel doesn't either.\nIf you want the beh... | [
4
] | [] | [] | [
"mongodb",
"nosql",
"orm",
"python"
] | stackoverflow_0008552262_mongodb_nosql_orm_python.txt |
Q:
how to replace all the occurrence in a string with a different number
I have never used python in my life. I need to make a little fix to a given code.
I need to replace this
new_q = q[:q.index('?')] + str(random.randint(1,rand_max)) + q[q.index('?')+1:]
with something that replace all of the occurrence of ? wi... | how to replace all the occurrence in a string with a different number | I have never used python in my life. I need to make a little fix to a given code.
I need to replace this
new_q = q[:q.index('?')] + str(random.randint(1,rand_max)) + q[q.index('?')+1:]
with something that replace all of the occurrence of ? with a random, different number.
how can I do that?
| [
"import re\nimport random\na = 'abc?def?ghi?jkl'\nrand_max = 9\n\nre.sub(r'\\?', lambda x:str(random.randint(1,rand_max)), a)\n\n# returns 'abc3def4ghi6jkl'\n\nor without regexp:\nimport random\na = 'abc?def?ghi?jkl'\nrand_max = 9\nwhile '?' in a:\n a = a[:a.index('?')] + str(random.randint(1,rand_max)) + a[a.in... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0008552556_python.txt |
Q:
Ruby mechanize script in python
I've got this ruby script:
require 'mechanize'
agent = Mechanize.new
page = agent.get "http://www.speech.sri.com/projects/srilm/download.html"
form = page.forms.last
form.field_with(name: "name").value = "Hans Meier"
form.field_with(name: "org").value = "Meier AG"
form.field_with(na... | Ruby mechanize script in python | I've got this ruby script:
require 'mechanize'
agent = Mechanize.new
page = agent.get "http://www.speech.sri.com/projects/srilm/download.html"
form = page.forms.last
form.field_with(name: "name").value = "Hans Meier"
form.field_with(name: "org").value = "Meier AG"
form.field_with(name: "email").value = "hans.meier.org"... | [
"import mechanize\nbr = mechanize.Browser()\nbr.open(\"http://www.speech.sri.com/projects/srilm/download.html\")\nbr.select_form(nr = True)\nbr['name'] = 'Hans Meier'\nbr['org'] = 'Meier AG'\nbr['email'] = 'hans.meier.org'\nbr['address'] = 'Baslerstrasse 32'\nbr['file'] = ['/project/srilm/srilm-1.6.0.tar.gz']\nform... | [
1
] | [] | [] | [
"mechanize",
"python",
"ruby"
] | stackoverflow_0008552366_mechanize_python_ruby.txt |
Q:
How to know if browser has AJAX (Django)
In my Django application I would like to know if the browser the client is using has AJAX or not. This is because I have, for example, profile editing. I have a version that edits the user's profile in-place and another one that redirects you to an edit page.
I know that mo... | How to know if browser has AJAX (Django) | In my Django application I would like to know if the browser the client is using has AJAX or not. This is because I have, for example, profile editing. I have a version that edits the user's profile in-place and another one that redirects you to an edit page.
I know that most browsers have AJAX nowadays, but just to ma... | [
"User agent sniffing and the like is not seen as the best solution... if you can afford that, rather use projects like hasjs on client side to check what the user's browser really is capable and send the information to the server somehow (like, serving the checking page when there is no session, let it do the check... | [
1,
1,
0,
0
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0008468427_ajax_django_python.txt |
Q:
how do i send an email in python?
i've looked online but every time i try to connect to the localhost it says connection refused. Do i need to sign into a valid email address to send email?
Here is my EXACT code.
>>> import smtplib
>>> sender = 'from@fromdomain.com'
#this is my exact sender name bc i don't know ... | how do i send an email in python? | i've looked online but every time i try to connect to the localhost it says connection refused. Do i need to sign into a valid email address to send email?
Here is my EXACT code.
>>> import smtplib
>>> sender = 'from@fromdomain.com'
#this is my exact sender name bc i don't know if i need to use a valid email address ... | [
"Do you have a smtp server running in your computer? Localhost refers to your own computer.\n",
"If you want to use gmail to send your message there is some code at: http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/ that you can use. It should be pretty self explaining..\n"
] | [
2,
2
] | [] | [] | [
"email",
"python"
] | stackoverflow_0008552826_email_python.txt |
Q:
For every string get unique combination of 3 chars (together)
If I have string like "combination.py", I want to get the following result using Python:
["com" , "omb", "mbi", "bin", "ina", "nat" , "ati" , "tio", "ion", "on.", "n.p" , ".py"]
I have something that is working quite good, but it's a really long code, ... | For every string get unique combination of 3 chars (together) | If I have string like "combination.py", I want to get the following result using Python:
["com" , "omb", "mbi", "bin", "ina", "nat" , "ati" , "tio", "ion", "on.", "n.p" , ".py"]
I have something that is working quite good, but it's a really long code, so I'm looking for something short and beautiful. :)
Thanks
| [
">>> s = \"combination.py\" \n>>> [s[i:i+3] for i in range(len(s)-2)]\n['com', 'omb', 'mbi', 'bin', 'ina', 'nat', 'ati', 'tio', 'ion', 'on.', 'n.p', '.py']\n\nIt is indeed a good habit to look for something \"short and beautiful\". Python is quite apt at this. :)\n",
"The function\ndef substrings(s, l=3):\n re... | [
10,
3,
1
] | [
" String txt = \"combination.py\";\nfor(int i=0;i<txt.length;i++){\n String result = txt.substring(i,i+2)\n System.out.println(result);\n i+=3;\n}\n\n"
] | [
-3
] | [
"python"
] | stackoverflow_0008552808_python.txt |
Q:
Global variable/Variable caching in Django
In my website, I want to present to the user the most viewed product categories in a sidebar, in multiple pages.
so in each different view I have:
variables = RequestContext(request, {
(...)
'most_viewed_cats': calculate_most_viewed_categories()
}
and in the variou... | Global variable/Variable caching in Django | In my website, I want to present to the user the most viewed product categories in a sidebar, in multiple pages.
so in each different view I have:
variables = RequestContext(request, {
(...)
'most_viewed_cats': calculate_most_viewed_categories()
}
and in the various templates
{% include "list_most_viewed_categor... | [
"If it's something you'd like to reuse across the whole site, you would probably do best to create a context processor that's going to always populate the template context with the variable containing the most viewed categories\nfrom django.core.cache import get_cache\n\nCACHE_KEY_MOST_VIEWED_CATEGORIES = 'most_vie... | [
5
] | [] | [] | [
"caching",
"django",
"django_cache",
"django_caching",
"python"
] | stackoverflow_0008430985_caching_django_django_cache_django_caching_python.txt |
Q:
django-template: HTML link tag contains entire html content of base page
index.html
<html>
<head>
<link href="static/style.css" rel="stylesheet" type="text/css" />
<title>I want to</title>
</head>
<body>
{% block header %}
<div id="header-wrap"></div>
{% endblock... | django-template: HTML link tag contains entire html content of base page | index.html
<html>
<head>
<link href="static/style.css" rel="stylesheet" type="text/css" />
<title>I want to</title>
</head>
<body>
{% block header %}
<div id="header-wrap"></div>
{% endblock %}
<div id="container">
{% block error %} {% endblock %}
... | [
"Just fixed it :\n- path to stylesheet on pages was relative(static/style.css) and NOT absolute(*/*static/style.css). Making absolute path makes it work\n<head>\n<link type=\"text/css\" rel=\"stylesheet\" href=\"/static/style.css\">\n<html>\n\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"html",
"python"
] | stackoverflow_0008552734_django_django_templates_html_python.txt |
Q:
What is the right way to create a list from variable and another list?
This is the only way i can think of looks like this:
var = 1
list = [2, 3, 4]
newList = [var,] + list
Is it the right way?
Update: I need to make a new list so insert would not help
A:
Your method is fine (other than the extra comma not need... | What is the right way to create a list from variable and another list? | This is the only way i can think of looks like this:
var = 1
list = [2, 3, 4]
newList = [var,] + list
Is it the right way?
Update: I need to make a new list so insert would not help
| [
"Your method is fine (other than the extra comma not needed for a 1-list); people have done it this way for a long time.\n",
"I am not sure what you want to imply by using the , after var but generally you won;t need it. As you were trying to get other options here is another way to do\nlst.insert(0,var)\n\nIf yo... | [
4,
2,
2,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0008553037_list_python.txt |
Q:
Python getopt() in __main__
I'm a Python beginner and have successfully gotten my first program with CLI parameters passed in to run. Got lots of help from this Handling command line options.
My question is: Why in Example 5.45 a separate def main(argv) has been used, instead of calling the try/except block withi... | Python getopt() in __main__ | I'm a Python beginner and have successfully gotten my first program with CLI parameters passed in to run. Got lots of help from this Handling command line options.
My question is: Why in Example 5.45 a separate def main(argv) has been used, instead of calling the try/except block within __main__ itself.
Example 5.45
... | [
"There is no strict technical reason, but it is quite idiomatic to keep the code outside functions as short as possible. Specifically, putting the code into the module scope would turn the variables grammar, opts and args into global public variables, even though they are only required inside the main code. Further... | [
2,
1
] | [] | [] | [
"getopt",
"python"
] | stackoverflow_0008550570_getopt_python.txt |
Q:
How to join/merge two generators output using python
I have two generators g1 and g2
for line in g1:
print line[0]
[a, a, a]
[b, b, b]
[c, c, c]
for line1 in g2:
print line1[0]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
for line in itertools.chain(g1, g2):
print line[0]
[a, a, a]
[b, b, b]
[c, c, c]
[1, 1, 1]
[2... | How to join/merge two generators output using python | I have two generators g1 and g2
for line in g1:
print line[0]
[a, a, a]
[b, b, b]
[c, c, c]
for line1 in g2:
print line1[0]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
for line in itertools.chain(g1, g2):
print line[0]
[a, a, a]
[b, b, b]
[c, c, c]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
How
do I get the output like:
[a, a, a... | [
"first case: use \nfor x, y in zip(g1, g2):\n print(x[0], y[0])\n\nsecond case: use \nfor x, y in zip(g1, g2):\n print(x[0] + y[0])\n\nYou can of course use itertools.izip for the generator version. You get the generator automatically if you use zip in Python 3 and greater.\n",
"You can use itertools.izip f... | [
18,
4,
3,
3
] | [] | [] | [
"generator",
"python",
"python_itertools"
] | stackoverflow_0008553349_generator_python_python_itertools.txt |
Q:
Error while running pycassa setup on Win 7
Im trying to use Pycassa-1.3.0 with DJango and cassandra-1.0.5, Cassandra is working but running Pycassa Setup (python setup.py) gives me error 404,
here are the traces:
Downloading http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c9-py
2.7.egg
Traceback (mo... | Error while running pycassa setup on Win 7 | Im trying to use Pycassa-1.3.0 with DJango and cassandra-1.0.5, Cassandra is working but running Pycassa Setup (python setup.py) gives me error 404,
here are the traces:
Downloading http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c9-py
2.7.egg
Traceback (most recent call last):
File "setup.py", line 16... | [
"It looks like you don't have setuptools installed, and so it's trying to install setuptools for you, but the default version it looks for is a little old, and so the link no longer works.\nI'll update pycassa to fix the problem, but in the meantime you have a couple of options:\n\nInstall setuptools manually\nChan... | [
0
] | [] | [] | [
"cassandra",
"django",
"django_models",
"pycassa",
"python"
] | stackoverflow_0008551326_cassandra_django_django_models_pycassa_python.txt |
Q:
Histogram matplotlib from arrays
I have two arrays:
For example:
a=[1, 2, 3, 4]
b=[10, 20, 30, 40]
And from those number I need to plot histogram, I known that is easy to plot curve with coordinates likes this (1,10), (2, 20) and etc. But how to plot histogram from arrays. Currently I am stuck with option to dr... | Histogram matplotlib from arrays | I have two arrays:
For example:
a=[1, 2, 3, 4]
b=[10, 20, 30, 40]
And from those number I need to plot histogram, I known that is easy to plot curve with coordinates likes this (1,10), (2, 20) and etc. But how to plot histogram from arrays. Currently I am stuck with option to draw histogram. Any suggestion would be ... | [
"You can make a histogram in matplotlib using matplotlib.pyplot.hist. Given the code in the question, where you want the values in a to be the frequencies for values in 2400 through 2500, this could be as simple as doing:\nplt.hist(range(2400, 2501), weights=a[0][0])\nplt.show()\n\nDoing that generates a histogram ... | [
4
] | [] | [] | [
"arrays",
"matplotlib",
"python"
] | stackoverflow_0008553573_arrays_matplotlib_python.txt |
Q:
How can i incorporate a load / save function into my game written in python
How can I incorporate saving and loading to a file in my game written in python 2.7.
The source code is available https://github.com/bob53124/Charlies-Adventure/blob/master/game.py here to view. If you have any idea please reply. BTW im wr... | How can i incorporate a load / save function into my game written in python | How can I incorporate saving and loading to a file in my game written in python 2.7.
The source code is available https://github.com/bob53124/Charlies-Adventure/blob/master/game.py here to view. If you have any idea please reply. BTW im writing it on a linux box
| [
"You can serialize an object to the disk using the Pickle library.\nhttp://docs.python.org/library/pickle.html\nWhen you restore the object you will get an exact replica in memory. \nSo you can just pickle up all your game state objects to save. To load just unpickle them in the appropriate places.\n",
"Just to g... | [
5,
2
] | [] | [] | [
"linux",
"python",
"python_2.7",
"python_2.x"
] | stackoverflow_0008553382_linux_python_python_2.7_python_2.x.txt |
Q:
Using exponentiation **0.5 less efficient than math.sqrt?
A quote from "Python Programming: An Introduction to Computer Science"
We could have taken the square root
using exponentiation **. Using
math.sqrt is somewhat more efficient.
"Somewhat", but to what extent, and how?
A:
Theoretically, hammar's answe... | Using exponentiation **0.5 less efficient than math.sqrt? | A quote from "Python Programming: An Introduction to Computer Science"
We could have taken the square root
using exponentiation **. Using
math.sqrt is somewhat more efficient.
"Somewhat", but to what extent, and how?
| [
"Theoretically, hammar's answer and duffymo's answer are good guesses. But in practice, on my machine, it's not more efficient:\n>>> import timeit\n>>> timeit.timeit(stmt='[n ** 0.5 for n in range(100)]', setup='import math', number=10000)\n0.15518403053283691\n>>> timeit.timeit(stmt='[math.sqrt(n) for n in range(1... | [
16,
11,
1,
1,
1
] | [] | [] | [
"exponentiation",
"python"
] | stackoverflow_0006637589_exponentiation_python.txt |
Q:
Remove all occurrences in a string except the first occurrence
In Python, I'm looking to remove all the "<html>" from a string (except for the first occurrence).
Also, I'm looking to remove all the "</html>" from a string (except for the last occurrence).
<html> can be uppercase, so I need it to be case insensitiv... | Remove all occurrences in a string except the first occurrence | In Python, I'm looking to remove all the "<html>" from a string (except for the first occurrence).
Also, I'm looking to remove all the "</html>" from a string (except for the last occurrence).
<html> can be uppercase, so I need it to be case insensitive.
What is my best approach?
| [
"To remove all but the first occurrence of <html> from the string s, you can use the follwoing code:\nsubstr = \"<html>\"\ntry:\n first_occurrence = s.index(substr) + len(substr)\nexcept ValueError:\n pass\nelse:\n s = s[:first_occurrence] + s[first_occurrence:].replace(substr, \"\")\n\nAll but the last oc... | [
5,
3
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0008552578_python_regex_string.txt |
Q:
Create variable names on demand
I'm trying to code a console minigame (for fun), and I need to create a map(graph) with a predefined number of rooms(vertices).
I'd like to define a class room and create instances of that class that will be assigned to variable names like room_1, room_2 and so on.
My problem is, th... | Create variable names on demand | I'm trying to code a console minigame (for fun), and I need to create a map(graph) with a predefined number of rooms(vertices).
I'd like to define a class room and create instances of that class that will be assigned to variable names like room_1, room_2 and so on.
My problem is, that I don't know how to create these v... | [
"Use a dict instead.\nrooms = dict(('room_%d' % x, Room(x)) for x in range(1, 6))\n\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0008554354_python.txt |
Q:
ValueError: math domain error when sending to function but works on its own
I'm sure this is a newbie question so sorry in advance. I've read a few books on basic python usage and am now working on the tutorials in 'programming collective intelligence' but I'm getting an error with my block of code:
ValueError: m... | ValueError: math domain error when sending to function but works on its own | I'm sure this is a newbie question so sorry in advance. I've read a few books on basic python usage and am now working on the tutorials in 'programming collective intelligence' but I'm getting an error with my block of code:
ValueError: math domain error
I see this error alot on google but I'm not sure why its happen... | [
"You can't take the square root of a negative number with math.sqrt(). If you're sure you want to (although I suspect you really don't...) then use cmath.sqrt() instead.\n",
"I think you're missing a pair of parentheses from this line:\nden=sqrt((sum1Sq-pow(sum1,2)/n)* sum2Sq-pow(sum2,2)/n)\n\nI think it should b... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0008554401_python.txt |
Q:
apply two functions to the two halves of a numpy array
I am trying to find how to apply two functions to a numpy array each one only on half the values.
Here is the code I have been trying
def hybrid_array(xs,height,center,fwhh):
xs[xs<=center] = height*np.exp((-(xs[xs<=center]-center)**2)/(2*(fwhh/(2*np.sqrt(... | apply two functions to the two halves of a numpy array | I am trying to find how to apply two functions to a numpy array each one only on half the values.
Here is the code I have been trying
def hybrid_array(xs,height,center,fwhh):
xs[xs<=center] = height*np.exp((-(xs[xs<=center]-center)**2)/(2*(fwhh/(2*np.sqrt(2*np.log(2))))**2))
xs[xs>center] = height*1/(np.abs(1+(... | [
"Try copy.deepcopy to copy the array b onto a before calling your function.\nimport copy\na = copy.deepcopy(b)\nc = hybrid_array(a,args)\n\nAlternatively, you can use the copy method of the array\na = b.copy()\nc = hybrid_array(a,args)\n\nNote***\nYou may be wondering, why despite an easier way to copy an array wit... | [
3,
2
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0008554409_arrays_numpy_python.txt |
Q:
timing a python program with threads
I have the following block of code that is part of a larger program. I am trying to get it to print the execution time once all of the threads are closed but can't seem to get it to work. Any ideas?
import time
import csv
import threading
import urllib.request
def openSP5... | timing a python program with threads | I have the following block of code that is part of a larger program. I am trying to get it to print the execution time once all of the threads are closed but can't seem to get it to work. Any ideas?
import time
import csv
import threading
import urllib.request
def openSP500file():
SP500 = reader(open(r'C:\Us... | [
"You aren't waiting for all the threads to finish (only the last one created). Perhaps something like this in your thread-spawning loop?\nthreads = []\nfor x in SP500:\n t1 = StockData(x[0])\n t1.start()\n threads.append(t1)\nfor t in threads:\n t.join()\n... print running time\n\n"
] | [
2
] | [] | [] | [
"multithreading",
"python",
"time"
] | stackoverflow_0008554503_multithreading_python_time.txt |
Q:
How to implement "where" (numpy.where(...) )?
I'm a functional programming newbie.
I'd like to know how to implement numpy.where() in python, scala or haskell.
A good explanation would be helpful to me.
A:
In Haskell, doing it for n-dimensional lists, as the NumPy equivalent supports, requires a fairly advanced ... | How to implement "where" (numpy.where(...) )? | I'm a functional programming newbie.
I'd like to know how to implement numpy.where() in python, scala or haskell.
A good explanation would be helpful to me.
| [
"In Haskell, doing it for n-dimensional lists, as the NumPy equivalent supports, requires a fairly advanced typeclass construction, but the 1-dimensional case is easy:\nselect :: [Bool] -> [a] -> [a] -> [a]\nselect [] [] [] = []\nselect (True:bs) (x:xs) (_:ys) = x : select bs xs ys\nselect (False:bs) (_:xs) (y:ys) ... | [
6,
5,
3
] | [] | [] | [
"functional_programming",
"haskell",
"numpy",
"python",
"scala"
] | stackoverflow_0008554673_functional_programming_haskell_numpy_python_scala.txt |
Q:
Create a grid of buttons using a loop in PyQT4
Is there a way to create a grid of buttons using a loop in PyQT4?
So for example, something that has the effect of:
for j in range(0, 10):
for k in range(0, 10):
grid.addbutton(j, k)
Thank you.
A:
Sure there is. QGridLayout might be useful in this case.... | Create a grid of buttons using a loop in PyQT4 | Is there a way to create a grid of buttons using a loop in PyQT4?
So for example, something that has the effect of:
for j in range(0, 10):
for k in range(0, 10):
grid.addbutton(j, k)
Thank you.
| [
"Sure there is. QGridLayout might be useful in this case.\nHere is a minimal example:\nimport sys\nfrom PyQt4 import QtGui\n\napp = QtGui.QApplication(sys.argv)\nwidget = QtGui.QWidget()\nlayout = QtGui.QGridLayout()\n\nbuttons = {}\n\nfor i in range(10):\n for j in range(10):\n # keep a reference to the ... | [
7
] | [] | [] | [
"button",
"grid",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0008554610_button_grid_pyqt_pyqt4_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.