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:
Updating a quickhull implementation to Python 3.2, list manipulation
So, I've got a quickhull implementation in python that I'm trying to use in python 3.2. Mostly it's fine, but there's a list indexing problem I'm having. The code does:
axis = sample[:,0]
This doesn't work, as python complains that list indices ... | Updating a quickhull implementation to Python 3.2, list manipulation | So, I've got a quickhull implementation in python that I'm trying to use in python 3.2. Mostly it's fine, but there's a list indexing problem I'm having. The code does:
axis = sample[:,0]
This doesn't work, as python complains that list indices need to be integers, no tuples. I'm having trouble trying to understand wh... | [
"axis is a Python list, but it should be a numpy array. The code is using numpy's special indexing rules for arrays to extract the first column.\n"
] | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006892202_list_python.txt |
Q:
lxml: get element with a particular child element?
Working in lxml, I want to get the href attribute of all links with an img child that has title="Go to next page".
So in the following snippet:
<a class="noborder" href="StdResults.aspx">
<img src="arrowr.gif" title="Go to next page"></img>
</a>
I'd like to get S... | lxml: get element with a particular child element? | Working in lxml, I want to get the href attribute of all links with an img child that has title="Go to next page".
So in the following snippet:
<a class="noborder" href="StdResults.aspx">
<img src="arrowr.gif" title="Go to next page"></img>
</a>
I'd like to get StdResults.aspx back.
I've got this far:
next_link = doc.... | [
"Just change a/img... to a[img...]: (the brackets sort of mean \"such that\")\nimport lxml.html as lh\n\ncontent='''<a class=\"noborder\" href=\"StdResults.aspx\">\n<img src=\"arrowr.gif\" title=\"Go to next page\"></img>\n</a>'''\n\ndoc=lh.fromstring(content)\nfor elt in doc.xpath(\"//a[img[@title='Go to next page... | [
2,
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0006892219_lxml_python.txt |
Q:
Taking full screen images with Python (Windows)
I've tried a number of things, but all I can get if I try to do an auto screen shot of a full size window is a black screen.
I've tried ImageGrab.grab(), and automated Prt Scr press and I've had no luck.
The automated Prt Scr key press allowed me to manually paste th... | Taking full screen images with Python (Windows) | I've tried a number of things, but all I can get if I try to do an auto screen shot of a full size window is a black screen.
I've tried ImageGrab.grab(), and automated Prt Scr press and I've had no luck.
The automated Prt Scr key press allowed me to manually paste the image correctly into paint, but if I tried to load ... | [
"Have you tried\nim = ImageGrab.grabclipboard()\n\nif isinstance(im, Image.Image):\n... got an image ...\nelif im:\n for filename in im:\n try:\n im = Image.open(filename)\n except IOError:\n pass # ignore this file\n else:\n ... got an image ...\nelse:\n ... cli... | [
0
] | [] | [] | [
"python",
"python_imaging_library",
"win32com",
"win32gui",
"windows"
] | stackoverflow_0006891824_python_python_imaging_library_win32com_win32gui_windows.txt |
Q:
Data Migrations and AppEngine
I've done a lot of development in rails, and am looking into developing projects using python & app engine.
From the demo project and what I've seen so far, I've got a question/concern about app engine projects:
How is data migration handled in app-engine? For example, if I change the... | Data Migrations and AppEngine | I've done a lot of development in rails, and am looking into developing projects using python & app engine.
From the demo project and what I've seen so far, I've got a question/concern about app engine projects:
How is data migration handled in app-engine? For example, if I change the name of an entity/table (ex: Texts... | [
"The short answer is: It doesn't handle it. You can't change the name of an entity, you can change a property but you'll have to update the data manually.\nYour Model definitions are just your applications \"view\" of how to interpret the entities stored in the datastore. If I had a definition like:\nclass MyEntity... | [
8,
1
] | [] | [] | [
"data_migration",
"google_app_engine",
"python",
"ruby_on_rails_3"
] | stackoverflow_0006892408_data_migration_google_app_engine_python_ruby_on_rails_3.txt |
Q:
Controlling a File Upload Box with Python
I am wondering what modules or methods I should use to control a File Upload box from Python. I want Python to take control of this box when it pops up, and automatically navigate to a specific folder/file and select this file.
A:
I used the SendKeys module, which allows... | Controlling a File Upload Box with Python | I am wondering what modules or methods I should use to control a File Upload box from Python. I want Python to take control of this box when it pops up, and automatically navigate to a specific folder/file and select this file.
| [
"I used the SendKeys module, which allows you to send keystrokes to Windows. Not perfect, but it works in the meantime.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006878273_python.txt |
Q:
{PYTHON + TKINTER} "Type cast" problem: How to retrieve Custom frame objects from a Pmw.NoteBook?
I am writing a GUI Python application.
I am using Tkinter + PythonMegaWidgets for semplicity reasons.
Going straight to the point, I need to extend Tkinter.Frame baseclass, by adding some custom member functions whi... | {PYTHON + TKINTER} "Type cast" problem: How to retrieve Custom frame objects from a Pmw.NoteBook? | I am writing a GUI Python application.
I am using Tkinter + PythonMegaWidgets for semplicity reasons.
Going straight to the point, I need to extend Tkinter.Frame baseclass, by adding some custom member functions which provides extra-functionalities.
These "Custom Frames" will be added to single tabs of a Pmw.NoteBook... | [
"I don't think you need to change the class of the notebook tab, you can just add your custom frame inside that tab. Just tell the frame what your inner frame is, and remember to pack your inner frame inside the tab frame. \nFor example:\nclass MyFrame(Frame):\n def __init__(self, master=None):\n ...\n ... | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006891553_python_tkinter.txt |
Q:
joining string to next string in list
I have a list with a large number of words in it:
sentence = ['a','list','with','a','lot','of','strings','in','it']
I want to be be able to go through the list and combine pairs of words according to some conditions I have. e.g.
['a','list','with','a','lot','of','strings','in'... | joining string to next string in list | I have a list with a large number of words in it:
sentence = ['a','list','with','a','lot','of','strings','in','it']
I want to be be able to go through the list and combine pairs of words according to some conditions I have. e.g.
['a','list','with','a','lot','of','strings','in','it']
becomes
['a list','with','a lot','o... | [
"You can use an iterator.\n>>> it = iter(['a','list','with','a','lot','of','strings','in','it'])\n>>> [i if i != 'a' else i+' '+next(it) for i in it]\n['a list', 'with', 'a lot', 'of', 'strings', 'in', 'it']\n\n",
"This works in-place:\nsentence = ['a','list','with','a','lot','of','strings','in','it']\n\nidx=0\ns... | [
4,
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006892472_python.txt |
Q:
Python: multiplication override
So, I've got a custom class that has a __mul__ function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., 2 * x where x is of my class. Is there a way I can have it use my __mul__ function for this?
A:
Just add the follow... | Python: multiplication override | So, I've got a custom class that has a __mul__ function which works with ints. However, in my program (in libraries), it's getting called the other way around, i.e., 2 * x where x is of my class. Is there a way I can have it use my __mul__ function for this?
| [
"Just add the following to the class definition and you should be good to go:\n__rmul__ = __mul__\n\n",
"Implement __rmul__ as well.\nclass Foo(object):\n def __mul__(self, other):\n print '__mul__'\n return other\n def __rmul__(self, other):\n print '__rmul__'\n return other\n\n... | [
55,
38
] | [] | [] | [
"operator_keyword",
"overriding",
"python"
] | stackoverflow_0006892616_operator_keyword_overriding_python.txt |
Q:
Boost.Python: Weak reference to object?
Is there a way to get a weak reference to a Python object? With boost::python::object you get a strong/shared reference so as long as either C++ or Python holds a reference to that object, it will not get deleted. I want only Python to hold a strong reference to an object, a... | Boost.Python: Weak reference to object? | Is there a way to get a weak reference to a Python object? With boost::python::object you get a strong/shared reference so as long as either C++ or Python holds a reference to that object, it will not get deleted. I want only Python to hold a strong reference to an object, and C++ a weak one. Is that possible?
| [
"You need to go into the CPython API for that. Use PyWeakReference type from weakrefobject.h. The header exposes an API that's similar to weakref module — see the docs.\n"
] | [
4
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0006892651_boost_python_c++_python.txt |
Q:
Python Crawler - need help with my algorithm
** Added a summary of the problem at the end of the post **
I've written a crawler that fetches and parses URLs.
in the first version, in order to get the next valid page I was increasing the URL ID and saved non-valid IDs to a file, the valid URLs were moved to a parse... | Python Crawler - need help with my algorithm | ** Added a summary of the problem at the end of the post **
I've written a crawler that fetches and parses URLs.
in the first version, in order to get the next valid page I was increasing the URL ID and saved non-valid IDs to a file, the valid URLs were moved to a parser that parsed the content I need, after a while I ... | [
"Stating an identifier as being global is done when one wants to provoke a modification concerning it when it is outside the function from which the modification is performed.\nHence it is an aberration to make lastResult and curRes global:\n\nthe first, lastResult, because it is a constant in your complete code. T... | [
1,
1,
0
] | [] | [] | [
"algorithm",
"python",
"web_crawler"
] | stackoverflow_0006879253_algorithm_python_web_crawler.txt |
Q:
problem with urlopen
This code used to print out a web page. It now prints a single space, even though that page clearly has content when viewed in a browser
from urllib.request import urlopen
f = urlopen('http://online.wsj.com/mdc/public/page/2_3020-tips.html?mod=topnav_2_3000')
page = f.read()
f.close()
print('... | problem with urlopen | This code used to print out a web page. It now prints a single space, even though that page clearly has content when viewed in a browser
from urllib.request import urlopen
f = urlopen('http://online.wsj.com/mdc/public/page/2_3020-tips.html?mod=topnav_2_3000')
page = f.read()
f.close()
print('*', page.decode(), '*')
T... | [
"It works in Python 3.1 and Python 3.2, but not Python 3.2.1 (it returns an empty string).\nEDIT: I've reported it in the Python-Dev list.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006892573_python_python_3.x.txt |
Q:
Python: subsetting multiple elements
Given
mylist = ["a", "b", "c"]
how can I subset elements 0 and 2 (i.e., ["a", "c"])?
A:
Although this is not the usual way to use itemgetter,
>>> from operator import itemgetter
>>> mylist = ["a", "b", "c"]
>>> itemgetter(0,2)(mylist)
('a', 'c')
If the indices are already i... | Python: subsetting multiple elements | Given
mylist = ["a", "b", "c"]
how can I subset elements 0 and 2 (i.e., ["a", "c"])?
| [
"Although this is not the usual way to use itemgetter,\n>>> from operator import itemgetter\n>>> mylist = [\"a\", \"b\", \"c\"]\n>>> itemgetter(0,2)(mylist)\n('a', 'c')\n\nIf the indices are already in a list - use * to unpack it\n>>> itemgetter(*[0,2])(mylist)\n('a', 'c')\n\nYou an also use a list comprehension\n>... | [
8,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006892835_python.txt |
Q:
Formatting operator modifiers doesn't work in a Python 3 script
this piece of code is driving me crazy. I'm trying to print a help list for a program I'm writing. So I define a dictionary, where the keys are the words that the user might want to be clarified and the values are the descriptions of the words. Then I... | Formatting operator modifiers doesn't work in a Python 3 script | this piece of code is driving me crazy. I'm trying to print a help list for a program I'm writing. So I define a dictionary, where the keys are the words that the user might want to be clarified and the values are the descriptions of the words. Then I use a for... in... loop to print it all. To put it simple:
ERROR = '... | [
"The problem is that those are at least 10 characters long: remember, the ANSI escape characters count. You could do any of the following:\n\nIncrease the field width until you get the width you want (since all of them seem to contain the same number of escape characters, this might work).\nStrip the escape charact... | [
3
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0006893166_python_string_formatting.txt |
Q:
Gnomeapplet - Seeing only a white dot where an entry and a button should be
I have written a gnomeapplet for gnome-panel, and the corresponding server file. Everything seems to work fine when I use the "debug mode", but when I try to load the applet from the panel it shows only a little white dot.
Can anyone help ... | Gnomeapplet - Seeing only a white dot where an entry and a button should be | I have written a gnomeapplet for gnome-panel, and the corresponding server file. Everything seems to work fine when I use the "debug mode", but when I try to load the applet from the panel it shows only a little white dot.
Can anyone help me find the problem?
my code is:
#!/usr/bin/env python
import gnomeapplet
import... | [
"Solved...The solution was so simple...I just have to change the path to the image file to the complete path...instead of pixbuf = gtk.gdk.pixbuf_new_from_file('1.png') I should use for example: pixbuf = gtk.gdk.pixbuf_new_from_file('/home/username/applet/1.png')\nBetter: pixbuf = gtk.gdk.pixbuf_new_from_file(os.pa... | [
1
] | [] | [] | [
"gnome",
"pygtk",
"python"
] | stackoverflow_0006867056_gnome_pygtk_python.txt |
Q:
Automatic CudaMat conversion in Python
I'm looking into speeding up my python code, which is all matrix math, using some form of CUDA. Currently my code is using Python and Numpy, so it seems like it shouldn't be too difficult to rewrite it using something like either PyCUDA or CudaMat.
However, on my first attemp... | Automatic CudaMat conversion in Python | I'm looking into speeding up my python code, which is all matrix math, using some form of CUDA. Currently my code is using Python and Numpy, so it seems like it shouldn't be too difficult to rewrite it using something like either PyCUDA or CudaMat.
However, on my first attempt using CudaMat, I realized I had to rearran... | [
"Have you looked at the GPUArray portion of PyCUDA?\nhttp://documen.tician.de/pycuda/array.html\nWhile I haven't used it myself, it seems like it would be what you're looking for. In particular, check out the \"Single-pass Custom Expression Evaluation\" section near the bottom of that page.\n"
] | [
2
] | [] | [] | [
"cuda",
"matrix",
"optimization",
"pycuda",
"python"
] | stackoverflow_0006735651_cuda_matrix_optimization_pycuda_python.txt |
Q:
what does calling a method do?
ok, noob question
I had this code
list = ['random', 'set', 'of', 'strings']
for item in list:
item.replace('a','b')
print list
the output doesn't show the replacement unless I change the code to this
list = ['random', 'set... | what does calling a method do? | ok, noob question
I had this code
list = ['random', 'set', 'of', 'strings']
for item in list:
item.replace('a','b')
print list
the output doesn't show the replacement unless I change the code to this
list = ['random', 'set', 'of', 'strings']
for ... | [
"The method is simply returning the new value, it does not modify the existing one.\nThere is no set rules that specify that all or no methods will do this, you will have to check the documentation for each one to know specifically what it does and what to expect.\nLots of functions are like that.\nTake this:\na = ... | [
5,
4,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006892694_python_string.txt |
Q:
Python mandatoryl arbitrary argument list *args
is there any way to define a mandatory *args (arbitrary arguments) in a method of a class?
class foo():
def __init__(self,*args):
....
Given this, you can create an object from the foo-class without any arguments x=foo(), i.e. its optional. Any ideas how to c... | Python mandatoryl arbitrary argument list *args | is there any way to define a mandatory *args (arbitrary arguments) in a method of a class?
class foo():
def __init__(self,*args):
....
Given this, you can create an object from the foo-class without any arguments x=foo(), i.e. its optional. Any ideas how to change it to a non-optional or "give me at least one a... | [
"*args is meant to receive all arguments that are not already taken by normal arguments.\nUsually if you need an argument to be mandatory, you just use a normal argument:\n>>> def foo(arg, *rest):\n... print arg, rest\n... \n>>> foo()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\... | [
4,
2,
0
] | [] | [] | [
"python",
"variadic_functions"
] | stackoverflow_0006892886_python_variadic_functions.txt |
Q:
libtorrent dht peer request?
Ive been playing around with the python bindings for libtorrent/rasterbar.
What I wanted to do was generate a new 'node-id' and reannounce it to the other nodes.
I read that a 'bencoded dicionary' needs to be created and I assume announced using something like force_dht_reannounce, is... | libtorrent dht peer request? | Ive been playing around with the python bindings for libtorrent/rasterbar.
What I wanted to do was generate a new 'node-id' and reannounce it to the other nodes.
I read that a 'bencoded dicionary' needs to be created and I assume announced using something like force_dht_reannounce, is this correct?
| [
"You can force libtorrent to use a specific node ID for the DHT by crafting a session-state file, and feed it to the session::load_state() function. Once you do this, you also need to restart the DHT by calling session::stop_dht() followed by session::start_dht().\nThe relevant parts of the session state you need t... | [
4
] | [] | [] | [
"bittorrent",
"dht",
"pex",
"python",
"uri"
] | stackoverflow_0006612429_bittorrent_dht_pex_python_uri.txt |
Q:
What is the Python "with" statement used for?
I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someone post some other examples too. I am just trying out flask and there are with statements galor... | What is the Python "with" statement used for? | I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someone post some other examples too. I am just trying out flask and there are with statements galore in it. Definitely request someone to provide som... | [
"There's a very nice explanation here. Basically, the with statement calls two special methods on the associated object. The __enter__ and __exit__ methods. The enter method returns the variable associated with the \"with\" statement. While the __exit__ method is called after the statement executes to handle any... | [
9,
9,
1
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0003813886_flask_python.txt |
Q:
How to load SWF content into a Python application on Linux?
I have an application that uses Flash for the GUI and Python for the core logic. This combination is awesome. Unfortunately my current approach only works on Windows, as it uses the wxPython comtypes library to embed the Flash ActiveX player. Every other ... | How to load SWF content into a Python application on Linux? | I have an application that uses Flash for the GUI and Python for the core logic. This combination is awesome. Unfortunately my current approach only works on Windows, as it uses the wxPython comtypes library to embed the Flash ActiveX player. Every other aspect of the app is platform-agnostic, so I'm thinking there mus... | [
"Flash Professional has support to Adobe Air, so you could use it as front-end, usually a flash project can be released as an AIR application without major changes to its code. The communication could be done using Native Process Api (see links bellow). Then you can run it on Mac, Win e Lin.\nhttp://www.kirupa.com/... | [
0
] | [] | [] | [
"embedding",
"flash",
"linux",
"python"
] | stackoverflow_0006838380_embedding_flash_linux_python.txt |
Q:
Using existing soap client written Python & suds for an iPhone app
I have written a client for JIRA in python and I was wondering if there is any way to use my existing libraries written in python for an iPhone jira client.
I read a little bit about pyObjc which I think is a bridge between the two language.
can ... | Using existing soap client written Python & suds for an iPhone app | I have written a client for JIRA in python and I was wondering if there is any way to use my existing libraries written in python for an iPhone jira client.
I read a little bit about pyObjc which I think is a bridge between the two language.
can I compile my python libraries into ObjC libraries?
If someone can point ... | [
"What you probably want to do is to embed a Python interpreter in a native iPhone app and then issue commands for it to run your Python scripts which in turn call your Python libraries.\nOn boot\n\nCreate Python interpreter in the app\nMake it to load your Python libaries\nSet-up Python environemnt (global vars and... | [
0
] | [] | [] | [
"ios",
"jira",
"python",
"soap",
"suds"
] | stackoverflow_0006892632_ios_jira_python_soap_suds.txt |
Q:
Python byte buffer object?
Is there a byte buffer object in Python to which I can append values of specific types? (preferably with specifiable endianess)
For example:
buf.add_int(4) # should add a 4 byte integer
buf.add_short(10) # should add a 2 byte short
buf.add_byte(24) # should add a byte
I know that I ... | Python byte buffer object? | Is there a byte buffer object in Python to which I can append values of specific types? (preferably with specifiable endianess)
For example:
buf.add_int(4) # should add a 4 byte integer
buf.add_short(10) # should add a 2 byte short
buf.add_byte(24) # should add a byte
I know that I could just use struct.pack but t... | [
"You can always use bitstring. It is capable of doing all the things you ask and more.\n>>> import bitstring\n>>> stream=bitstring.BitStream()\n>>> stream.append(\"int:32=4\")\n>>> stream.append(\"int:16=10\")\n>>> stream.append(\"int:8=24\")\n>>> stream\nBitStream('0x00000004000a18')\n>>> stream.bytes\n'\\x00\\x00... | [
11,
5,
1
] | [] | [] | [
"buffer",
"python"
] | stackoverflow_0006892570_buffer_python.txt |
Q:
Web2py Python split rows based on true/false from database result
I have the following code in web2py/python:
{{for row in db(db.t_problems.id==db.t_problems(request.args(0))).select(): }}
Which grabs all of the rows, as I need them to be. The rows are actual python results, which when I print them out are:
>>> t... | Web2py Python split rows based on true/false from database result | I have the following code in web2py/python:
{{for row in db(db.t_problems.id==db.t_problems(request.args(0))).select(): }}
Which grabs all of the rows, as I need them to be. The rows are actual python results, which when I print them out are:
>>> testFunction(2, 3, 4) True >>> testFunction(2, 1, 4) False >>> legalTria... | [
"In raw python, it would be,\ns = \">>> testFunction(2, 3, 4)\\r\\nTrue >>> testFunction(2, 1, 4)\\r\\nFalse >>> legalTriangles(-1, -1, -1)\\r\\nFalse\"\nfor func, result in [i.splitlines() for i in s.split(\">>>\") if i]:\n print \"<tr><td>%s</td><td>%s</td></tr>\" % (func.strip(), result.strip())\n\nResult:\n<... | [
0
] | [] | [] | [
"for_loop",
"python",
"split",
"web2py"
] | stackoverflow_0006893573_for_loop_python_split_web2py.txt |
Q:
PDF Thumbnailing with Google App Engine (Python)
Is it possible, using the python version of google app engine, to create a thumbnail of a PDF file?
The goal is for the user to be able to upload a PDF, and see it represented as a thumbnail on the page.
A:
You may be able to use Google's imaging services directl... | PDF Thumbnailing with Google App Engine (Python) | Is it possible, using the python version of google app engine, to create a thumbnail of a PDF file?
The goal is for the user to be able to upload a PDF, and see it represented as a thumbnail on the page.
| [
"You may be able to use Google's imaging services directly, since PDFs are essentially images and PIL can do this, though I haven't tried it. \nIf the direct approach doesn't work, you may be able to use the following process: \n\nSave the PDF to the blobstore. \nOpen its link. \nObtain a snapshot of the displayed ... | [
2,
1
] | [] | [] | [
"google_app_engine",
"pdf",
"python"
] | stackoverflow_0006878642_google_app_engine_pdf_python.txt |
Q:
TypeError: __init__() takes at least 4 non-keyword arguments (3 given)
Possible Duplicate:
TypeError: init() takes at least 4 non-keyword arguments (3 given)
When i use this script:
import sys, tweepy, webbrowser
Q = sys.argv[1:]
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, stat... | TypeError: __init__() takes at least 4 non-keyword arguments (3 given) |
Possible Duplicate:
TypeError: init() takes at least 4 non-keyword arguments (3 given)
When i use this script:
import sys, tweepy, webbrowser
Q = sys.argv[1:]
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
try:
print "%s\t%s\t%s\t%s" % (status.text,... | [
"streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout=60)\n\nin this line you need to change auth with username, password separately, or update to the last release of tweepy.\n"
] | [
0
] | [] | [] | [
"api",
"arguments",
"python",
"streaming"
] | stackoverflow_0006893896_api_arguments_python_streaming.txt |
Q:
Handling file submissions with html and python
I'm trying to create a form that will handle video file uploads from the user, but I'm running into a bunch of problems. I am trying to avoid building a model form for this because I won't be saving the file to my database long term. I just want to get it to the serve... | Handling file submissions with html and python | I'm trying to create a form that will handle video file uploads from the user, but I'm running into a bunch of problems. I am trying to avoid building a model form for this because I won't be saving the file to my database long term. I just want to get it to the server so that I can submit it to youtube. The html I hav... | [
"request.POST doesn't contain file upload information. You need to use request.FILES.\n"
] | [
2
] | [] | [] | [
"django",
"file_upload",
"html",
"python"
] | stackoverflow_0006893870_django_file_upload_html_python.txt |
Q:
How to set up a file download dialog using Django and jQuery?
I am jQuery newbie and I have been trying to set up a file download dialog window without any success. If and when the dialog window is loaded, the user should have the option to download the dynamically generated file. I am not able to set up a dialog ... | How to set up a file download dialog using Django and jQuery? | I am jQuery newbie and I have been trying to set up a file download dialog window without any success. If and when the dialog window is loaded, the user should have the option to download the dynamically generated file. I am not able to set up a dialog window.
On debugging, I can see that a valid http response is gener... | [
"Instead of performing the POST in AJAX, have the browser navigate to the view naturally. The browser will then prompt for the download.\n"
] | [
1
] | [] | [] | [
"django",
"django_templates",
"jquery",
"python"
] | stackoverflow_0006893946_django_django_templates_jquery_python.txt |
Q:
Subtract and add two lists without changing their order in Python
If I have the list [68,31,93,35,10] (all the numbers will be different) and the list [93,0,22,10,99,33,21,9] (again, all the numbers will be different, but may overlap the other list), I need to be able to get exactly [68,31,93,35,10,0,22,99,33,21,9... | Subtract and add two lists without changing their order in Python | If I have the list [68,31,93,35,10] (all the numbers will be different) and the list [93,0,22,10,99,33,21,9] (again, all the numbers will be different, but may overlap the other list), I need to be able to get exactly [68,31,93,35,10,0,22,99,33,21,9], where the second list is appended to the first list without duplicat... | [
"l1 = [68, 31, 93, 35,10]\nl2 = [93, 0, 22, 10, 99, 33, 21,9]\n\nl1 + [x for x in l2 if not x in l1]\n# [68, 31, 93, 35, 10, 0, 22, 99, 33, 21, 9]\n\n[x for x in l1 if not x in l2]\n# [68, 31, 35]\n\nEDIT: for long lists, you don't want to do all those list lookups. Here are two other recipes:\nunion:\nfrom collect... | [
4,
2,
0,
0,
0,
0
] | [] | [] | [
"addition",
"list",
"python",
"subtraction"
] | stackoverflow_0006889726_addition_list_python_subtraction.txt |
Q:
App (or Model) Not Showing up in Django Admin
Note:
Django 1.3
thingy is my experimental app's name.
been learning Python & Django for a week.
I'm just trying to get my app to show up in the admin area, but it won't work. I've already read other questions/answers elsewhere on this site on this issue, but none of... | App (or Model) Not Showing up in Django Admin | Note:
Django 1.3
thingy is my experimental app's name.
been learning Python & Django for a week.
I'm just trying to get my app to show up in the admin area, but it won't work. I've already read other questions/answers elsewhere on this site on this issue, but none of it helped me get this working. I'm guessing the pr... | [
"In your admin.py you should change the way you're registering your model.\nChange the class name from\nclass Daily(admin.ModelAdmin):\n fields = ['user', 'hours_as_sec']\n\nto\nclass DailyAdmin(admin.ModelAdmin):\n fields = ['user', 'hours_as_sec']\n\nand register as follows:\nadmin.site.register(Daily... | [
4
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0006893988_django_django_admin_python.txt |
Q:
Submit without the use of a submit button, Mechanize
So, I started out with Mechanize, and apparently the first thing I try it on is a monkey-rhino-level high JavaScript navigated site.
Now the thing I'm stuck on is submitting the form.
Normally I'd do a submit using the Mechanize built-in submit() function.
impor... | Submit without the use of a submit button, Mechanize | So, I started out with Mechanize, and apparently the first thing I try it on is a monkey-rhino-level high JavaScript navigated site.
Now the thing I'm stuck on is submitting the form.
Normally I'd do a submit using the Mechanize built-in submit() function.
import mechanize
browser = mechanize.Browser()
browser.select_... | [
"Three ways:\nThe first method is preferable if the form is submitted using the POST/GET method, otherwise you'll have to resort to second and third method.\n\nSubmitting the form manually and check for POST/GET requests, their parameters and the post url required to submit the form. Popular tools for checking head... | [
11
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0005035390_mechanize_python.txt |
Q:
Python mechanize: read table element next to input
I'm using mechanize to fill out a form that has a series of rows. Each row is an <input type="checkbox"> followed by <td>name of the checkbox</td>. How do I read the name so I know whether to check the box?
Thanks
A:
I would recommend using both mechanize and et... | Python mechanize: read table element next to input | I'm using mechanize to fill out a form that has a series of rows. Each row is an <input type="checkbox"> followed by <td>name of the checkbox</td>. How do I read the name so I know whether to check the box?
Thanks
| [
"I would recommend using both mechanize and etree, but I'm no programmer, so don't take my word for it. Note: all code is in python, and is ver 2.7.1 but should work up to 2.7.3.\nHope I could help\n -Just another Dunce\nimport mechanize\nimport lxml.etree as etree\n\nurl = 'something'\n\nbr = mechanize.Bro... | [
0
] | [] | [] | [
"mechanize",
"python",
"webforms"
] | stackoverflow_0003849204_mechanize_python_webforms.txt |
Q:
How do I add a dependency to Buildout?
I'm quite new to Buildout, but I just got my first Django application building in it thanks to the nice tutorial here. I'm used to using Maven, so how do I "add a dependency" so Buildout will download it and include it in the build? Here's my buildout.cfg file:
[buildout]
par... | How do I add a dependency to Buildout? | I'm quite new to Buildout, but I just got my first Django application building in it thanks to the nice tutorial here. I'm used to using Maven, so how do I "add a dependency" so Buildout will download it and include it in the build? Here's my buildout.cfg file:
[buildout]
parts = python django
develop = .
eggs = my-pro... | [
"Add the name of the required dependency to setup.py's install_requires array:\nsetup(\n ...\n install_requires = ['setuptools', 'south'],\n ...\n)\n\n"
] | [
6
] | [] | [] | [
"buildout",
"python"
] | stackoverflow_0006893758_buildout_python.txt |
Q:
Is there a way to get all modules 'under' a specific module in the hierarchy?
Is there a way of listing all python modules directly underneath a specified model in the hierarchy?
I've got a Django web-app that is slowly growing, and I've re-organised it based on this article:
http://paltman.com/2008/01/29/breaking... | Is there a way to get all modules 'under' a specific module in the hierarchy? | Is there a way of listing all python modules directly underneath a specified model in the hierarchy?
I've got a Django web-app that is slowly growing, and I've re-organised it based on this article:
http://paltman.com/2008/01/29/breaking-apart-models-in-django/
However, I'm trying to improve on his technique by making ... | [
"Well, you can get os.path.dirname(parent.__file__), and then glob.glob() or os.walk() and look for other init.py files.\n",
"This is just an attempt, but it seems to work. I'm running python 2.7.1 and dir(somemodule) gives me all associated modules. Tested with the openpyxl and os modules.\ndef import_all(nam... | [
1,
1
] | [] | [] | [
"django",
"introspection",
"python"
] | stackoverflow_0006889864_django_introspection_python.txt |
Q:
How do I modify gitstats to only utilize a specified file extension for its statistics?
The website of the statistics generator in question is:
http://gitstats.sourceforge.net/
Its git repository can be cloned from:
git clone git://repo.or.cz/gitstats.git
What I want to do is something like:
./gitstatus --ext=".... | How do I modify gitstats to only utilize a specified file extension for its statistics? | The website of the statistics generator in question is:
http://gitstats.sourceforge.net/
Its git repository can be cloned from:
git clone git://repo.or.cz/gitstats.git
What I want to do is something like:
./gitstatus --ext=".py" /input/foo /output/bar
Failing being able to easily pass the above option without heavy ... | [
"I found this question today while looking for the same thing. After reading sinelaw's answer I looked into the code and ended up forking the project.\nhttps://github.com/ShawnMilo/GitStats\nI added an \"exclude_extensions\" config option. It doesn't affect all parts of the output, but it's getting there. \nI may e... | [
6,
3
] | [] | [] | [
"python"
] | stackoverflow_0004686647_python.txt |
Q:
How do I test a database connection in Django?
How do I test a database connection for Django? For example to make sure that the username and password of the database is correct.
Or if it is easier, where do I "catch" the database error when database connection fails ?
I have a scenario where database connection p... | How do I test a database connection in Django? | How do I test a database connection for Django? For example to make sure that the username and password of the database is correct.
Or if it is easier, where do I "catch" the database error when database connection fails ?
I have a scenario where database connection parameters is defined in a form by user. I need to ma... | [
"Write a middleware (\"How Django processes a request\") which will check for the database connection and redirect to your edit form.\nclass DbCheckMiddleware(object):\n\n def process_request(self, request):\n try:\n \"Some DB Code\"\n success = True\n except:\n suc... | [
4
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0006894358_database_django_python.txt |
Q:
Mechanize: what kind of object return submit method?
My problem is that I have a form to submit, but after the submit this one redirect the user to a second page (which address is quite random) and ask for a confirmation. This second page consist of a form with only two button: Cancel and Continue. I would like to... | Mechanize: what kind of object return submit method? | My problem is that I have a form to submit, but after the submit this one redirect the user to a second page (which address is quite random) and ask for a confirmation. This second page consist of a form with only two button: Cancel and Continue. I would like to automatically submit this second form after the completio... | [
"When you use mechanize to submit the first page, it creates a response that you can capture with \nresp=br.submit()\n\nbr then opens the second page so instead of actually capturing the response, you can actually just click/submit continue depending on the input type. Good luck!\n"
] | [
0
] | [] | [] | [
"forms",
"mechanize",
"python"
] | stackoverflow_0006341219_forms_mechanize_python.txt |
Q:
Produce 10 (or less) uniformly distributed random floats using a list comprehension by filtering based on random value
For some strange reason, let's say that I want use List Comprehensions -- and List Comprehensions only -- to generate 10 random numbers larger than 0.5. For the "10 random numbers" part of the pro... | Produce 10 (or less) uniformly distributed random floats using a list comprehension by filtering based on random value | For some strange reason, let's say that I want use List Comprehensions -- and List Comprehensions only -- to generate 10 random numbers larger than 0.5. For the "10 random numbers" part of the problem we would use:
samples = [ random.random() for x in range(10) ]
Now, for the "larger than 0.5", how one would implement... | [
"What are you describing is called rejection sampling, and is a bad idea. For example if you wanted only numbers >0.999, it would take 1000 times longer to generate them.\n\nBest way\nThe correct way to do this is to use another sampling technique, such as using the inverse of the CDF (cumulative density function),... | [
6,
4,
1
] | [
"I think you mean\nsamples = [ x for x in range(10) if random.random() > 0.5 ]\n\nor \nsamples = [ (lambda r: r > 0.5 and r or 0)(random.random()) for x in range(10) ]\n\nThe second one might not be syntatically correct as i don't have python-able machine with me atm.\nEDIT:- I know this has an accepted answer and ... | [
-2
] | [
"python"
] | stackoverflow_0006894251_python.txt |
Q:
how to convert text files to pdf files without reportlab in python?
I have a problem when using reportlab and py2exe. It works normal on python but much error on reportlab modules when running the exe file after compiled by py2exe. Can you suggest a library or code in python way to convert a text files (with table... | how to convert text files to pdf files without reportlab in python? | I have a problem when using reportlab and py2exe. It works normal on python but much error on reportlab modules when running the exe file after compiled by py2exe. Can you suggest a library or code in python way to convert a text files (with tables) to pdf format without using reportlab. Thanks.
| [
"I used pyPdf in the past, which is quite good for quick and dirty solutions, though I would hesitate before using it for large projects.\n"
] | [
0
] | [] | [] | [
"py2exe",
"python",
"reportlab",
"text"
] | stackoverflow_0006894623_py2exe_python_reportlab_text.txt |
Q:
jquery lightbox with django
This may be repeated question but I am not able to solve it. I want to use jquery dialog similar to this but data is going in database instead of showing on page.
My requirement is that once I click a button from my main page, my form should open. After filling the form if I click on su... | jquery lightbox with django | This may be repeated question but I am not able to solve it. I want to use jquery dialog similar to this but data is going in database instead of showing on page.
My requirement is that once I click a button from my main page, my form should open. After filling the form if I click on submit, all form data should go to ... | [
"Well its kind of hard to tell with the limited detail, but im guessing you have th form popping up with a submit button? are you using jquery-ui? do you have ANY code written?\nWhat you could do is make a standard Django view that accepts post parameters and does all the processing you need then supply an AJAX cal... | [
1,
1
] | [] | [] | [
"django",
"jquery",
"postgresql",
"python"
] | stackoverflow_0006763801_django_jquery_postgresql_python.txt |
Q:
How to upload a file and display its information
I want to build a web service that will process some files.
Here is what I want to do:
User uploads a file to the server using "upload form", the file is saved as a temporary file on the server-side
Server-side python script processes the temporary file and produc... | How to upload a file and display its information | I want to build a web service that will process some files.
Here is what I want to do:
User uploads a file to the server using "upload form", the file is saved as a temporary file on the server-side
Server-side python script processes the temporary file and produces some statistics (for example, number of lines and w... | [
" function ajaxRequest(){\n var activexmodes=[\"Msxml2.XMLHTTP\", \"Microsoft.XMLHTTP\"] //activeX versions to check for in IE\n if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)\n for (var i=0; i<activexmodes.length; i++){\n try{\n return ne... | [
1,
0,
0
] | [] | [] | [
"ajax",
"html",
"jquery",
"php",
"python"
] | stackoverflow_0006895205_ajax_html_jquery_php_python.txt |
Q:
implement singleton with metaclass
the code below is how i implement singleton with metaclass, and it works well
class Test_MetaClass(type):
def __init__(cls, name, bases, dict):
super(Test_MetaClass, cls).__init__(cls, bases, dict)
cls._instance = None
print 'Test_MetaClass __init__'
... | implement singleton with metaclass | the code below is how i implement singleton with metaclass, and it works well
class Test_MetaClass(type):
def __init__(cls, name, bases, dict):
super(Test_MetaClass, cls).__init__(cls, bases, dict)
cls._instance = None
print 'Test_MetaClass __init__'
def __call__(cls, *args, **kwargs):... | [
"Isn't that what you wanted? cls._instance isn't None, so it won't execute type.__call__(cls, *args, **kwargs):\n>>> type.__call__(A)\nA __init__ triggered\n<__main__.A object at 0x00BADB30>\n\nIt's through this call that A.__new__ and A.__init__ get called to create/initialize a new instance. But for your singleto... | [
2
] | [] | [] | [
"metaclass",
"python",
"python_2.x"
] | stackoverflow_0006895284_metaclass_python_python_2.x.txt |
Q:
What is the solution to complex Python parameter passing requirement?
I am looking for a solution to the following complex parameter pass problem:
I want to pass function's list along with its parameters as a parameter in another function using Python. I know it is possible to pass function as a parameter,
but is ... | What is the solution to complex Python parameter passing requirement? | I am looking for a solution to the following complex parameter pass problem:
I want to pass function's list along with its parameters as a parameter in another function using Python. I know it is possible to pass function as a parameter,
but is it possible to pass lists of function and its arguments in a python?
My sam... | [
"Here is an example:\ndef f1(a):\n return a*a\n\ndef f2(a,b):\n return a*b\n\nflist = [[f1, 2], [f2, 3, 4]]\n\nprint [item[0](*item[1:]) for item in flist]\n\nthe output is:\n[4, 12]\n\n"
] | [
5
] | [] | [] | [
"parameter_passing",
"python"
] | stackoverflow_0006895433_parameter_passing_python.txt |
Q:
Is there a more efficient method to process large amounts of data than through arrays?
Hej there, I am writing a data aquisition and analysis software to a physical measurement set up with Python. In the process I gather massive amounts of data points (easily in the order of 1.000.000 or more) which I subsequently... | Is there a more efficient method to process large amounts of data than through arrays? | Hej there, I am writing a data aquisition and analysis software to a physical measurement set up with Python. In the process I gather massive amounts of data points (easily in the order of 1.000.000 or more) which I subsequently will analyze. So far I am using arrays of float numbers, which in principle do the job.
How... | [
"Do you mean lists? You can use NumPy to handle numerical arrays efficient and performant.\nFrom the NumyPy website:\n\nFirst of all, they are great for performing calculation relying\n heavily on mathematical and numerical operations. They can work\n natively with matrices and arrays, perform operations on them,... | [
5
] | [] | [] | [
"arrays",
"data_structures",
"python"
] | stackoverflow_0006895544_arrays_data_structures_python.txt |
Q:
What is the numerical method used in this implementation of IRR?
The ActiveState Recipes site has a function implementing Internal Rate of Return in Python:
def irr(cashflows, iterations=100):
"""The IRR or Internal Rate of Return is the annualized effective
compounded return rate which can be earned o... | What is the numerical method used in this implementation of IRR? | The ActiveState Recipes site has a function implementing Internal Rate of Return in Python:
def irr(cashflows, iterations=100):
"""The IRR or Internal Rate of Return is the annualized effective
compounded return rate which can be earned on the invested
capital, i.e., the yield on the investment.
... | [
"The method is called fixed point iteration; see for instance the Wikipedia article http://en.wikipedia.org/wiki/Fixed_point_iteration. \nThe idea is that if rate contains the correct value (that is, the IRR), then the NPV is zero, so the statement\nrate *= (1 - npv(rate, cashflows) / investment)\n\nwill not change... | [
4,
3,
2
] | [] | [] | [
"algorithm",
"numerical_methods",
"python"
] | stackoverflow_0006892900_algorithm_numerical_methods_python.txt |
Q:
How can I check to see if a variable exists?
I want to check if variables named component + "_STATUS" or + "_DESC" exist.
I tried the following, but it won't work. So, here's my code:
Components = ['SAVE_DOCUMENT', \
'GET_DOCUMENT', \
'DVK_SEND', \
'DVK_RECEIVE', \
'GET_USER_INFO', \
'NOTIFICATIONS', \
'ERROR_LOG... | How can I check to see if a variable exists? | I want to check if variables named component + "_STATUS" or + "_DESC" exist.
I tried the following, but it won't work. So, here's my code:
Components = ['SAVE_DOCUMENT', \
'GET_DOCUMENT', \
'DVK_SEND', \
'DVK_RECEIVE', \
'GET_USER_INFO', \
'NOTIFICATIONS', \
'ERROR_LOG', \
'SUMMARY_STATUS']
for Component in Component... | [
"I might be wrong but i think that you can do this the following way(without usign eval - because it is not a very good to use it):\nComponents = ['SAVE_DOCUMENT', 'GET_DOCUMENT', 'DVK_SEND', 'DVK_RECEIVE', 'GET_USER_INFO', 'NOTIFICATIONS', 'ERROR_LOG', 'SUMMARY_STATUS']\nmissed = [x for x in Components if x + \"_S... | [
4,
2
] | [] | [] | [
"arrays",
"python",
"variables"
] | stackoverflow_0006895748_arrays_python_variables.txt |
Q:
Mysql INTERVAL sql statement problem
I am using the the following sql in MySQL terminal and it works fine.
select * from metric_measured_value where metric_id=18 and measurement_time>(now()-INTERVAL 2 year);
However, when I used it in python code, it won't work.
res = self._db.Query("""SELECT * FROM metric_measur... | Mysql INTERVAL sql statement problem | I am using the the following sql in MySQL terminal and it works fine.
select * from metric_measured_value where metric_id=18 and measurement_time>(now()-INTERVAL 2 year);
However, when I used it in python code, it won't work.
res = self._db.Query("""SELECT * FROM metric_measured_value
... | [
"This is probably your DB access library utilizes prepared statements. INTERVAL is a MySQL keyword and it is not expected to be passed into prepared statements.\n",
"Instead of calculating the interval on the database, why not do it in python, and pass it into your measurement time.\nfrom datetime import date\nma... | [
2,
2
] | [] | [] | [
"intervals",
"mysql",
"python"
] | stackoverflow_0006895349_intervals_mysql_python.txt |
Q:
What’s the most forgiving HTML parser in Python?
I have some random HTML and I used BeautifulSoup to parse it, but in most of the cases (>70%) it chokes. I tried using Beautiful soup 3.0.8 and 3.2.0 (there were some problems with 3.1.0 upwards), but the results are almost same.
I can recall several HTML parser opt... | What’s the most forgiving HTML parser in Python? | I have some random HTML and I used BeautifulSoup to parse it, but in most of the cases (>70%) it chokes. I tried using Beautiful soup 3.0.8 and 3.2.0 (there were some problems with 3.1.0 upwards), but the results are almost same.
I can recall several HTML parser options available in Python from the top of my head:
Bea... | [
"They all are. I have yet to come across any html page found in the wild that lxml.html couldn't parse. If lxml barfs on the pages you're trying to parse you can always preprocess them using some regexps to keep lxml happy.\nlxml itself is fairly strict, but lxml.html is a different parser and can deal with very br... | [
3,
2,
2,
1
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"lxml",
"pyquery",
"python"
] | stackoverflow_0006870446_beautifulsoup_html_parsing_lxml_pyquery_python.txt |
Q:
How can I count words frequency (one per line) in huge file (2 gb)?
I am trying to write a program to create a 2gb (approximately) sized file of English words. And from this 2gb file trying to print the frequency of words using external sorting. After external sorting it can just print the count(frequency)
A:
Py... | How can I count words frequency (one per line) in huge file (2 gb)? | I am trying to write a program to create a 2gb (approximately) sized file of English words. And from this 2gb file trying to print the frequency of words using external sorting. After external sorting it can just print the count(frequency)
| [
"Python has a built-in function sorted which sorts an iterable. But even better than that, in versions 2.7 and greater it has a built-in collection for counting the frequencies of things. Assuming your large file has one word per line, you can do:\nfrom collections import Counter\nwith open(<giant-dictionary>) as w... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006896349_python.txt |
Q:
Using Objective C function call styles in Python
I know that this question will recieve some fairly strong comments but I'm going to post it anyway.
I'm working on a project in Python. My simple reasons for choosing Python are the available librtaries and it is cross platform and open source. My problem is that I... | Using Objective C function call styles in Python | I know that this question will recieve some fairly strong comments but I'm going to post it anyway.
I'm working on a project in Python. My simple reasons for choosing Python are the available librtaries and it is cross platform and open source. My problem is that I really enjoy coding with the very verbose, descriptiv... | [
"If you mean, \"can I write the call with square brackets instead of round ones and put them around the object and method names instead of after and omit the commas\", then no.\nIf you mean \"can I make verbose, descriptive method names\", then of course you can; you can do that in any language worth mentioning.\nI... | [
4
] | [] | [] | [
"coding_style",
"objective_c",
"python"
] | stackoverflow_0006896565_coding_style_objective_c_python.txt |
Q:
Django how to validate requested URL against a choices field?
I have a choice field in one of my models in an app I am writing. It looks, for arguments sake, like:
MANUFACTURERS = (
('sk','skoda')
('vw','volkswagen')
)
class car(models.Model):
manufacturer = models.CharField(max_length='2', choices=MAN... | Django how to validate requested URL against a choices field? | I have a choice field in one of my models in an app I am writing. It looks, for arguments sake, like:
MANUFACTURERS = (
('sk','skoda')
('vw','volkswagen')
)
class car(models.Model):
manufacturer = models.CharField(max_length='2', choices=MANUFACTURERS)
Now, I want to create a view to list all the cars by a... | [
"What I would do is to make a dict out of the possible manufacturers, for example:\nfrom mymodel import MANUFACTURERS\nmdict = dict(MANUFACTURERS)\n\n\ndef myview(request, manufacturer):\n if not (manufacturer in mdict):\n raise Http404\n\n #--> do what you need to do\n\nThis way you are looking on the... | [
2,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0006893473_django_django_views_python.txt |
Q:
Trying to combine this list of unicode strings
Trying to combine this list of unicode strings. I've tried both using sum as well as using join. No luck.
Any idea how I can do this? I just want a plain text output of all of these strings as one large string.
[u'\nPanera Bread (NASDAQ: <a class="ticker" href="/stock... | Trying to combine this list of unicode strings | Trying to combine this list of unicode strings. I've tried both using sum as well as using join. No luck.
Any idea how I can do this? I just want a plain text output of all of these strings as one large string.
[u'\nPanera Bread (NASDAQ: <a class="ticker" href="/stock/pnra#NASDAQ">PNRA</a>) is down 6 percent today over... | [
"Use unicode.join.\nu''.join(that_list)\n\n",
"\nI've tried both using sum as well as using join. No luck.\n\n?\n''.join(the_list) works fine for me.\n",
"May be this help same one but with replace\n''.join(ur_list).replace('\\n','')\n\n"
] | [
9,
1,
0
] | [] | [] | [
"python",
"string",
"unicode"
] | stackoverflow_0006892585_python_string_unicode.txt |
Q:
oauth , python and google API?
Best way to authentiacte google API using Python?
1) oauth
2) AuthSub
Is there any tutorials for oauth2.o + python + google
A:
You can try: https://bitbucket.org/smartproject/oauth2python
It is well tested and documented library. It runs smoothly on google app engine.
Demo that c... | oauth , python and google API? | Best way to authentiacte google API using Python?
1) oauth
2) AuthSub
Is there any tutorials for oauth2.o + python + google
| [
"You can try: https://bitbucket.org/smartproject/oauth2python\nIt is well tested and documented library. It runs smoothly on google app engine.\nDemo that connects with Google and Facebook: http://esmeoauth.appspot.com/\n",
"why you would write full separate code in python ? there is already a module of python wh... | [
1,
0
] | [] | [] | [
"api",
"oauth_2.0",
"python"
] | stackoverflow_0006884890_api_oauth_2.0_python.txt |
Q:
write data output in specific format python
How can I get data from this
100 Aktiva
110 Aktiva Lancar
111 Kas
112 Piutang Usaha
113 Piutang Gaji
120 Aktiva Tetap / Inventaris
121 Tanah ... | write data output in specific format python | How can I get data from this
100 Aktiva
110 Aktiva Lancar
111 Kas
112 Piutang Usaha
113 Piutang Gaji
120 Aktiva Tetap / Inventaris
121 Tanah
122 Kendaraan
to output ... | [
"data = [\n (100, 'Aktiva'),\n (110, 'Aktiva Lancar'),\n (111, 'Kas'),\n (112, 'Piutang Usaha'),\n (113, 'Piutang Gaji'),\n (120, 'Aktiva Tetap / Inventaris'),\n (121, 'Tanah'),\n (122, 'Kendaraan'),\n (200, 'Pasiva') ]\n\ndef rzeros(a):\n ''' count number of zeros from right '''\n return len(a)-len(... | [
2,
2,
0,
0
] | [] | [] | [
"python",
"string",
"tuples"
] | stackoverflow_0006896589_python_string_tuples.txt |
Q:
python/tkinter: is it possible to copy paste text AND tags?
in my Text widget I have here and there many tags, taking care of the text appearance (bold, italic etc).
Tkinter takes care by default of cut/copy/paste in the text widget, but only of the text content, not of the associated tags. Do you know if it is po... | python/tkinter: is it possible to copy paste text AND tags? | in my Text widget I have here and there many tags, taking care of the text appearance (bold, italic etc).
Tkinter takes care by default of cut/copy/paste in the text widget, but only of the text content, not of the associated tags. Do you know if it is possible to implement it?
I anticipate some problems if I would cut... | [
"Yes, it's possible to implement it. You can use the dump method of the text widget to get all the text and tags in a given range. To paste, you just have to use that information when inserting the text.\nIt gets somewhat complicated when you try to paste, say, italic text inside a range of already bolded text sinc... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006895545_python_tkinter.txt |
Q:
Which python mpi library to use?
I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy site lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.
A:
I have heard good things about mpi4py (bu... | Which python mpi library to use? | I'm starting work on some simulations using MPI and want to do the programming in Python/scipy. The scipy site lists a number of mpi libraries, but I was hoping to get feedback on quality, ease of use, etc from anyone who has used one.
| [
"I have heard good things about mpi4py (but I have never used it myself). That's what a colleague recommended who looked at all the alternatives. He mentioned the completeness as one advantage.\n",
"Also check whether pymw (master/worker framework) might help you. It supports various backends (MPI via pympi, Boin... | [
15,
4,
2
] | [] | [] | [
"mpi",
"python"
] | stackoverflow_0001422260_mpi_python.txt |
Q:
How to pickle several .txt files into one pickle
I need to overcome some cPickle constrains,
namely i need to open several files and pickle them to one file, like this:
import cPickle
file1=open('file1.txt','r')
file2=open('file2.txt','r')
obj=[file1,file2] or obj=[file1.read(), file2.read()]
cPickle.dump(obj,ope... | How to pickle several .txt files into one pickle | I need to overcome some cPickle constrains,
namely i need to open several files and pickle them to one file, like this:
import cPickle
file1=open('file1.txt','r')
file2=open('file2.txt','r')
obj=[file1,file2] or obj=[file1.read(), file2.read()]
cPickle.dump(obj,open('result.i2','w'),2)
so that later I can "repickle" ... | [
"This is the correct way, it pickles the file contents:\nfile1=open('file1.txt','r')\nfile2=open('file2.txt','r')\nobj=[file1.read(), file2.read()]\ncPickle.dump(obj,open('result.i2','w'),2)\n\nIf you set obj=[file1,file2] you are not pickling the file contents, you are pickling the file handles.\n",
"Proper code... | [
3,
2
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0006884903_pickle_python.txt |
Q:
Saving stdout from subprocess.Popen to file line by line
My python script uses subprocess to call an another script, which produces output very slow(line-by-line basis). I would like to write the output line by line to file not when the whole process ends and writes the entire output as string.The following code w... | Saving stdout from subprocess.Popen to file line by line | My python script uses subprocess to call an another script, which produces output very slow(line-by-line basis). I would like to write the output line by line to file not when the whole process ends and writes the entire output as string.The following code writes the output to "file" when the "script" ends.
args = ("... | [
"You can interact with the process using poll so that you can attempt to interact with it line by line:\nFor example:\nprocess = subprocess.Popen([\"ls\", \"-lart\"],\n bufsize=-1, # fully buffered (default)\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n ... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0005171317_python_subprocess.txt |
Q:
how to stop the matplotlib GUI thread from freezing up?
from matplotlib import pyplot as p
from scipy import zeros
from Queue import Queue
import random
w,h = 320,200
black = zeros((h,w,3), dtype='uint8')
red = black.copy(); red[:,:,0] = 255
green = black.copy(); green[:,:,1] = 255
blue = black.copy(); blue[:,:,... | how to stop the matplotlib GUI thread from freezing up? | from matplotlib import pyplot as p
from scipy import zeros
from Queue import Queue
import random
w,h = 320,200
black = zeros((h,w,3), dtype='uint8')
red = black.copy(); red[:,:,0] = 255
green = black.copy(); green[:,:,1] = 255
blue = black.copy(); blue[:,:,2] = 255
def ants():
from scipy import rand, dstack
retu... | [
"To avoid freezing the GUI, you need to run update_image in a separate thread or process. Using threading, you might do something like this:\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as p\nfrom scipy import zeros\nimport random\nimport threading\n\n\nw,h = 320,200\n\nblack = zeros((... | [
2
] | [] | [] | [
"matplotlib",
"multithreading",
"python",
"user_interface"
] | stackoverflow_0006895776_matplotlib_multithreading_python_user_interface.txt |
Q:
Breaking a string into individual words in Python
I have a large list of domain names (around six thousand), and I would like to see which words trend the highest for a rough overview of our portfolio.
The problem I have is the list is formatted as domain names, for example:
examplecartrading.com
examplepensions.c... | Breaking a string into individual words in Python | I have a large list of domain names (around six thousand), and I would like to see which words trend the highest for a rough overview of our portfolio.
The problem I have is the list is formatted as domain names, for example:
examplecartrading.com
examplepensions.co.uk
exampledeals.org
examplesummeroffers.com
+5996
... | [
"We try to split the domain name (s) into any number of words (not just 2) from a set of known words (words). Recursion ftw!\ndef substrings_in_set(s, words):\n if s in words:\n yield [s]\n for i in range(1, len(s)):\n if s[:i] not in words:\n continue\n for rest in substrings_... | [
6,
1,
1
] | [] | [] | [
"python",
"string",
"trie"
] | stackoverflow_0006897214_python_string_trie.txt |
Q:
How is it possible to cook up data attributes for an object on the fly?
Dive into Python: HTTP Web Services -
class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
def http_error_default(self, req, fp, code, msg, headers):
result = urllib2.HTTPError(
req.get_full_url(), code, msg, he... | How is it possible to cook up data attributes for an object on the fly? | Dive into Python: HTTP Web Services -
class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler):
def http_error_default(self, req, fp, code, msg, headers):
result = urllib2.HTTPError(
req.get_full_url(), code, msg, headers, fp)
result.status = code
return result
HTTPError obje... | [
"Python has a different notion of data types than C or Java. Python does not allocate memory for the data members of an instance if it is created. Instead, when an instance is created, it gets an __dict__ attribute pointing to a dictionary mapping attribute names to values. This dictionary is as dynamic as any s... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006898141_python.txt |
Q:
Confused about Python's with statement
I saw some code in the Whoosh documentation:
with ix.searcher() as searcher:
query = QueryParser("content", ix.schema).parse(u"ship")
results = searcher.search(query)
I read that the with statement executes __ enter__ and __ exit__ methods and they are really useful ... | Confused about Python's with statement | I saw some code in the Whoosh documentation:
with ix.searcher() as searcher:
query = QueryParser("content", ix.schema).parse(u"ship")
results = searcher.search(query)
I read that the with statement executes __ enter__ and __ exit__ methods and they are really useful in the forms "with file_pointer:" or "with l... | [
"Example straight from PEP-0343:\nwith EXPR as VAR:\n BLOCK\n\n#translates to:\n\nmgr = (EXPR)\nexit = type(mgr).__exit__ # Not calling it yet\nvalue = type(mgr).__enter__(mgr)\nexc = True\ntry:\n try:\n VAR = value # Only if \"as VAR\" is present\n BLOCK\n except:\n # The exceptional... | [
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0006898257_python.txt |
Q:
run django from ssh
i want to create a django project using ssh, my host give me some options when i enable ssh, i'm allowed to use bash, zsh, ksh, csh,fish and tcsh, I'm familiar with bash but not with the rest so which is better for django? which is the closest to python? or are they all the same when it comes t... | run django from ssh | i want to create a django project using ssh, my host give me some options when i enable ssh, i'm allowed to use bash, zsh, ksh, csh,fish and tcsh, I'm familiar with bash but not with the rest so which is better for django? which is the closest to python? or are they all the same when it comes to application development... | [
"The chosen UNIX shell does not matter for the Python development. AFAIK the only shell specific part in Python development, which is currently being widely used, is virtualenv and it should work with sh compatible shells.\n"
] | [
2
] | [] | [] | [
"bash",
"django",
"python",
"ssh"
] | stackoverflow_0006892686_bash_django_python_ssh.txt |
Q:
How to return the value of a recursive function
I have recursive function which walk nested dict and return needed key's value:
def recurs(l):
for key in l.keys():
if key == '_events':
return l[key]
else:
recurs(l[key])
c=recurs(d)
print c
And how i can get these value... | How to return the value of a recursive function | I have recursive function which walk nested dict and return needed key's value:
def recurs(l):
for key in l.keys():
if key == '_events':
return l[key]
else:
recurs(l[key])
c=recurs(d)
print c
And how i can get these values?
| [
"The easiest way to get a flattened iterator is to write a generator function:\ndef recurs(l):\n for key in l.keys():\n if key == '_events':\n yield l[key]\n else:\n for x in recurs(l[key]):\n yield x\n\n",
"Just return it:\ndef recurs(l):\n for key in l.ke... | [
3,
1
] | [] | [] | [
"dictionary",
"python",
"recursion"
] | stackoverflow_0006898544_dictionary_python_recursion.txt |
Q:
'NoneType' object has no attribute 'title'
Code:
class trafikformu(db.Model):
title = db.StringProperty()
class QueryHandler(webapp.RequestHandler):
def get(self,id):
v = form.get_by_id(int(id))
self.response.out.write(v.title) # AttributeError
The line self.response.out.write(v.title) g... | 'NoneType' object has no attribute 'title' | Code:
class trafikformu(db.Model):
title = db.StringProperty()
class QueryHandler(webapp.RequestHandler):
def get(self,id):
v = form.get_by_id(int(id))
self.response.out.write(v.title) # AttributeError
The line self.response.out.write(v.title) gives this error: 'NoneType' object has no attrib... | [
"The function form.get_by_id(int(id)) returned None for the given id, so v has no attribute title since it is None.\n"
] | [
7
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006898885_google_app_engine_python.txt |
Q:
Select a range of dates in Python dictionary
I have the following dictionary:
history = {
"2008-11-17": 41,
"2010-05-28": 82,
"2008-11-14": 47,
"2008-11-13": 60,
"2008-11-12": 56,
"2008-11-11": 55,
"2008-11-10": 98,
"2008-11-19": 94,
"2008-11-18": 94,
"2004-05-27": 82,
"2004-05-26": 45,
"2004-05-25": 70... | Select a range of dates in Python dictionary | I have the following dictionary:
history = {
"2008-11-17": 41,
"2010-05-28": 82,
"2008-11-14": 47,
"2008-11-13": 60,
"2008-11-12": 56,
"2008-11-11": 55,
"2008-11-10": 98,
"2008-11-19": 94,
"2008-11-18": 94,
"2004-05-27": 82,
"2004-05-26": 45,
"2004-05-25": 70,
# there's more ...
}
How do I define a generato... | [
"I'd just iterate over the dictionary and return the items that match:\ndef get_records(history, start_date, end_date):\n for date, entry in history.iteritems():\n if start_date <= date <= end_date:\n yield date, entry\n\nNote that your particular date format allows direct string comparison wi... | [
6,
0,
0,
0,
0
] | [] | [] | [
"date",
"dictionary",
"python",
"range"
] | stackoverflow_0006899101_date_dictionary_python_range.txt |
Q:
Python urllib2 parse html problem
I am using mechanize to parse html of website, but with this website i got strange result.
from mechanize import Browser
br = Browser()
r = br.open("http://www.heavenplaza.com")
result = r.read()
result is something which i can not understand. you can see here: http://paste2.org/... | Python urllib2 parse html problem | I am using mechanize to parse html of website, but with this website i got strange result.
from mechanize import Browser
br = Browser()
r = br.open("http://www.heavenplaza.com")
result = r.read()
result is something which i can not understand. you can see here: http://paste2.org/p/1556077
Anyone can have some method t... | [
"I quickly checked the script in the console and the site was returning crap. You probably need to spoof your HTTP user agent to be something else that the site doesn't think you are using a robot.\nhttp://www.google.com works\n",
"import urllib2, StringIO, gzip\nf = urllib2.urlopen(\"http://www.heavenplaza.com\"... | [
1,
1
] | [] | [] | [
"mechanize",
"python",
"urllib",
"urllib2"
] | stackoverflow_0006899273_mechanize_python_urllib_urllib2.txt |
Q:
Low memory consumption watermarking for Python
I'm trying to add an image watermark to images (image sizes can go up to 2.5MB), but my current solutions require a larger amount of memory - at the moment I'm using https://bitbucket.org/codekoala/django-watermark.
Because of the 60MB memory limit define by my hostin... | Low memory consumption watermarking for Python | I'm trying to add an image watermark to images (image sizes can go up to 2.5MB), but my current solutions require a larger amount of memory - at the moment I'm using https://bitbucket.org/codekoala/django-watermark.
Because of the 60MB memory limit define by my hosting, I'm getting MemoryError errors.
It could be a me... | [
"Python offers little ready / productized tools for progressive image processing. My recommendation way is simply to move a hosting where you can safely decompress a full image to the memory. This does not go for Python, but for other platforms as well generally.\nThe only thing which can be buffered with PIL is lo... | [
1
] | [] | [] | [
"memory_management",
"python",
"watermark"
] | stackoverflow_0006899036_memory_management_python_watermark.txt |
Q:
Put a digital clock in a pygtk window
Hello,
I have this code for a digital clock with TKinter:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import Tkinter
import time
def tick(time_old, clock):
# get the current local time from the PC
time_now = time.strftime('%H:%M:%S')
# if time string has changed, u... | Put a digital clock in a pygtk window | Hello,
I have this code for a digital clock with TKinter:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import Tkinter
import time
def tick(time_old, clock):
# get the current local time from the PC
time_now = time.strftime('%H:%M:%S')
# if time string has changed, update it
if time_now != time_old:
... | [
"If I got you right, here's the code that will do the trick:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\nimport time\n\nclass Clock:\n\n def __init__(self):\n window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n window.connect(\"destroy\", lambda w: gtk... | [
4,
0
] | [] | [] | [
"clock",
"glade",
"pygtk",
"python"
] | stackoverflow_0006892893_clock_glade_pygtk_python.txt |
Q:
Getting a more useful 'logging' module error output in python
I am using the logger module of python (python version 3.x, but it should not matter) and I noticed that an error in a format string is reported as such:
Traceback (most recent call last):
File "/usr/lib/python3.1/logging/__init__.py", line 770, in em... | Getting a more useful 'logging' module error output in python | I am using the logger module of python (python version 3.x, but it should not matter) and I noticed that an error in a format string is reported as such:
Traceback (most recent call last):
File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
msg = self.format(record)
File "/usr/lib/python3.1/logging... | [
"If I understand you properly, the problem here is that the traceback does not give you any indication from where in your code the error originates. Somehow you had to track down the line\nlogging.debug('This is a string %d', str(foo))\n\nyourself. \nThe logging module was designed so that exceptions that occur dur... | [
3,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006898674_python_python_3.x.txt |
Q:
Passing kwargs into a python string for rendering rather then using %s/%d...etc
About a week ago I saw a script using kwargs in the string template. Unfortunately I can't re-find that script so I thought I'd ask to see if anyone knows of a way that I can pass kwargs into the string builder rather then just args.
H... | Passing kwargs into a python string for rendering rather then using %s/%d...etc | About a week ago I saw a script using kwargs in the string template. Unfortunately I can't re-find that script so I thought I'd ask to see if anyone knows of a way that I can pass kwargs into the string builder rather then just args.
Here is the desired result:
"""%name went to the store.""" %( name = John )
Naturally... | [
"\"\"\"%(name)s went to the store.\"\"\" % {\"name\": \"John\"}\n\nor\n\"\"\"%(name)s went to the store.\"\"\" % dict(name=\"John\")\n\n"
] | [
3
] | [] | [] | [
"python",
"string",
"templates"
] | stackoverflow_0006899633_python_string_templates.txt |
Q:
How to override a field in the parent class
I have parent and child classes in Django model. And I want to fill a field in parent class when initialize child class. Or override this field in child class.
class Parent(models.Model):
type = models.CharField()
class Child(Parent):
type = mod... | How to override a field in the parent class | I have parent and child classes in Django model. And I want to fill a field in parent class when initialize child class. Or override this field in child class.
class Parent(models.Model):
type = models.CharField()
class Child(Parent):
type = models.CharField() //Doesn't work
Also trying over... | [
"\nIn normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called ... | [
16
] | [] | [] | [
"class",
"django",
"overriding",
"python"
] | stackoverflow_0006897730_class_django_overriding_python.txt |
Q:
Quickhelp for Python in Emacs autocomplete.el?
I am using Emacs 23.1.1 on GNU/Linux with autocomplete.el 1.3 and Ropemacs 0.6.
In Lisp programming, autocomplete.el shows the documentation (known as 'QuickHelp' in autocomplete.el) of the suggested completions. Python completion with ropemacs works, but does not sho... | Quickhelp for Python in Emacs autocomplete.el? | I am using Emacs 23.1.1 on GNU/Linux with autocomplete.el 1.3 and Ropemacs 0.6.
In Lisp programming, autocomplete.el shows the documentation (known as 'QuickHelp' in autocomplete.el) of the suggested completions. Python completion with ropemacs works, but does not show quick help for the Python completion. Is it possib... | [
"Ropemacs does the job : Use the function rope-show-doc over the symbol or use the keybinding C-c d. Simple :)\n",
"I stopped using all the autocomplete stuff in all my developing environments. They rarely do what I want. Either the lists is too long, or too short, or not sorted well. Therefore I use dabbrev-expa... | [
3,
1
] | [] | [] | [
"emacs",
"python"
] | stackoverflow_0003506105_emacs_python.txt |
Q:
Why does Celery work in Python shell, but not in my Django views? (import problem)
I installed Celery (latest stable version.)
I have a directory called /home/myuser/fable/jobs. Inside this directory, I have a file called tasks.py:
from celery.decorators import task
from celery.task import Task
class Submitter(T... | Why does Celery work in Python shell, but not in my Django views? (import problem) | I installed Celery (latest stable version.)
I have a directory called /home/myuser/fable/jobs. Inside this directory, I have a file called tasks.py:
from celery.decorators import task
from celery.task import Task
class Submitter(Task):
def run(self, post, **kwargs):
return "Yes, it works!!!!!!"
Inside th... | [
"This is what I did which finally worked \nin Settings.py I added \nCELERY_IMPORTS = (\"myapp.jobs\", )\n\nunder myapp folder I created a file called jobs.py\nfrom celery.decorators import task\n\n@task(name=\"jobs.add\")\ndef add(x, y):\n return x * y\n\nThen ran from commandline: python manage.py celeryd -l i... | [
11,
10,
5
] | [] | [] | [
"celery",
"django",
"import",
"python",
"unix"
] | stackoverflow_0004643065_celery_django_import_python_unix.txt |
Q:
Delete duplicates in list structure (python)
I have the following structure in python:
revisions = [
['01.02.2010','abc','qwe'],
['02.02.2010','abc','qwe'],
['03.02.2010','aaa','qwe'],
['04.02.2010','aaa','qwe'],
['05.02.2010','aaa','qwe'],
['06.02.2010','aaa','dsa'],
]
how can i remove the duplicates with minimu... | Delete duplicates in list structure (python) | I have the following structure in python:
revisions = [
['01.02.2010','abc','qwe'],
['02.02.2010','abc','qwe'],
['03.02.2010','aaa','qwe'],
['04.02.2010','aaa','qwe'],
['05.02.2010','aaa','qwe'],
['06.02.2010','aaa','dsa'],
]
how can i remove the duplicates with minimum algorithmic complexity? Output example:
revisio... | [
"A crude approach (while guessing what you're trying to do):\n#!/usr/bin/env python\n\nimport pprint\n\nrevisions = [\n ['01.02.2010','abc','qwe'],\n ['02.02.2010','abc','qwe'],\n ['03.02.2010','aaa','qwe'],\n ['04.02.2010','aaa','qwe'],\n ['05.02.2010','aaa','qwe'],\n ['06.02.2010','aaa','dsa'],\... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006899665_python.txt |
Q:
Python + Django vs. ASP.NET + C#/VB vs PHP?
I know similar questions to this have been asked before, but I'm looking for a more specific answer so here it goes:
I'm a student and am looking to develop a web app. I have little experience with all mentioned and like different aspects of each. I like the Visual Web ... | Python + Django vs. ASP.NET + C#/VB vs PHP? | I know similar questions to this have been asked before, but I'm looking for a more specific answer so here it goes:
I'm a student and am looking to develop a web app. I have little experience with all mentioned and like different aspects of each. I like the Visual Web Dev that can be used to create ASP.NET sites, a a... | [
"This question is really too open ended. there is no one true language, otherwise we'd all be using it. As you've seen they all have merit. You didn't mention Java which still holds a lot of clout in enterprise computing.\nThe only answer is pick one you like and get good at it. You can spends years wishing you'd p... | [
1,
1,
0
] | [] | [] | [
"asp.net",
"django",
"php",
"python"
] | stackoverflow_0006896942_asp.net_django_php_python.txt |
Q:
Data plotting in boxes with python
I have an array
d[0:100]
which is defined in boxes (or cells) whose center are stored in these two arrays
x[0:100]
y[0:100]
and whose size is
h[0:100]
I wish I could plot an image showing boxes/cells colored according to the value of the array defined in each of them.... | Data plotting in boxes with python | I have an array
d[0:100]
which is defined in boxes (or cells) whose center are stored in these two arrays
x[0:100]
y[0:100]
and whose size is
h[0:100]
I wish I could plot an image showing boxes/cells colored according to the value of the array defined in each of them. It seems and histogram but it is not. D... | [
"Given the desire to draw squares with area h**2 and a color based on the value in d, you could draw rectangles using matplotlib with a color obtained from a colormap (scaled to 0-1):\nimport pylab\nimport numpy as np\nimport matplotlib as mpl\nimport random\nimport matplotlib.cm as cm\n\nmy_cmap = cm.bone\n\ndef m... | [
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006895935_matplotlib_python.txt |
Q:
Should I also parse mandatory arguments with getopt(...)
"""
Saves a dir listing in a file
Usage: python listfiles.py -d dir -f filename [flags]
Arguments:
-d, --dir dir; ls of which will be saved in a file
-f, --file filename (if existing will be overwritten)
Flags:
-h, --help ... | Should I also parse mandatory arguments with getopt(...) | """
Saves a dir listing in a file
Usage: python listfiles.py -d dir -f filename [flags]
Arguments:
-d, --dir dir; ls of which will be saved in a file
-f, --file filename (if existing will be overwritten)
Flags:
-h, --help show this help
-v, --verbose be verbose... | [
"the getopt module is only for those users who are already familiar with the same module in C, the python standard argument handling is argparse.\n",
"\"Mandatory Options\" is a contradiction, and is not generally well supported by the various option parsing libraries; You should consider placing mandatory argum... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0006892036_python.txt |
Q:
Use of type() for method calls
Why does PEP-343 use type() in this situation here?
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
Couldn't we just as well use exit = mgr.__exit__ and value = mgr.__enter__()? Seems simpler to me, but I assume I'm missing s... | Use of type() for method calls | Why does PEP-343 use type() in this situation here?
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
Couldn't we just as well use exit = mgr.__exit__ and value = mgr.__enter__()? Seems simpler to me, but I assume I'm missing something.
| [
"Of course the PEP could use attributes of the instance itself instead of attributes of the type, but this would be in contrast to the use of special methods in Python. For example\na + b\n\nis translated to\ntype(a).__add__(a, b)\n\nand not to\na.__add__(b)\n\nas shown by the following example:\n>>> class MyInt(i... | [
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0006900283_python.txt |
Q:
Python: apply list in nested function call
I have two def functions that I call in a nested fashion and want to call the second in a loop. I currently can only figure out the syntax for how to call my list manually, rather than applying each member of the list...
#A list of the files I want to read
afiles = [['awc... | Python: apply list in nested function call | I have two def functions that I call in a nested fashion and want to call the second in a loop. I currently can only figure out the syntax for how to call my list manually, rather than applying each member of the list...
#A list of the files I want to read
afiles = [['awc_mm09c.txt','integer'], ['canopy01c.txt','real']... | [
"Replace the call to rows() by\nrows(*(readfile(x[0]) for x in afiles))\n\n",
"You simply need to move 'readfile(afiles[i][0])' before 'for' - because that is the way list comprehension works in python. You can update your code the following way:\nc.executemany(strQuery, rows(*[readfile(afiles[i][0]) for i in xra... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006900500_python.txt |
Q:
Python function composition (max recursion depth error, scope?)
What is wrong with this function? It seems like a scope error (although I thought I had fixed that by placing each callable in the list, instead of using it directly). Error is max recursion depth reached (when calling comp(inv,dbl,inc))...
Note: the ... | Python function composition (max recursion depth error, scope?) | What is wrong with this function? It seems like a scope error (although I thought I had fixed that by placing each callable in the list, instead of using it directly). Error is max recursion depth reached (when calling comp(inv,dbl,inc))...
Note: the question is: why is it even recursing, not why it's reaching the max ... | [
"The lambda function you create builds a closure over the composed variable:\ncomposed.append(lambda *args, **kwargs: func(composed[-1](*args,**kwargs)))\n\nThis means that composed[-1] isn't evaluated when you create the lambda function, but when you call it. The effect is, that composed[-1] will be calling itself... | [
5,
1
] | [] | [] | [
"composition",
"function_composition",
"functional_programming",
"python",
"recursion"
] | stackoverflow_0006900241_composition_function_composition_functional_programming_python_recursion.txt |
Q:
Django query optimization: retrieve values in groups possible?
I have:
active = Node.objects.filter(status = 'a')
potential = Node.objects.filter(status = 'p')
hotspot = Node.objects.filter(status = 'h')
I'm wondering: is it's possible to do it in a better way?
EDIT: maybe i didn't explain myself very well. I nee... | Django query optimization: retrieve values in groups possible? | I have:
active = Node.objects.filter(status = 'a')
potential = Node.objects.filter(status = 'p')
hotspot = Node.objects.filter(status = 'h')
I'm wondering: is it's possible to do it in a better way?
EDIT: maybe i didn't explain myself very well. I need to have 3 lists with the 3 different status. If I do just 1 query ... | [
"Even better, use in:\nNode.objects.filter(status__in=['a', 'p', 'h'])\n\nEdit after comment Don't know why that would be inefficient. Perhaps one improvement would be to add .order_by('status') so you get an ordered queryset, then split when you iterate through. Likely to be a micro-optimization though.\n",
"Tak... | [
2,
1
] | [] | [] | [
"django",
"django_orm",
"django_queryset",
"python"
] | stackoverflow_0006899867_django_django_orm_django_queryset_python.txt |
Q:
parsing xml in python
I want to parse text from a xml file.Consider that I have a some lines in a file.xml
<s id="1792387-2">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>
How can I extract the following text from the abov... | parsing xml in python | I want to parse text from a xml file.Consider that I have a some lines in a file.xml
<s id="1792387-2">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>
How can I extract the following text from the above line:
Castro Verde is sit... | [
"LXML makes this particularly easy.\n>>> from lxml import etree\n>>> text = '''<s id=\"1792387-2\">Castro Verde is situated in the Baixo Alentejo Subregion within a territory known locally as the Campo Branco (English: White Plains).</s>'''\n>>> def edit(s):\n... return 'Changed Text'\n... \n>>> t = etree.froms... | [
5,
4,
1
] | [] | [] | [
"python",
"xml_parsing"
] | stackoverflow_0006900595_python_xml_parsing.txt |
Q:
How can I write multiple lines to a textbox using python win32?
I have a C program that has a textbox component. I want to have a python GUI write text to this text box. Currently, I can write to the textbox HWND using:
def winFunc(hwnd, lparam):
s = win32gui.GetWindowText(hwnd)
if s == "":
win32gu... | How can I write multiple lines to a textbox using python win32? | I have a C program that has a textbox component. I want to have a python GUI write text to this text box. Currently, I can write to the textbox HWND using:
def winFunc(hwnd, lparam):
s = win32gui.GetWindowText(hwnd)
if s == "":
win32gui.SendMessage(hwnd, win32con.WM_SETTEXT, 0, lparam)
hwnd = win32gui.... | [
"Appending text\n\nSend an EM_SETSEL message to move the selection to the end of the rich edit control. Use WM_GETTEXTLENGTH to find out how many characters are in the edit control.\nSend an EM_REPLACESEL message to replace the selection. If the selection point is at the end of the control, then replacing is the sa... | [
1
] | [] | [] | [
"c",
"python",
"textbox",
"winapi"
] | stackoverflow_0006900660_c_python_textbox_winapi.txt |
Q:
pareto ranking using Pyevolve
I am currently using Pyevolve package to solve some Genetic Algorithms problems. I am wondering is there any examples using Pareto ranking in Pyevolve package, since I have multi evaluation functions.
If not exists, could you plz provides some pseudo code of Pareto ranking algorithms.... | pareto ranking using Pyevolve | I am currently using Pyevolve package to solve some Genetic Algorithms problems. I am wondering is there any examples using Pareto ranking in Pyevolve package, since I have multi evaluation functions.
If not exists, could you plz provides some pseudo code of Pareto ranking algorithms. I want to implement it by myself.
... | [
"Based on the last release documentation there effectively doesn't seem to be any Pareto ranking package in Pyevolve.\nIf you want to implement it yourself, you should check NSGA-II which is one most well known and best working algorithm for multi-objective optimization. The original article, containing pseudocode,... | [
6
] | [] | [] | [
"evolutionary_algorithm",
"genetic_algorithm",
"pyevolve",
"python"
] | stackoverflow_0006898100_evolutionary_algorithm_genetic_algorithm_pyevolve_python.txt |
Q:
Consistent application of stuff on __init__ with SqlAlchemy
Suppose I have something like this:
class Tab(Base):
a = 'a'
b = 'b'
c = 'c'
def __init__(self):
self.c_a = DBSession.query(Table2).filter(Table2.a == self.a).all()
It seems that self.c_a is only applied on items I insert. I want to ensure t... | Consistent application of stuff on __init__ with SqlAlchemy | Suppose I have something like this:
class Tab(Base):
a = 'a'
b = 'b'
c = 'c'
def __init__(self):
self.c_a = DBSession.query(Table2).filter(Table2.a == self.a).all()
It seems that self.c_a is only applied on items I insert. I want to ensure that the operations specified in __init__ (this is just an example... | [
"referencing the database from inside the model is an abstraction leak; models shouldn't have to know about the particulars of the persistence they may reside on; they might not be persistent at all (they are, after all, models, and might be used for any sort of computation.)\nWhen trying to make associations to o... | [
5,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0006886608_python_sqlalchemy.txt |
Q:
PyQT QPushButton.setMenu? How to make it work?
im just a beginner in PyQT.
and im not sure if my thread title is the correct thing to put for my problem.
im having a problem creating a popmenu on a Qpushbutton.
based on the doc of QT docs
i need to make a QPushButton.setMenu (self, QMenu menu)
but i really dont kn... | PyQT QPushButton.setMenu? How to make it work? | im just a beginner in PyQT.
and im not sure if my thread title is the correct thing to put for my problem.
im having a problem creating a popmenu on a Qpushbutton.
based on the doc of QT docs
i need to make a QPushButton.setMenu (self, QMenu menu)
but i really dont know where to start.. i cant find a sample on how to u... | [
"The basic idea is that you first have to create a QMenu, then use the setMenu method to attach it to your push button. If you look at the QMenu documentation, you'll see that there is a method called addAction that will add menu items to your newly created QMenu. addAction is overloaded, so there are a lot of di... | [
11
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0006893923_pyqt_pyqt4_python.txt |
Q:
Error in Exception handling in Python script
m = ldap.initialize(server)
try:
m.start_tls_s()
except ldap.LDAPError, e:
print e
This part of a python script. I am getting the error in the line "except ldap.LDAPError, e:". But it seems to be right. Can anyone help?
Thanks!
A:
If you u... | Error in Exception handling in Python script | m = ldap.initialize(server)
try:
m.start_tls_s()
except ldap.LDAPError, e:
print e
This part of a python script. I am getting the error in the line "except ldap.LDAPError, e:". But it seems to be right. Can anyone help?
Thanks!
| [
"If you use Python 3 that's\nm = ldap.initialize(server)\ntry:\n m.start_tls_s()\nexcept ldap.LDAPError as e:\n print(e)\n\nSee the language reference.\n"
] | [
4
] | [] | [] | [
"exception",
"python",
"python_3.x"
] | stackoverflow_0006901553_exception_python_python_3.x.txt |
Q:
SQLAlchemy: select over multiple tables
I wanted to optimize my database query:
link_list = select(
columns=[link_table.c.rating, link_table.c.url, link_table.c.donations_in],
whereclause=and_(
not_(link_table.c.id.in_(
select(
columns=[request_table.c.recipient],
... | SQLAlchemy: select over multiple tables | I wanted to optimize my database query:
link_list = select(
columns=[link_table.c.rating, link_table.c.url, link_table.c.donations_in],
whereclause=and_(
not_(link_table.c.id.in_(
select(
columns=[request_table.c.recipient],
whereclause=request_table.c.donator... | [
"You may be look for the SQL NOT EXISTS construct:\nhttp://www.sqlalchemy.org/docs/orm/tutorial.html#using-exists\n",
"Riffing on masida's answer: \nFirst, the original query:\n>>> print select(\n... columns=[link_table.c.url, link_table.c.donations_in],\n... whereclause=and_(\n... not_(link_table... | [
1,
0
] | [] | [] | [
"mysql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003061154_mysql_python_sql_sqlalchemy.txt |
Q:
simplejson decoder for a python script
I am trying to parse the code with simplejson using a python script.
{ "name":"some",
"products_valid_time_from":2011-08-01T14:45:00,
"products_valid_time_to":2011-08-01T21:00:00,
}
Ia m getting an error
simplejson.decoder.JSONDecodeError: Expecting , delimiter: line ... | simplejson decoder for a python script | I am trying to parse the code with simplejson using a python script.
{ "name":"some",
"products_valid_time_from":2011-08-01T14:45:00,
"products_valid_time_to":2011-08-01T21:00:00,
}
Ia m getting an error
simplejson.decoder.JSONDecodeError: Expecting , delimiter: line 2 column 34 (char 52)
Can some one help me ... | [
"Dates are not part of JSON. See for example this blog entry.\n",
"Your dates need to be in quotes. It's just another string to the JSON parser.\n",
"The format is wrong.\nYou can follow this json rule\nYou can save your date as string first.\nThen when you retrieve that value, you can use alternative library t... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006901783_python.txt |
Q:
saving multiple outputs in different files
I have a program which generates several plots.. Now I need to save each plot in a different file like say: file1, file2, file2,...
P.S: I am using Gnuplot to save and generate the plots:
g('set output \"test.ps\"')
How do I generate these names?
A:
You need to use stri... | saving multiple outputs in different files | I have a program which generates several plots.. Now I need to save each plot in a different file like say: file1, file2, file2,...
P.S: I am using Gnuplot to save and generate the plots:
g('set output \"test.ps\"')
How do I generate these names?
| [
"You need to use string formatting. The simplest option is to use\ng('set output \\\"test%d.ps\\\"' % n)`\n\nand make n increase.\n"
] | [
1
] | [] | [] | [
"filesystems",
"gnuplot",
"python",
"store"
] | stackoverflow_0006901228_filesystems_gnuplot_python_store.txt |
Q:
rpy2 error on OSX Lion
I've tried the installation (which terminates successfully) of rpy2 both from source (python setup.py install) and macports, and upon trying to import rpy2, I'm getting this error:
/Library/Python/2.7/site-packages/rpy2/rinterface/__init__.py in <module>()
76
77
---> 78 from rpy2... | rpy2 error on OSX Lion | I've tried the installation (which terminates successfully) of rpy2 both from source (python setup.py install) and macports, and upon trying to import rpy2, I'm getting this error:
/Library/Python/2.7/site-packages/rpy2/rinterface/__init__.py in <module>()
76
77
---> 78 from rpy2.rinterface._rinterface impo... | [
"The Python bindings depend on a working R installation. Based on the file paths shown, the traceback you give must be from your source install and it is not finding the R framework or libraries, which would not be in that location (/Library/Frameworks) if installed by MacPorts. Your best bet is to stick with the... | [
0
] | [] | [] | [
"python",
"r",
"rpy2"
] | stackoverflow_0006894983_python_r_rpy2.txt |
Q:
Having arbitrary number of arguments with a named default in python
I want to write a function in python that can take an arbitrary number of unnamed arguments in addition to one named argument (with a default).
For example, I want to write something like this
def myFunc(*args, optDefault=1):
But this just gives ... | Having arbitrary number of arguments with a named default in python | I want to write a function in python that can take an arbitrary number of unnamed arguments in addition to one named argument (with a default).
For example, I want to write something like this
def myFunc(*args, optDefault=1):
But this just gives a syntax error. Is there an equivalent way to do this?
| [
"What about\ndef myFunc(*args, **kwargs):\n optDefault = kwargs.pop('optDefault', 1)\n assert kwargs == {}, \"There may only be one keyword argument to myFunc\"\n\nNot the prettiest, but it works.\n",
"What about:\ndef myFunc(optDefault=1, *args):\n\n"
] | [
2,
1
] | [
"why dont you use this, \nan example (I borrow from here)\nimport optparse\n\nif __name__==\"__main__\":\n parser = optparse.OptionParser(\"usage: %prog [options] arg1 arg2\")\n parser.add_option(\"-H\", \"--host\", dest=\"hostname\",\n default=\"127.0.0.1\", type=\"string\",\n ... | [
-2
] | [
"arguments",
"function",
"python"
] | stackoverflow_0006902192_arguments_function_python.txt |
Q:
Python RESTfull Server
I am new in python and I have to run a project about web services with the following specs:
Windows Server (2003/2008)
REST architecture enabled
Python platform (any version)
My questions are:
Which web server fits better (IIS, Apache, ...)?
May I use GoogleAppEngine for commercial purpos... | Python RESTfull Server | I am new in python and I have to run a project about web services with the following specs:
Windows Server (2003/2008)
REST architecture enabled
Python platform (any version)
My questions are:
Which web server fits better (IIS, Apache, ...)?
May I use GoogleAppEngine for commercial purposes?
In order to make RESTful... | [
"\nWhich web server fits better (IIS, Apache, ...)?\n\nFits what better? Fits Windows? Fits RESTful web services?\nIt doesn't much matter. Which ever one you can configure and manage.\n\nIn order to make RESTful web services on windows which python modules I will have to have?\n\nAll of them.\nREST is simply a s... | [
1,
1
] | [] | [] | [
"python",
"rest",
"windows"
] | stackoverflow_0006902200_python_rest_windows.txt |
Q:
Can't import library to project
I try to create project in Python, which is composed of GAE, Django and Orange library. When I create this project without Orange there is no problem to run it. But when I attach that library to project i get message
ImportError: No module named orange
I try to add sources to my p... | Can't import library to project | I try to create project in Python, which is composed of GAE, Django and Orange library. When I create this project without Orange there is no problem to run it. But when I attach that library to project i get message
ImportError: No module named orange
I try to add sources to my project directory but it also doesn't ... | [
"GAE does not support python modules with C extensions. In their own words:\n\nApplication code written for the Python environment must be written exclusively in Python. Extensions written in the C language are not supported.\n\n\nhttp://code.google.com/appengine/docs/whatisgoogleappengine.html\n\n\n$ cloc Orange-2... | [
4
] | [] | [] | [
"django",
"google_app_engine",
"orange",
"python"
] | stackoverflow_0006902359_django_google_app_engine_orange_python.txt |
Q:
python calculate mouse speed
i am using the following method in python to get the X,Y corordinates at any given this
data = display.Display().screen().root.query_pointer()._data
x = data["root_x"]
y = data["root_y"]
z = time.time()
I want to calculate the mouse speed over a given time, is there any way i can c... | python calculate mouse speed | i am using the following method in python to get the X,Y corordinates at any given this
data = display.Display().screen().root.query_pointer()._data
x = data["root_x"]
y = data["root_y"]
z = time.time()
I want to calculate the mouse speed over a given time, is there any way i can calculate and show mouse speed in m... | [
"Store the start position and end position, as well as the start time and end time. Get the distance, then divide by the time. That gives you a speed. Presumably that speed is pixels per millisecond, so you just need to convert that to the units you want (miles per hour).\n# Start\ndata = display.Display().screen()... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006902299_python.txt |
Q:
repo init fails getting android source code
I have tried to get the source code of android (on Windows 7) via this tutorial:
http://source.android.com/source/downloading.html
At this step
$ repo init -u https://android.googlesource.com/platform/manifest
I got this error message which I cannot solve yet:
fatal: ... | repo init fails getting android source code | I have tried to get the source code of android (on Windows 7) via this tutorial:
http://source.android.com/source/downloading.html
At this step
$ repo init -u https://android.googlesource.com/platform/manifest
I got this error message which I cannot solve yet:
fatal: unable to start C:\Users\mike\myrepo.repo\repo/ma... | [
"I have fixed the problem.\n\nI made a clean installation of Eclipse Indigo SE (better newer than older versions) \ngot the sources via http://vogella.de/articles/Android/article.html (2.4. Android Source Code) \ncreated a new project, created the classes and copied all the contents in the new classes \nconfig... | [
2
] | [] | [] | [
"android_source",
"python"
] | stackoverflow_0006879780_android_source_python.txt |
Q:
Python file scan application with multithreading
How to use multithreading in this code and limit the thread; example 4 thread.
import os
import glob
from pymongo import Connection
from gridfs import GridFS
db = Connection().microfilm
fs = GridFS(db)
def scandirs(path):
for currentFile in glob.glob( os.path.... | Python file scan application with multithreading | How to use multithreading in this code and limit the thread; example 4 thread.
import os
import glob
from pymongo import Connection
from gridfs import GridFS
db = Connection().microfilm
fs = GridFS(db)
def scandirs(path):
for currentFile in glob.glob( os.path.join(path, '*') ):
if os.path.isdir(currentFil... | [
"Create a pool(list) of Thread objects of size n, use is_alive to check if any is finished, so then you can assign a new directory scan in it.\nAlso you should subclass the Thread class and define a run method to adapt to your problem, details on how to do this are in the docs.\n",
"first import Threading then Th... | [
1,
0
] | [] | [] | [
"file",
"mongodb",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0006901818_file_mongodb_multiprocessing_multithreading_python.txt |
Q:
Python/imaplib - How to get messages' labels?
I'm using imaplib for my project because I need to access gmails accounts.
Fact: With gmail's labels each message may be on an arbitrary number of folders/boxes/labels.
The problem is that I would like to get every single label from every single message.
The first solu... | Python/imaplib - How to get messages' labels? | I'm using imaplib for my project because I need to access gmails accounts.
Fact: With gmail's labels each message may be on an arbitrary number of folders/boxes/labels.
The problem is that I would like to get every single label from every single message.
The first solution it cames to my mind is to use "All Mail" folde... | [
"To get all the labels for a given message within gmail you can do the following\nt, d = imapconn.uid('FETCH', uid, '(X-GM-LABELS)')\nor\nt, d = imapconn.fetch(uid, '(X-GM-LABELS)')\n\nBTW: You can find more on gmail imap extensions at http://code.google.com/apis/gmail/imap/\n",
"in imap you don't have labels, gm... | [
13,
0
] | [] | [] | [
"gmail",
"imaplib",
"python"
] | stackoverflow_0006123164_gmail_imaplib_python.txt |
Q:
Test archive data (unzip -t equivalent) - Python
I have a program written in python that uploads an archive (zip file) to a remote server. But before uploading it I need to test that it is not corrupted, so I want to execute something like an unzip -t and throw an error if it fails.
Is there something implemented... | Test archive data (unzip -t equivalent) - Python | I have a program written in python that uploads an archive (zip file) to a remote server. But before uploading it I need to test that it is not corrupted, so I want to execute something like an unzip -t and throw an error if it fails.
Is there something implemented in python that can do that (couldn't find anything on... | [
"Zipfile.testzip is your friend.\n\nRead all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None.\n\n",
"Use ZipFile.testzip:\nimport zipfile\ndef zip_isOk(fn):\n with zipfile.ZipFile(fn, 'r') as zipf:\n return zipf.testzip() is Non... | [
4,
3
] | [] | [] | [
"linux",
"python",
"unzip"
] | stackoverflow_0006902752_linux_python_unzip.txt |
Q:
Do Django-nonrel and Django-SocialAuth play together nicely?
Anybody got Django-SocialAuth working with Django-nonrel?
Do they work together?
Please let me know if you have done it. Any gotchas to watch for?
A:
They do, the only issue you'll run into if you are using a non-rel database is that the admin module... | Do Django-nonrel and Django-SocialAuth play together nicely? | Anybody got Django-SocialAuth working with Django-nonrel?
Do they work together?
Please let me know if you have done it. Any gotchas to watch for?
| [
"They do, the only issue you'll run into if you are using a non-rel database is that the admin modules for Social_Auth will not work. They use joins. I was considering forking the project to see if I could make them work with non-rel, but I ran out of time.\nWhat I've done is setup two separate databases. I'm stori... | [
1
] | [] | [] | [
"django_nonrel",
"django_socialauth",
"python"
] | stackoverflow_0006473879_django_nonrel_django_socialauth_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.