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: url method of ImageField returns a non-Url value - Django I'm developing using Django on Windows. I have a model with an imagefield, and use a form to fill it. Images get uploaded without problem. The problem occurs when I attempt to show an uploaded image inside a template by coding this: <img src ='{{object.imag...
url method of ImageField returns a non-Url value - Django
I'm developing using Django on Windows. I have a model with an imagefield, and use a form to fill it. Images get uploaded without problem. The problem occurs when I attempt to show an uploaded image inside a template by coding this: <img src ='{{object.image.url}}'/> (object is an instance of the relevant model, an...
[ "I had the same problem. At model declaration, I changed \"upload_to\" argument value from absolute path to relative, this fixes the problem.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python", "url" ]
stackoverflow_0000862860_django_django_models_python_url.txt
Q: Facing "can't start new thread" error while doing multithread file operations Hey guys, I'm writing a script to update status log, this involves frequently file operations. My way of doing this is to use a "big" method including all read/write operations on this file, and set a RLock to make sure only one thread o...
Facing "can't start new thread" error while doing multithread file operations
Hey guys, I'm writing a script to update status log, this involves frequently file operations. My way of doing this is to use a "big" method including all read/write operations on this file, and set a RLock to make sure only one thread operating the file at a time. I'm sure there is far less than 1000 threads running ...
[ "You are probably reaching memory limit for an application on your platform. Check how much is allocated for stack for each thread.\nhttp://docs.python.org/library/resource.html\n" ]
[ 0 ]
[]
[]
[ "file_io", "multithreading", "python" ]
stackoverflow_0006240716_file_io_multithreading_python.txt
Q: Widget Layering in Tkinter I'm using the place geometry manager to make draggable widgets. I've noticed however, that the last widget made gets priority in layering. In other words it always appears over the widgets made before it. Is there any way to change widget layering? A: Use tk lower whose Tkinter form is...
Widget Layering in Tkinter
I'm using the place geometry manager to make draggable widgets. I've noticed however, that the last widget made gets priority in layering. In other words it always appears over the widgets made before it. Is there any way to change widget layering?
[ "Use tk lower whose Tkinter form is \nwindow.lower(belowThis=None)\n\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006240702_python_tkinter.txt
Q: Python socket.sendall() function I'm reading Tutorial on Network Programming with Python, and in this document the author is saying that "The function sendall() should be used only with blocking sockets." But I do not see any such condition in the Python documentation, socket.sendall(string[, flags]). Is the autho...
Python socket.sendall() function
I'm reading Tutorial on Network Programming with Python, and in this document the author is saying that "The function sendall() should be used only with blocking sockets." But I do not see any such condition in the Python documentation, socket.sendall(string[, flags]). Is the author of PyNet right?
[ "When in doubt, check the source.\nsocket_sendall clearly gives up once send() returns -1, which it will do (with errno of EAGAIN or EWOULDBLOCK) if you call it on a non-blocking socket without calling poll() or select(). (And the internal_select function skips calling poll()/select() when the socket is non-blocki...
[ 12, 6 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0006240737_python_sockets.txt
Q: small issue with whitespeace/punctuation in python? I have this function that will convert text language into English: def translate(string): textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go', 'lol': 'laugh out loud', 'ur': 'your',} translatestring = '' for word in s...
small issue with whitespeace/punctuation in python?
I have this function that will convert text language into English: def translate(string): textDict={'y':'why', 'r':'are', "l8":'late', 'u':'you', 'gtg':'got to go', 'lol': 'laugh out loud', 'ur': 'your',} translatestring = '' for word in string.split(' '): if word in textDict: ...
[ "oneliner comprehension:\n''.join(textDict.get(word, word) for word in re.findall('\\w+|\\W+', string))\n\n[Edit] Fixed regex.\n", "You're adding words to a string without spaces. If you're going to do things this way (instead of the way suggested to your in your previous question on this topic), you'll need to m...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "punctuation", "python" ]
stackoverflow_0006240685_punctuation_python.txt
Q: Using ruby gem/command from python I've installed the Ruby gem 'haml' on my mac, which I can use to compile haml files into html files using the following command at the terminal: haml 'path/to/haml/file.haml' 'desired/html/path/file.html' This command simply creates an html file at the second path, and gives no ...
Using ruby gem/command from python
I've installed the Ruby gem 'haml' on my mac, which I can use to compile haml files into html files using the following command at the terminal: haml 'path/to/haml/file.haml' 'desired/html/path/file.html' This command simply creates an html file at the second path, and gives no output in the terminal. So for example, ...
[ "I see that you are using, shell=True, so I would have expected things to just work. Checked it locally here with Python 2.7.1 and haml 3.1.1 and I had no problems executing it. There are also some python implementations you might be interested in, PyHAML, HamlPy, djaml or django-haml.\nimport subprocess\nsubproces...
[ 2, 0 ]
[]
[]
[ "command", "haml", "python", "shell", "subprocess" ]
stackoverflow_0006239218_command_haml_python_shell_subprocess.txt
Q: Problem posting to datastore with deferred.defer tasks I am trying to do this on Google App Engine in Python: def add_to_db(person): a = PersonDb(key_name = person) # get some data data1 = a.name data2 = a.age a.put() for person in people: deferred.defer(add_to_db, person, _queue="myq...
Problem posting to datastore with deferred.defer tasks
I am trying to do this on Google App Engine in Python: def add_to_db(person): a = PersonDb(key_name = person) # get some data data1 = a.name data2 = a.age a.put() for person in people: deferred.defer(add_to_db, person, _queue="myque") When I run the above code via a cron job it does not w...
[ "This is probably happening because the function you are trying to defer (add_to_db) is defined in the request handler. Move add_to_db to another module (a different python file) and import it from there (from myfuncs import add_to_db).\nThis limitation is mentioned in the limitations section of the deferred artic...
[ 2 ]
[]
[]
[ "datastore", "deferred", "google_app_engine", "python", "scheduled_tasks" ]
stackoverflow_0006225400_datastore_deferred_google_app_engine_python_scheduled_tasks.txt
Q: Python for x in list basic question I am trying to create a function which will load a whole lot of images and map them to appropriate names in PyGame. I'm not all that great with python and this really has me stuck. My current code is this: tile1 = pygame.image.load("/one.bmp") tile2 = pygame.image.load("/two.bmp...
Python for x in list basic question
I am trying to create a function which will load a whole lot of images and map them to appropriate names in PyGame. I'm not all that great with python and this really has me stuck. My current code is this: tile1 = pygame.image.load("/one.bmp") tile2 = pygame.image.load("/two.bmp") tile3 = pygame.image.load("/three.bmp"...
[ "List comprehensions to the rescue.\ntiles = ['/one.bmp', '/two.bmp', '/three.bmp']\ntilelist = [pygame.img.load(tile) for tile in tiles]\n\n\nAs @isakkarlsson commented,\n\n...or easier(?) tilelist = map(pygame.img.load, tiles)\n\n", "To load the data\ntile = ['/one.bmp', '/two.bmp', '/three.bmp']\nimageMap = {}...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006240906_python.txt
Q: Need help specifying a ending while condition I have written a Python script to download all of the xkcd comic images. The only problem is I can't tell it to stop when it gets to the last one... Here is what I have so far. import re, mechanize from urllib import urlretrieve from BeautifulSoup import BeautifulSoup ...
Need help specifying a ending while condition
I have written a Python script to download all of the xkcd comic images. The only problem is I can't tell it to stop when it gets to the last one... Here is what I have so far. import re, mechanize from urllib import urlretrieve from BeautifulSoup import BeautifulSoup as bs baseUrl = "http://xkcd.com/1/" #Specify the ...
[ "When you follow the \"Next\" link from the most recent xkcd comic, a hash tag is appended to the URL. Try using the following.\nwhile not br.geturl().endswith(\"#\"):\n ...\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "mechanize", "python", "while_loop" ]
stackoverflow_0006240865_beautifulsoup_mechanize_python_while_loop.txt
Q: Configuring tools with an external file in cherrypy I'm trying to figure out how to configure a tool to run whenever a request is received in cherrypy, using an external configuration file. I've read through the examples in the documentation, but these all embed the configuration into the source file, rather than...
Configuring tools with an external file in cherrypy
I'm trying to figure out how to configure a tool to run whenever a request is received in cherrypy, using an external configuration file. I've read through the examples in the documentation, but these all embed the configuration into the source file, rather than a separate configuration file. I've read that tools can...
[ "There is no facility inside of a config file to instantiate a Tool (the cherrypy.Tool(...) part). You need to do that in code. Your 'mytools.py' file should look like this:\ndef print_path(multiplier=1):\n ...\ncherrypy.tools.print_path = cherrypy.Tool('on_start_resource', print_path)\n\n...and then your config...
[ 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0006240376_cherrypy_python.txt
Q: Is there something about the os module I'm not getting? For the last half hour I've been trying to figure out what is wrong with this code. It should be very straight forward. I've practically copied it out of the documentation at this point. But no matter what I try I receive a syntax error. Here's the code: def ...
Is there something about the os module I'm not getting?
For the last half hour I've been trying to figure out what is wrong with this code. It should be very straight forward. I've practically copied it out of the documentation at this point. But no matter what I try I receive a syntax error. Here's the code: def addfiles(folder): foldercont = [os.path.normcase(f) for f...
[ "There's a parenthesis missing at this line:\nfiles.append(os.path.realpath(x)\n ^\n\nPython complains about the True: bit because it's expecting a statement like\n(x if condition else y)\n\nAs jcomeau_ictx says, you should also leave out the == True when checking for booleans:\nif x:...
[ 11, 1 ]
[]
[]
[ "file", "operating_system", "python", "syntax" ]
stackoverflow_0006241253_file_operating_system_python_syntax.txt
Q: Python code hangs while trying to open a named pipe for reading I am trying to setup two way communication between a daemon and a client using named pipes. The code hangs while trying to open the named pipe used for input Why? class comm(threading.Thread): def __init__(self): self.srvoutf = './tmp/serverout' ...
Python code hangs while trying to open a named pipe for reading
I am trying to setup two way communication between a daemon and a client using named pipes. The code hangs while trying to open the named pipe used for input Why? class comm(threading.Thread): def __init__(self): self.srvoutf = './tmp/serverout' self.srvinf = './tmp/serverin' if os.path.exists(self.srvoutf...
[ "From the specification for open():\n\nWhen opening a FIFO with O_RDONLY or\nO_WRONLY set:\nIf O_NONBLOCK is set, an\nopen() for reading-only shall return\nwithout delay. An open() for\nwriting-only shall return an error if\nno process currently has the file open\nfor reading.\nIf O_NONBLOCK is clear, an open() for...
[ 13 ]
[]
[]
[ "fifo", "file_io", "named_pipes", "nonblocking", "python" ]
stackoverflow_0006241260_fifo_file_io_named_pipes_nonblocking_python.txt
Q: Error compiling coverage.py on MacOSX I tried to install coverage 3.4 on my MacBook running on current Mac OS X 10.6.7. This is what I got as an error: $ easy_install coverage install_dir /Users/jammon/workspace/myproject/lib/python2.7/site-packages/ Searching for coverage Reading http://pypi.python.org/simple/cov...
Error compiling coverage.py on MacOSX
I tried to install coverage 3.4 on my MacBook running on current Mac OS X 10.6.7. This is what I got as an error: $ easy_install coverage install_dir /Users/jammon/workspace/myproject/lib/python2.7/site-packages/ Searching for coverage Reading http://pypi.python.org/simple/coverage/ Reading http://nedbatchelder.com/cod...
[ "The most recent version of XCode removes support for compiling to the old PowerPC (PPC) architecture. Unfortunately, Python on Mac typically still tries to build C extensions for PPC as well as x86. To get around this, prefix commands like 'setup.py install' or 'easy_install' with an ARCHFLAGS setting that only in...
[ 6, 0, 0 ]
[]
[]
[ "compiler_errors", "coverage.py", "installation", "macos", "python" ]
stackoverflow_0005793709_compiler_errors_coverage.py_installation_macos_python.txt
Q: gae Model get_by_id() vs get_by_key_name() I am wondering about fetching records using Model.get_by_key_name() vs Model.get_by_id() For example, let's say I am returning some JSON that will be used to display a table of records, and for each record, there is a button to delete that record. Suppose I have model 'Fo...
gae Model get_by_id() vs get_by_key_name()
I am wondering about fetching records using Model.get_by_key_name() vs Model.get_by_id() For example, let's say I am returning some JSON that will be used to display a table of records, and for each record, there is a button to delete that record. Suppose I have model 'Foo' and model instance 'foo'. I believe I can ass...
[ "You're confusing a Key name with the stringified Key. They're different. A key's name is something you give an entity via the reserved key_name property at construction time. If you don't, the system will generate an id. An entity key can have either a name or an id, but not both.\nIf you've intentionally stringif...
[ 11, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006240312_google_app_engine_python.txt
Q: how to enumerate class method then chain them with itertools.product() in python? I just learned yesterday from this site that I can: class Seq(object): def __init__(self, seq): self.seq = seq def __repr__(self): return repr(self.seq) def __str__(self): return str(self.seq) ...
how to enumerate class method then chain them with itertools.product() in python?
I just learned yesterday from this site that I can: class Seq(object): def __init__(self, seq): self.seq = seq def __repr__(self): return repr(self.seq) def __str__(self): return str(self.seq) def all(self): return Seq(self.seq[:]) def head(self, count): retur...
[ "Note that something like \"s.head()\" means a method which is \"bound\" to that specific instance of Seq, that is, \"s.\" Something like \"Seq.head()\" means a method which is unbound, so one can still pass in different instances of Seq.\nFrom there it simply requires basic functional composition and string concat...
[ 0 ]
[]
[]
[ "class_method", "enumeration", "method_chaining", "python" ]
stackoverflow_0006241162_class_method_enumeration_method_chaining_python.txt
Q: Python A* algorithm not searching appropriately So I'm trying to write a Python implementation of the A* algorithm. My algorithm finds the path to the target without trouble, but when I get the program to visualize the closed and open lists, I notice that the closed list, whenever the obstacles are a little compl...
Python A* algorithm not searching appropriately
So I'm trying to write a Python implementation of the A* algorithm. My algorithm finds the path to the target without trouble, but when I get the program to visualize the closed and open lists, I notice that the closed list, whenever the obstacles are a little complicated, will balloon into a large, perfect diamond sh...
[ "My theory: it's because Manhattan distance is not admissible in this case, because you can move diagonal as well.\nTry this:\ndef distance(self, tile1, tile2):\n self.xDist = abs(tile1.col * TILE_SIZE - tile2.col * TILE_SIZE)\n self.yDist = abs(tile1.row * TILE_SIZE - tile2.row * TILE_SIZE)\n self.totalDi...
[ 1 ]
[]
[]
[ "a_star", "pygame", "python" ]
stackoverflow_0006241383_a_star_pygame_python.txt
Q: I'm using Pylons and having issues with response.set_cookie I am thinking one of the versions of Pylons is different but I could not find an easy way to tell what versions I was running. In the first example I am fairly certain it is 0.9.7 and up using webob to set the cookie. This environment is setting the @ sym...
I'm using Pylons and having issues with response.set_cookie
I am thinking one of the versions of Pylons is different but I could not find an easy way to tell what versions I was running. In the first example I am fairly certain it is 0.9.7 and up using webob to set the cookie. This environment is setting the @ symbol to \100. As you can see in the other environment doing the ex...
[ "Its because of the newer version of webob. \nThe webob package in pylons 0.9.7 is ~0.9.8, which does not escape cookie values.\nSomewhere between then and now, webob started escaping the values, which is causing your 'new' version to fail. If you dig into the webob codebase (newer version), this is happening in th...
[ 1 ]
[]
[]
[ "cookies", "pylons", "python", "webob" ]
stackoverflow_0006232159_cookies_pylons_python_webob.txt
Q: how can I program a large number of for loops I'm new to programming so I'm sorry in phrasing if I'm not asking this question correctly. I have the following code: int sum = 100; int a1 = 20; int a2 = 5; int a3 = 10; for (int i = 0; i * a1 <= sum; i++) { for (int j = 0; i * a1 + j * a2 <= sum; j++) { f...
how can I program a large number of for loops
I'm new to programming so I'm sorry in phrasing if I'm not asking this question correctly. I have the following code: int sum = 100; int a1 = 20; int a2 = 5; int a3 = 10; for (int i = 0; i * a1 <= sum; i++) { for (int j = 0; i * a1 + j * a2 <= sum; j++) { for (int k = 0; i * a1 + j * a2 + k * a3 <= sum; k++...
[ "Recursion.\nThis is what it sounds like you are trying to solve:\n\nyour current example: 20x1 + 5x2 + 10x3 = 100\nso in general you are doing: A1x1 + A2x2 + ... + Anxn = SUM\nso you pass in an array of constants {A1, A2, ..., An}\nand you want to solve for {x1, x2, ..., xn}\n\n public void findVariables(int[] ...
[ 13, 7, 3, 2, 2 ]
[]
[]
[ "algorithm", "java", "loops", "math", "python" ]
stackoverflow_0006240770_algorithm_java_loops_math_python.txt
Q: QNetworkProxy: unset proxy How to unset the proxy settings in python set by QNetworkProxy.setApplicationProxy? Sultan. A: To go back to the application defaults, use QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.DefaultProxy)) if you want to explicitly disable any proxy you can use QNetworkProxy...
QNetworkProxy: unset proxy
How to unset the proxy settings in python set by QNetworkProxy.setApplicationProxy? Sultan.
[ "To go back to the application defaults, use\nQNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.DefaultProxy))\n\nif you want to explicitly disable any proxy you can use QNetworkProxy.NoProxy instead.\n" ]
[ 2 ]
[]
[]
[ "proxy", "pyqt", "python", "qnetworkaccessmanager" ]
stackoverflow_0006241323_proxy_pyqt_python_qnetworkaccessmanager.txt
Q: Doxygen end of line comments on declarations in Python In C/C++, you can force doxygen to recognize that a comment applies to the text preceding it on a line. Any of these: int my_variable; /*!< This is my variable */ int my_variable; /**< This is my variable */ int my_variable; ...
Doxygen end of line comments on declarations in Python
In C/C++, you can force doxygen to recognize that a comment applies to the text preceding it on a line. Any of these: int my_variable; /*!< This is my variable */ int my_variable; /**< This is my variable */ int my_variable; //!< This is my variable int my_variable; ...
[ "No, at the moment this is not supported.\nThe parser for Python was provided by a couple of students. While they did a good job overall, they did not implement all the features that are available for C/C++.\nTwo most notable features that are missing are:\n\nsupport for documenting stuff after the definition\nhttp...
[ 8 ]
[]
[]
[ "doxygen", "python" ]
stackoverflow_0006179305_doxygen_python.txt
Q: Best way to represent this using Python data structures <specification> <propertyName> string </propertyName> <value> <number> <value> anyNumberHere </value> </number> <text> <value> anyTextHere </value> </text> <URL> <value> anyURIHere </value> ...
Best way to represent this using Python data structures
<specification> <propertyName> string </propertyName> <value> <number> <value> anyNumberHere </value> </number> <text> <value> anyTextHere </value> </text> <URL> <value> anyURIHere </value> </URL> </value> <!-- ... 1 or more value nodes ...
[ "How about a list of Specification objects, of which each has a property_name and a list of value dictionaries? (values could be a list of objects instead of dictionaries.)\nFor example:\nclass Value(object):\n def __init__(self,\n number=None,\n text=None,\n url=...
[ 6, 0, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0006240937_data_structures_python.txt
Q: Ancestors in App Engine data store I've been developing for Google App Engine for a while. One of the features I've noticed but haven't had an opportunity to use yet is "ancestors" in the data store. What would be an example of a situation where this is useful? A: When you create an entity with a parent, the en...
Ancestors in App Engine data store
I've been developing for Google App Engine for a while. One of the features I've noticed but haven't had an opportunity to use yet is "ancestors" in the data store. What would be an example of a situation where this is useful?
[ "When you create an entity with a parent, the entities are placed in the same Entity Group. Transactions in App Engine can only work within a single entity group, so if you need transactions, you need entity groups. If you don't need transaction, you don't need entity groups (in particular, to build relationships b...
[ 5 ]
[]
[]
[ "ancestor", "datastore", "google_app_engine", "python" ]
stackoverflow_0006239737_ancestor_datastore_google_app_engine_python.txt
Q: Windows isn't generating Python Compiled Files I'm currently on a Windows 7 environment developing a Pyramid web application. I had been developing this app on my Mac, but that's recently died, so I've had to move to my Windows machine. I've set up everything I need; Python 2.7, Pyramid, pyramid_beaker, MongoDB, ...
Windows isn't generating Python Compiled Files
I'm currently on a Windows 7 environment developing a Pyramid web application. I had been developing this app on my Mac, but that's recently died, so I've had to move to my Windows machine. I've set up everything I need; Python 2.7, Pyramid, pyramid_beaker, MongoDB, mongoengine, etc. It seemed to be working while I wa...
[ "Sorry, your question is not clear enough. It seems you have some kind of read/write permission problems, and generating *.pyc has nothing to do with it. \n*.pyc contains Python bytecode, in fact it is there just to load the original *.py files faster. Every time Python successfully reads a *.py file and is able to...
[ 3 ]
[]
[]
[ "pyramid", "python", "windows" ]
stackoverflow_0006242915_pyramid_python_windows.txt
Q: Can I create a Python Numpy ufunc from an unbound member method? I would like to use numpy.frompyfunc to generate an unbound ufunc from an unbound member method. My concrete but failing attempts look like class Foo(object): def f(x,y,z): return x + y + z Foo.g = numpy.frompyfunc(Foo.f,3,1) i = Foo() ...
Can I create a Python Numpy ufunc from an unbound member method?
I would like to use numpy.frompyfunc to generate an unbound ufunc from an unbound member method. My concrete but failing attempts look like class Foo(object): def f(x,y,z): return x + y + z Foo.g = numpy.frompyfunc(Foo.f,3,1) i = Foo() i.g(5,6,7) where the last line fails with "TypeError: unbound method ...
[ "I must admit that I don't quite understand why you'd want f and g to be inside Foo class, but the following works:\n>>> class Foo(object):\n... @staticmethod\n... def f(x, y, z):\n... return x+y+z\n...\n>>> Foo.g = numpy.frompyfunc(Foo.f, 3, 1)\n>>> i = Foo()\n>>> i.g(5, 6, 7)\n18\n\nEDIT: sinc...
[ 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006126233_numpy_python.txt
Q: Tree traversal in a customised way in Python? I have two trees in python. I need to compare them in a customized way according to the following specifications. Suppose I have a tree for entity E1 and a tree for entity E2. I need to traverse both the trees starting from E1 and E2 and moving upwards till I get to a ...
Tree traversal in a customised way in Python?
I have two trees in python. I need to compare them in a customized way according to the following specifications. Suppose I have a tree for entity E1 and a tree for entity E2. I need to traverse both the trees starting from E1 and E2 and moving upwards till I get to a common root. (Please note that I have to start the ...
[ "This is not a \"traveral\" (which visits each node in a tree); what you describe is merely following the parents.\nThe algorithm would look as follows. One of the tricks is to interleave calculations, so that the algorithm is guaranteed to terminate quickly. You also have to consider cases like node1==node2. This ...
[ 2, 1, 0 ]
[]
[]
[ "python", "tree" ]
stackoverflow_0006241245_python_tree.txt
Q: Python lambda function What is happening here? reduce(lambda x,y: x+y, [x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0]) I understand how x is iterating through all of the numbers from 1 to 999 and taking out those that are divisible by 3 or 5, but the 'lambda x,y: x+y' part is stumping me. A: This is bad...
Python lambda function
What is happening here? reduce(lambda x,y: x+y, [x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0]) I understand how x is iterating through all of the numbers from 1 to 999 and taking out those that are divisible by 3 or 5, but the 'lambda x,y: x+y' part is stumping me.
[ "This is bad Python for\nsum(x for x in range(1,1000) if x % 3 == 0 or x % 5 == 0)\n\nIt simply sums all numbers in the range 1..999 divisible by 3 or 5.\nreduce() applies the given function to the first two items of the iterable, then to the result and the next item of the iterable, and so on. In this example, th...
[ 18, 10, 5 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0006243460_lambda_python.txt
Q: numpy csv import problem I am having some difficulty with importing data from a .csv file. I am simply trying to import the data and print the max value. Here is my code: >>> x, y = numpy.loadtxt('data.csv', delimiter=',', usecols=(4,5), unpack=True) >>> print 'max =', max(x) When I enter the above code, I get th...
numpy csv import problem
I am having some difficulty with importing data from a .csv file. I am simply trying to import the data and print the max value. Here is my code: >>> x, y = numpy.loadtxt('data.csv', delimiter=',', usecols=(4,5), unpack=True) >>> print 'max =', max(x) When I enter the above code, I get the following error message: Typ...
[ "The output of loadtxt() is unfortunately a bit inconistent: If there is only one line in your file, x and y will be scalars, but for more than one line, they will be arrays. The Python built-in max() only works for iterables, so it only works in the latter case.\nUsing the Python built-in max() function instead ...
[ 4 ]
[]
[]
[ "csv", "numpy", "python" ]
stackoverflow_0006243583_csv_numpy_python.txt
Q: What's the most elegant way of keeping track of the last time a python object is accessed? I have a list of objects in python that I would regularly check and destroy some of them - those which haven't been accessed lately (i.e. no method was called). I can maintain the last time accessed and update it in every m...
What's the most elegant way of keeping track of the last time a python object is accessed?
I have a list of objects in python that I would regularly check and destroy some of them - those which haven't been accessed lately (i.e. no method was called). I can maintain the last time accessed and update it in every method, but is there any more elegant way to achieve this?
[ "Use a decorator for the methods you want wrapped with the timestamp functionality, as @Marcelo Cantos pointed out.\nConsider this example:\nfrom datetime import datetime\nimport time\nimport functools\n\ndef t_access(method):\n @functools.wraps(method)\n def wrapper(self):\n self.timestamp = datetime....
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "class", "object", "python", "tracking" ]
stackoverflow_0006241448_class_object_python_tracking.txt
Q: python: invoking socket.recvfrom() twice I am writing two python scripts to communicate over UDP using python sockets. Here's the related part of code s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((HOST, PORT)) s.setblocking(True) #I want it to be blocking #(...) (msg, addr) = sock.recvfrom(4) #(...)...
python: invoking socket.recvfrom() twice
I am writing two python scripts to communicate over UDP using python sockets. Here's the related part of code s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((HOST, PORT)) s.setblocking(True) #I want it to be blocking #(...) (msg, addr) = sock.recvfrom(4) #(...) (msg2, addr2) = sock.recvfrom(2) I want the ...
[ "socket.recvfrom(size) will (for UDP sockets) read one packet, up to size bytes. The excess data is discarded. If you want to receive the whole packet, you have to pass a larger bufsize, then process the packet in bits (instead of trying to receive it in bits.)\nIf you want a more convenient, less fickle interface ...
[ 5, 2, 1 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0006243691_python_sockets_udp.txt
Q: Extract URLs from specific tags in python all. I have an huge html file which contains tags like these: <h3 class="r"> <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm" class=l onmousedown="return clk(this.href,'','','','6','','0CDEQFjACOAM')"> I need to extract all the urls from this page in pyt...
Extract URLs from specific tags in python
all. I have an huge html file which contains tags like these: <h3 class="r"> <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm" class=l onmousedown="return clk(this.href,'','','','6','','0CDEQFjACOAM')"> I need to extract all the urls from this page in python. In a loop: Find occurences of <h3 clas...
[ "from BeautifulSoup import BeautifulSoup\n\nhtml = \"\"\"<html>\n...\n<h3 class=\"r\">\n<a href=\"http://en.wikipedia.org/wiki/Digital_Signature_Algorithm\" class=l\n onmousedown=\"return clk(this.href,'','','','6','','0CDEQFjACOAM')\">\ntext</a>\n</h3>\n...\n<h3>Don't find me!</h3>\n<h3 class=\"r\"><a>Don't find...
[ 1 ]
[ "I'd use XPATH, see here for a question what package would be appropriate in Python.\n", "You can use a Regular Expressions (RegEx) for that.\nThis RegEx will catch all URL's beginning with http and surrounded by quotes (\"):\nhttp([^\\\"]+)\n\nAnd this is how it's done in Python:\nimport re\nmyRegEx = re.compile...
[ -1, -1 ]
[ "extract", "python", "tags", "url" ]
stackoverflow_0006243646_extract_python_tags_url.txt
Q: Where is the recommended way to put member variables when designing classes in python? I am trying to get familiar with classes in python. In C++ the structure of a class seems straightforward to me, regarding the member variables. You just declare them at the beginning of the class scope or at the end (as public ...
Where is the recommended way to put member variables when designing classes in python?
I am trying to get familiar with classes in python. In C++ the structure of a class seems straightforward to me, regarding the member variables. You just declare them at the beginning of the class scope or at the end (as public or private, as desired) and work with them as you need. How is this handled in python? Right...
[ "All of these approaches work, so it's a matter of your own code standards and documentation.\nPersonally, I regard it as good practice to initialise the \"public\" member attributes in the __init__ function. That makes it obvious what they are, and this should be emphasised by documenting them in the class docstri...
[ 4, 1, 0 ]
[]
[]
[ "class", "member_variables", "python" ]
stackoverflow_0006242872_class_member_variables_python.txt
Q: How do I access netstat data in Python? I'm trying to need to access/parse all outgoing connections on a particular port number on a Linux machine using a Python script. The simplest implementation seems to be to open a subprocess for netstat and parse its stdout. I imagine someone somewhere has had this problem b...
How do I access netstat data in Python?
I'm trying to need to access/parse all outgoing connections on a particular port number on a Linux machine using a Python script. The simplest implementation seems to be to open a subprocess for netstat and parse its stdout. I imagine someone somewhere has had this problem before, and am surprised not to find any netst...
[ "If you want to control the connection opened by a certain process you can use psutil:\n>>> p = psutil.Process(1694)\n>>> p.name()\n'firefox'\n>>> p.connections()\n[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED'),\n connection(fd=11...
[ 38 ]
[]
[]
[ "netstat", "python" ]
stackoverflow_0003993731_netstat_python.txt
Q: Can/should I implement Python methods by assignment to attributes? Is there any stylistic taboo or other downside to implementing trivial methods by assignment to class attributes? E.g. like bar and baz below, as opposed to the more ususal foo. class MyClass(object): def hello(self): return 'hello' ...
Can/should I implement Python methods by assignment to attributes?
Is there any stylistic taboo or other downside to implementing trivial methods by assignment to class attributes? E.g. like bar and baz below, as opposed to the more ususal foo. class MyClass(object): def hello(self): return 'hello' def foo(self): return self.hello() bar = lambda self: self...
[ "Personally, I think things like\n__str__ = __repr__ = hello\n\nare fine, but\nbar = lambda self: self.hello()\n\nis evil. You cannot easily give a lambda a docstring, and the .func_name attribute will have the meaningless value <lambda>. Both those problems don't occur for the first line.\n", "In general, it's...
[ 8, 4 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0006244342_coding_style_python.txt
Q: How to pass a bash parameter to a python script in a cron job? I have a python application that uses getopt() to parse the command line for parameters. It works fine in an interactive bash shell, or in a bash script that is called from the command line, bit it will not execute when being called from within a bash...
How to pass a bash parameter to a python script in a cron job?
I have a python application that uses getopt() to parse the command line for parameters. It works fine in an interactive bash shell, or in a bash script that is called from the command line, bit it will not execute when being called from within a bash shell script via cron. I am using Fedora 15. The application fails...
[ "While I agree with both comments, one way to debug issues with crontab entries is to be sure you're getting all the error messages. Are you looking at the cron users email file? Any un-captured output from cron is sent as an email to the userID. (If the user doesn't have an email account on the cron'ed machine, t...
[ 4 ]
[]
[]
[ "bash", "cron", "parameters", "python" ]
stackoverflow_0006239940_bash_cron_parameters_python.txt
Q: Extract text from a file object using .read() I'm trying to read the source of a website with this code: import urllib2 z=urllib2.urlopen('http://skreemr.com/results.jsp?q=said+the+whale&search=SkreemR+Search') z.read() print z txt = open('music.txt','w') txt.write(str(z)) txt.close() for i in open('music.txt','r'...
Extract text from a file object using .read()
I'm trying to read the source of a website with this code: import urllib2 z=urllib2.urlopen('http://skreemr.com/results.jsp?q=said+the+whale&search=SkreemR+Search') z.read() print z txt = open('music.txt','w') txt.write(str(z)) txt.close() for i in open('music.txt','r'): if '''onclick="javascript:pageTracker._t...
[ "z is a file object. In fact your codes prints the object description. You need to put the result of z.read() inside a variable (or print it directly).\nYou should do\nimport urllib2\nz=urllib2.urlopen('http://skreemr.com/results.jsp?q=said+the+whale&search=SkreemR+Search')\ni = z.read()\nprint i\n\n", ".read() d...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "urllib2", "urlopen" ]
stackoverflow_0006244462_python_urllib2_urlopen.txt
Q: How to dynamically clone class methods but be able to tell them apart in Python I'm trying to write a wrapper for an external module in python. The module provides a method to conjugate a verb that expects 2 arguments. I would like to wrap it into several methods and I was wondering if there was a way to do it pro...
How to dynamically clone class methods but be able to tell them apart in Python
I'm trying to write a wrapper for an external module in python. The module provides a method to conjugate a verb that expects 2 arguments. I would like to wrap it into several methods and I was wondering if there was a way to do it programatically. i.e. instead of: class X: def a(self,arg): return module.do(arg,'...
[ "You can do something like\nclass X:\n pass\nfor name in \"abcdefghij\":\n setattr(X, name, lambda self, arg, _name=name: module.do(arg, _name))\n\nIt's enough to add the methods to the class once -- it's not necessary to do this for every instance in __init__().\nMaybe a better alternative is overwriting __g...
[ 3, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0006244605_class_python.txt
Q: Replacement for _PyString_Resize in Python 3 I'm porting a module that uses C to extend Python's functionality from 2.x to 3, and can't find in the documents any references on how to resize a string, only how to get its size: http://docs.python.org/py3k/c-api/unicode.html?highlight=pyunicode#PyUnicode_GetSize How ...
Replacement for _PyString_Resize in Python 3
I'm porting a module that uses C to extend Python's functionality from 2.x to 3, and can't find in the documents any references on how to resize a string, only how to get its size: http://docs.python.org/py3k/c-api/unicode.html?highlight=pyunicode#PyUnicode_GetSize How do I convert this code: _PyString_Resize(&buffer, ...
[ "While it's not documented in the page you linked, unicodeobject.c does contain both\nint _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length) \n\nand the wrapper\nint PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)\n{\n return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);\n}\n\nI do...
[ 5 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006244581_python_python_3.x.txt
Q: Binary Files on 32bit / 64bit systems? I am using python struct module to create custom binary files. The file itself has the following format: 4 bytes (integer) 1 byte (unsigned char) 4 bytes (float) 4 bytes (integer) 1 byte (unsigned char) 4 bytes (float) .......................... (100000 such lines) 4 bytes ...
Binary Files on 32bit / 64bit systems?
I am using python struct module to create custom binary files. The file itself has the following format: 4 bytes (integer) 1 byte (unsigned char) 4 bytes (float) 4 bytes (integer) 1 byte (unsigned char) 4 bytes (float) .......................... (100000 such lines) 4 bytes (integer) 1 byte (unsigned char) 4 bytes (fl...
[ "As long as your struct format string uses \"standard size and alignment\" (< or >) rather than \"native size and alignment\" (@), your files can be used cross-platform.\n", "See http://docs.python.org/library/struct.html#byte-order-size-and-alignment\n\nBy default, C types are represented in the machine’s native...
[ 2, 1, 1 ]
[]
[]
[ "32bit_64bit", "python", "serialization" ]
stackoverflow_0006244799_32bit_64bit_python_serialization.txt
Q: action after sign in with google account I'm new in google app engine, so my question may be kind of stupid or trivial, but anyway... For each user (for each google acc) I have an entity in my datastore. So when a new user logs in I want to add him to database. I use: - url: /.* login: required To make sure use...
action after sign in with google account
I'm new in google app engine, so my question may be kind of stupid or trivial, but anyway... For each user (for each google acc) I have an entity in my datastore. So when a new user logs in I want to add him to database. I use: - url: /.* login: required To make sure user is logged in with his google acc. The proble...
[ "Here's a simple approach: If you create a subclass of webapp.RequestHandler that your handlers will then subclass, you can provide it with a convenience method for getting or creating a UserInfo object given users.get_current_user().user_id() (or .user_email(), if that's what you prefer to use as a key). Your hand...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006242326_google_app_engine_python.txt
Q: get entities for last 7 days in datastore i need to fetch entities for the last 7 days, and if fewer than 50 entities are fetched extend the range to 10 days, the model is something like: class MyModel(db.Model): title = db.StringProperty() date = db.DateTimeProperty(auto_now_add=True) plays = db.Integ...
get entities for last 7 days in datastore
i need to fetch entities for the last 7 days, and if fewer than 50 entities are fetched extend the range to 10 days, the model is something like: class MyModel(db.Model): title = db.StringProperty() date = db.DateTimeProperty(auto_now_add=True) plays = db.IntegerProperty() I also need to order by number of...
[ "I can't test the code right now but I would do something like :\nfrom datetime import datetime, timedelta\n\nquery = MyModel.gql(\"WHERE date > :1 ORDER BY plays DESC\", datetime.now() - timedelta(days=7))\ncount = query.count()\nif count < 50:\n query = MyModel.gql(\"WHERE date > :1\", datetime.now() - timedelt...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006244814_google_app_engine_google_cloud_datastore_python.txt
Q: Python & Amazon EC2 -- Using All Compute Units? I'm building a scientific application in Python and considering using Amazon EC2 to run the process on. My application is both memory and CPU hungry and would benefit from any resources given to it. An Extra Large Instance of EC2 gives about 15GB of memory, along wit...
Python & Amazon EC2 -- Using All Compute Units?
I'm building a scientific application in Python and considering using Amazon EC2 to run the process on. My application is both memory and CPU hungry and would benefit from any resources given to it. An Extra Large Instance of EC2 gives about 15GB of memory, along with 8 compute units. My question is, can a single Pytho...
[ "Python has a GIL that makes it complex to write multi-threaded applications that fully utilize more than one core. You can read more about it here How do threads work in Python, and what are common Python-threading specific pitfalls? or here http://www.dabeaz.com/python/UnderstandingGIL.pdf if you're really into t...
[ 4, 3 ]
[]
[]
[ "amazon_ec2", "python" ]
stackoverflow_0006244768_amazon_ec2_python.txt
Q: How do I insert video greater than 1MB with gdata.youtube api direct method I am using the gdata.youtube service to insert a video entry. It is failing with a url fetch error complaining that the file is too large. It is a pretty small video (1.7MB). In an ideal world, there is a natural way to break up the file a...
How do I insert video greater than 1MB with gdata.youtube api direct method
I am using the gdata.youtube service to insert a video entry. It is failing with a url fetch error complaining that the file is too large. It is a pretty small video (1.7MB). In an ideal world, there is a natural way to break up the file as necessary and stream it in chunks. Is there an api to do this already. Here is ...
[ "Url fetch has a limit of 1 megabyte for request size. Check the appengine docs for quotas and other limits \n" ]
[ 0 ]
[]
[]
[ "gdata", "python", "video", "youtube" ]
stackoverflow_0002608712_gdata_python_video_youtube.txt
Q: How to create view/python reference on scipy sparse matrix? I am working on an algorithm that uses diagonal and first off-diagonal blocks of a large (will be e06 x e06) block diagonal sparse matrix. Right now I create a dict that stores the blocks in such a way that I can access the blocks in a matrix like fashion...
How to create view/python reference on scipy sparse matrix?
I am working on an algorithm that uses diagonal and first off-diagonal blocks of a large (will be e06 x e06) block diagonal sparse matrix. Right now I create a dict that stores the blocks in such a way that I can access the blocks in a matrix like fashion. For example B[0,0](5x5) gives the first block of matrix A(20x20...
[ "As far as I know, all of the various sparse matricies in scipy.sparse return copies rather than a view of some sort. (Some of the others may be significantly faster at doing so than lil_matrix, though!)\nOne way of doing what you want is to just work with slice objects. For example:\nimport scipy.sparse\n\nclass ...
[ 4 ]
[]
[]
[ "python", "scipy", "sparse_matrix", "view" ]
stackoverflow_0006230847_python_scipy_sparse_matrix_view.txt
Q: Python 3.2 Idle vs terminal In python 3.2 under OSX, if I'll run "type(sys.stdin)" under Idle I get a strange answer as shown below >>> type(sys.stdin) <class 'idlelib.rpc.RPCProxy'> >>> But if I'll reun the same command under terminal, I get: >>> import sys >>> type(sys.stdin) <class '_io.TextIOWrapper'> >>> ...
Python 3.2 Idle vs terminal
In python 3.2 under OSX, if I'll run "type(sys.stdin)" under Idle I get a strange answer as shown below >>> type(sys.stdin) <class 'idlelib.rpc.RPCProxy'> >>> But if I'll reun the same command under terminal, I get: >>> import sys >>> type(sys.stdin) <class '_io.TextIOWrapper'> >>> I understand this is because I'm ...
[ "This is a filed Python bug:\nhttp://bugs.python.org/issue9290\n\nThe fact that in IDLE sys.stdin is a\n idlelib.rpc.RPCProxy results in\n programs having different behavior in\n IDLE and in Command Line mode.\nI noticed that when grading many\n students exercises in IDLE. Things\n like:\nsys.stdin.readlines()...
[ 6 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0006244956_python_python_idle.txt
Q: How to limit I/O consumption of Python processes (possibly using ionice)? I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using nice to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value...
How to limit I/O consumption of Python processes (possibly using ionice)?
I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using nice to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot...
[ "psutil exposes this functionality (python 2.4 -> 3.2):\nimport psutil, os\np = psutil.Process(os.getpid())\np.ionice(psutil.IOPRIO_CLASS_IDLE)\n\nAlso, starting from Python 3.3 this will be available in python stdlib as well:\nhttp://bugs.python.org/issue10784\n", "Hm.\nAs a start pointer, you should find what s...
[ 17, 5, 3 ]
[]
[]
[ "linux", "performance", "python", "unix" ]
stackoverflow_0000702407_linux_performance_python_unix.txt
Q: CMS or web framework a simple project There's not really anything on my planned site that would require a whole lot of customization but I'm looking for something that has built in functionality for forums, comments, reviews, a blog, a database that can queried by users, and some social networking features. I have...
CMS or web framework a simple project
There's not really anything on my planned site that would require a whole lot of customization but I'm looking for something that has built in functionality for forums, comments, reviews, a blog, a database that can queried by users, and some social networking features. I have a decent amount of experience using python...
[ "Pick up one of the many CMS projects in Django, like Mezzanine or Pinax, or Django cms or any of a number of others see http://oswco.com/2011/may/20/cms-frameworks-what-use-django-vs-drupal/ for a more complete set of references or discussions. You will be way happier and in something that can be more easily scale...
[ 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "content_management_system", "django", "python", "wordpress" ]
stackoverflow_0006244906_content_management_system_django_python_wordpress.txt
Q: Python combinatorials w/o repetition - Pyncomb? I'm trying to do some combinatorial stuff with data in Python. I looked the question How to generate all permutations of a list in Python, but think that doesn't fit my needs.. I have data of this type...: group1-Steve group1-Mark group1-Tom group2-...
Python combinatorials w/o repetition - Pyncomb?
I'm trying to do some combinatorial stuff with data in Python. I looked the question How to generate all permutations of a list in Python, but think that doesn't fit my needs.. I have data of this type...: group1-Steve group1-Mark group1-Tom group2-Brett group2-Mick group2-Foo group3-Dan ...
[ "The easiest way is to use itertools.product():\ngroup1 = [\"Steve\", \"Mark\", \"Tom\"]\ngroup2 = [\"Brett\", \"Mick\", \"Foo\"]\ngroup3 = [\"Dan\", \"Phil\"]\nfor x in itertools.product(group1, group2, group3):\n print x\n\nprints\n('Steve', 'Brett', 'Dan')\n('Steve', 'Brett', 'Phil')\n('Steve', 'Mick', 'Dan')...
[ 9, 4 ]
[]
[]
[ "combinatorics", "python" ]
stackoverflow_0006245108_combinatorics_python.txt
Q: How to get two line above a selected string? Say i had text like this: www.something.com get the 2 above www.somethingss.com get the 2 above www.somethingssss.com get the 2 above Maybe something like this: for a in text: if 'get the 2 above' in a: get 2 above How would i do this? A: Assuming ...
How to get two line above a selected string?
Say i had text like this: www.something.com get the 2 above www.somethingss.com get the 2 above www.somethingssss.com get the 2 above Maybe something like this: for a in text: if 'get the 2 above' in a: get 2 above How would i do this?
[ "Assuming the above is a string:\ns = '''www.something.com\n\nget the 2 above\n\nwww.somethingss.com\n\nget the 2 above\n\nwww.somethingssss.com\n\nget the 2 above'''\n\ns = s.splitlines()\nfor i, line in enumerate(s):\n if 'get the 2 above' in line:\n print s[i-1], s[i-2]\n\ns.splitlines() removes the ne...
[ 3, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006244942_python.txt
Q: Losing elements in python code while creating a dictionary from a list? I have some headache with this python code. print "length:", len(pub) # length: 420 pub_dict = dict((p.key, p) for p in pub) print "dict:", len(pub_dict) # length: 163 If I understand this right, I get a dictionary containing the ...
Losing elements in python code while creating a dictionary from a list?
I have some headache with this python code. print "length:", len(pub) # length: 420 pub_dict = dict((p.key, p) for p in pub) print "dict:", len(pub_dict) # length: 163 If I understand this right, I get a dictionary containing the attribute p.key as key and the object p as its value for each element of pub....
[ "Since you may have several p with the same key then you may use list as value for you key within new dicitionary:\npub_dict = {} \nfor p in pub:\n if not p.key in pub_dict:\n pub_dict[p.key] = []\n pub_dict[p.key].append(p)\n\nOr if it is neccessary for you to uniquely identify each record you may use ...
[ 4 ]
[ "pub_dict = {}\nfor i,p in enumerate(pub):\n pub_dict[p.key] = p\n print i+1,len(pub_dict)\n\nwould have give you light on the problem\n" ]
[ -1 ]
[ "dictionary", "list_comprehension", "python" ]
stackoverflow_0006245382_dictionary_list_comprehension_python.txt
Q: GAE: Model loses track of parent->child relationship I'm having what seems like a very strange problem with an Entity relationship in the google app engine data store. I'm work on a Python/GAE webapp (learning exercise), the full code to which can be found on sourceforge. I have 2 models: Gallery - a search ter...
GAE: Model loses track of parent->child relationship
I'm having what seems like a very strange problem with an Entity relationship in the google app engine data store. I'm work on a Python/GAE webapp (learning exercise), the full code to which can be found on sourceforge. I have 2 models: Gallery - a search term and (indirectly) a list of photos Photo - information a...
[ "So, after much digging around, I believe I found an answer...\n\nWhen a file is modified (the timestamp changes), the app engine invalidates the compiled/cached files it has\nWhen the Photo class is defined, it adds a property to the Gallery based on the collection of ids it has for them\nWhen it needs the Gallery...
[ 2 ]
[]
[]
[ "database", "google_app_engine", "python" ]
stackoverflow_0006244543_database_google_app_engine_python.txt
Q: Django ORM & Unit of Work Is there any easy way / library / external app to introduce Unit of Work concept to Django ORM? What approaches or techniques do you use to solve the problem of importing the same row twice in a complicated model setup without loosing all the modularity? EDIT Example Consider the followin...
Django ORM & Unit of Work
Is there any easy way / library / external app to introduce Unit of Work concept to Django ORM? What approaches or techniques do you use to solve the problem of importing the same row twice in a complicated model setup without loosing all the modularity? EDIT Example Consider the following examplatory situation - there...
[ "I'm not entirely sure what you're asking, but a few years ago David Cramer wrote a library called Django-identitymapper - could that fit the bill?\n", "You can execute raw SQL, or manage the transactions. Managers also make it very easy to implement custom functionality and precise control over your models. You ...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_orm", "orm", "python" ]
stackoverflow_0006245498_django_django_models_django_orm_orm_python.txt
Q: python & SQLite in Production When using python, can SQLite be used as production database to manage say 10,000 databases files (each in a separate file -- of size 500[MB])? Only one thread will be used to write data to the database files (no concurrency). Are there alternatives libraries that can work better / fa...
python & SQLite in Production
When using python, can SQLite be used as production database to manage say 10,000 databases files (each in a separate file -- of size 500[MB])? Only one thread will be used to write data to the database files (no concurrency). Are there alternatives libraries that can work better / faster / more reliably?
[ "Maybe you'll look at this page titled \"appropriate uses for sqlite\". To quote:\n\nThe basic rule of thumb for when it is\n appropriate to use SQLite is this: Use\n SQLite in situations where simplicity\n of administration, implementation, and\n maintenance are more important than\n the countless complex fea...
[ 7, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006244892_python_sqlite.txt
Q: Sanitize python slice? I am using Python/ctypes to wrap a C library. One of the structures I am wrapping resembles a numerical vector, and I would like the getitem() method of the corresponding Python class to support slices. At the C - level I have slice-aware function like this: void * slice_copy( void * ptr ,...
Sanitize python slice?
I am using Python/ctypes to wrap a C library. One of the structures I am wrapping resembles a numerical vector, and I would like the getitem() method of the corresponding Python class to support slices. At the C - level I have slice-aware function like this: void * slice_copy( void * ptr , int index1 , int index2 , i...
[ "There is indeed a function in the interface. slice objects have an indices() method that accepts the length of the sequence as parameter and returns the normalised start, stop and step values as a tuple.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0006246084_ctypes_python.txt
Q: How can Python regex ignore case inside a part of a pattern but not the entire expression? Say I have a string containing foobar fooBAR FOObar FOOBAR, and I want to search all instances containing a case insensitive "foo" or "FOO" but a lowercase "bar". In this case, re.findall should return ['foobar', 'FOObar']. ...
How can Python regex ignore case inside a part of a pattern but not the entire expression?
Say I have a string containing foobar fooBAR FOObar FOOBAR, and I want to search all instances containing a case insensitive "foo" or "FOO" but a lowercase "bar". In this case, re.findall should return ['foobar', 'FOObar']. The accepted answer for this question explains that it can be done in C# with (?i)foo(?-i)bar, b...
[ "Python does not support disabling flags in the same manner; you will have to handle it differently.\n>>> re.match('[Ff][Oo]{2}bar', 'Foobar')\n<_sre.SRE_Match object at 0x7eff94dac920>\n\n", "The re module doesn't support scoped flags, but there's an alternative regex implementation which does:\nhttp://pypi.pyth...
[ 7, 4 ]
[]
[]
[ "case_insensitive", "case_sensitive", "python", "regex" ]
stackoverflow_0006246096_case_insensitive_case_sensitive_python_regex.txt
Q: In Django, how can I use a request to determine its URLconf viewname? I can get the view function from request.path: from django.core.urlresolvers import resolve view_func, _args, _kwargs = resolve(request.path) However, I need something more. I need to take a list of view names, like ['edit_foo', 'delete_foo'], ...
In Django, how can I use a request to determine its URLconf viewname?
I can get the view function from request.path: from django.core.urlresolvers import resolve view_func, _args, _kwargs = resolve(request.path) However, I need something more. I need to take a list of view names, like ['edit_foo', 'delete_foo'], and find out if the current URL is for one of those. I've come up with a co...
[ "After writing that long question, I figured it out :/ (posting for whoever else runs into this, by chance). It's quite simple:\n>>> resolve(request.path).url_name\n'edit_foo'\n\nI must have been mistaken about the resolve function's usefulness, which is vast.\n" ]
[ 5 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0006246360_django_django_urls_python.txt
Q: form.save() not saving For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work. Any help is appre...
form.save() not saving
For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work. Any help is appreciated. Here is the relevant...
[ "To properly debug your code, change your template to:\n<form action=\"/todo/\" method=\"post\"> {{ csrf_token }}\n {{ form.errors }}\n {{ form.as_p }}\n <input type=\"submit\" value=\"Add Task\" />\n</form>\n\nAnd your view to:\ndef create_task(request):\n if request.method == 'POST':\n form = a...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006233514_django_django_forms_python.txt
Q: How to secure a Python distributed computing layer These modules are designed to facilitate a layer of computational capacity across multiple computers. What one or more proven methods are available which will secure against spoofed packets? How can I best make a deep copy of any not included objects referenced by...
How to secure a Python distributed computing layer
These modules are designed to facilitate a layer of computational capacity across multiple computers. What one or more proven methods are available which will secure against spoofed packets? How can I best make a deep copy of any not included objects referenced by the transmitted callable? Is a function object the best...
[ "I've taken a closer look at your code now, and I've got some comments:\n\nThis code looks like it can easily protect against accidental modification of the pickled objects while they are in flight. sha224 is an excellent hashing algorithm, and will easily notice packets that have been accidentally modified that mi...
[ 6 ]
[]
[]
[ "distributed_computing", "hash", "python" ]
stackoverflow_0006246548_distributed_computing_hash_python.txt
Q: Security Flaw in my Python Program I am working on a small program that requires the user to insert a USB Flash Drive (pre configured) to login to the system. The way it works right now is you log in to the windows OS, like usual. Then the script checks for the USB key, and if found, closes. But, if the key isn't ...
Security Flaw in my Python Program
I am working on a small program that requires the user to insert a USB Flash Drive (pre configured) to login to the system. The way it works right now is you log in to the windows OS, like usual. Then the script checks for the USB key, and if found, closes. But, if the key isn't found, the a dialog appears for the user...
[ "From your comments, you're logging the user into a Windows session. You won't be able to secure the system with the scheme you've set up - you've discovered the first of what will be many easily-exploited vulnerabilities. Look into credential providers (and GINA for editions of Windows older than Vista) - they're ...
[ 4 ]
[]
[]
[ "python", "security", "usb", "windows" ]
stackoverflow_0006246739_python_security_usb_windows.txt
Q: Appengine ACL with Google Authentication I would like to implement ACL with Google Authentication. Need some pointer regarding the possibility of the same. Use case: Page X accessible only to myadmin@gmail.com Page Y accessible for all belong to a group Y. After registration a moderator will add/reject the user t...
Appengine ACL with Google Authentication
I would like to implement ACL with Google Authentication. Need some pointer regarding the possibility of the same. Use case: Page X accessible only to myadmin@gmail.com Page Y accessible for all belong to a group Y. After registration a moderator will add/reject the user to the group Y. Pages are not accessible if use...
[ "You'll need to do this yourself: Implement the ACL with a datastore model keyed by the user's user_id, and fetch and check it on each request. The Users API doesn't provide anything like this built-in.\n", "Here's an answer to the admin part only and possible suggestions on how to do the other part of your quest...
[ 5, 0 ]
[]
[]
[ "authentication", "authorization", "django", "google_app_engine", "python" ]
stackoverflow_0006239612_authentication_authorization_django_google_app_engine_python.txt
Q: python/django function returning identical value every time I have a function that looks like this: def getCurrentShow(hour=(localtime().tm_hour),day=datetime.datetime.now().strftime('%A')): return Schedule.objects.get(hour=hour,day=day).show so I can call it with or without a time or day. My problem is t...
python/django function returning identical value every time
I have a function that looks like this: def getCurrentShow(hour=(localtime().tm_hour),day=datetime.datetime.now().strftime('%A')): return Schedule.objects.get(hour=hour,day=day).show so I can call it with or without a time or day. My problem is that when I call it with no arguments ie: print getCurrentShow() ...
[ "The default values for your function arguments are calculated the first time the function is loaded by the interpreter. What you want is the following:\ndef getCurrentShow(hour=None, day=None):\n hour = hour or localtime().tm_hour\n day = day or datetime.datetime.now().strftime('%A')\n return Schedule.obj...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006247064_django_python.txt
Q: Python: How to obtain an instance's name at runtime? I'm using PyQt. And because I'm using Qt Style Sheets, I have to set object names to widgets which I want to specify in my style rules (e.g "#deleteButton { font-size: 14px; }"). In code, I have to do: ... self.deleteButton = QToolButton(self) self.deleteButton....
Python: How to obtain an instance's name at runtime?
I'm using PyQt. And because I'm using Qt Style Sheets, I have to set object names to widgets which I want to specify in my style rules (e.g "#deleteButton { font-size: 14px; }"). In code, I have to do: ... self.deleteButton = QToolButton(self) self.deleteButton.setObjectName("deleteButton") ... But I would to do: ... ...
[ "Does this help?\nHow to obtain an instance's name at runtime?\n", "What you're trying to accomplish is better done with this code:\nfor name, obj in self.__dict__.iteritems():\n if isinstance(obj, QtCore.QObject) and not obj.objectName(): # QObject without a name\n obj.setObjectName(name)\n\nUse it at ...
[ 1, 1, 0 ]
[]
[]
[ "instance", "pyqt", "python", "runtime", "stylesheet" ]
stackoverflow_0004575275_instance_pyqt_python_runtime_stylesheet.txt
Q: Eclipse + Pydev + twitter library question I am working my way through 'Mining Twitter' by Matthew A. Russell. I have installed the twitter library from http://pypi.python.org/pypi/twitter but I can't seem to get this set of tools linked in correctly as an external library. I have added the following folders as ex...
Eclipse + Pydev + twitter library question
I am working my way through 'Mining Twitter' by Matthew A. Russell. I have installed the twitter library from http://pypi.python.org/pypi/twitter but I can't seem to get this set of tools linked in correctly as an external library. I have added the following folders as external libraries, but I still get an 'Unresolve...
[ "I recommend you, using easy_install for installing python modules. It's easy and clean. \n", "Fairly sure you simply made those folders and perhaps copied that .egg file in?\nWhat you should be doing, is relatively this:\nOpen up the terminal, and change your directory(cd) to where the twitter library is downloa...
[ 0, 0 ]
[]
[]
[ "eclipse", "linux", "python", "twitter" ]
stackoverflow_0005845536_eclipse_linux_python_twitter.txt
Q: How do you modify sys.path in Google App Engine (Python)? I've tried adding the following line to my handler script (main.py), but it doesn't seem to work: sys.path.append('subdir') subdir lives in the my root directory (i.e. the one containing app.yaml). This doesn't seem to work, because when I try to import m...
How do you modify sys.path in Google App Engine (Python)?
I've tried adding the following line to my handler script (main.py), but it doesn't seem to work: sys.path.append('subdir') subdir lives in the my root directory (i.e. the one containing app.yaml). This doesn't seem to work, because when I try to import modules that live in subdir, my app explodes.
[ "1) Ensure you have a blank __init__.py file in subdir. \n2) Use a full path; something like this: \nimport os\nimport sys\n\nsys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))\n\n\nEdit: providing more info to answer questions asked in a comment. \nAs Nick Johnson demonstrates you can place tho...
[ 21, 2 ]
[]
[]
[ "google_app_engine", "python", "sys.path" ]
stackoverflow_0002354166_google_app_engine_python_sys.path.txt
Q: Detect the size of an image in HTML, using python I'm trying to implement a similar functionality to Facebook's thumbnail preview. The idea is, a user enters the URL of a product, and selects the best image of that product. In order to filter out images that obviously aren't a product, I want to filter them based ...
Detect the size of an image in HTML, using python
I'm trying to implement a similar functionality to Facebook's thumbnail preview. The idea is, a user enters the URL of a product, and selects the best image of that product. In order to filter out images that obviously aren't a product, I want to filter them based on height and width > 150px. I'm using python and Beaut...
[ "GD is a library that's been around for quite some time and it has a pretty easy interface to work with...Here's a link to GD\nSee the \"size\" method to get width and height.\nEDIT\nAh, how about this? \n\nParse the HTML content and retrieve URLs to the CSS file(s) and inline styles\nDownload the CSS file(s) and ...
[ 0 ]
[]
[]
[ "css", "html", "image", "python" ]
stackoverflow_0006246983_css_html_image_python.txt
Q: Simple Django template question I have a template variable: {{article.pub_date}} that outputs this: May 25, 2011, 7:52 p.m. How can I get just the date without the time: May 25, 2011 without the: , 7:52 p.m. I only have access to the template tags/variables not the python code. A: {{ article.pub_date|d...
Simple Django template question
I have a template variable: {{article.pub_date}} that outputs this: May 25, 2011, 7:52 p.m. How can I get just the date without the time: May 25, 2011 without the: , 7:52 p.m. I only have access to the template tags/variables not the python code.
[ "{{ article.pub_date|date:\"DATE_FORMAT\" }}\n\nhttps://docs.djangoproject.com/en/dev/ref/templates/builtins/#date\n", "{{article.pub_date|date:\"F j, Y\"}}\n\nDjango uses the same formatting as PHP date objects.\n", "Also you can set a default format if you want a format used all over the site\nhttps://docs.dj...
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006243762_django_python.txt
Q: Whats the easy way to build search engine for website in python I have one website in django , with many content pages. I want to build the search engine so that if i search for keywords then i get the URL of that Page. It can be any library or scripts. My Main rquirements is that i should be able to tweak the scr...
Whats the easy way to build search engine for website in python
I have one website in django , with many content pages. I want to build the search engine so that if i search for keywords then i get the URL of that Page. It can be any library or scripts. My Main rquirements is that i should be able to tweak the script or add my own code so that in future i can build the index accord...
[ "A pure python search library would be whoosh:\n\nhttp://whoosh.ca/\nhttp://www.arnebrodowski.de/blog/add-full-text-search-to-your-django-project-with-whoosh.html\n\n" ]
[ 1 ]
[]
[]
[ "full_text_search", "linux", "python" ]
stackoverflow_0006247705_full_text_search_linux_python.txt
Q: uwsgi + python + nginx + willy nilly file execution I'm using uwsgi on Nginx to run some Python code. I'd like to bind uwsgi to a directory and make it render any .py file that I call from the server in the browser. I'm thinking like PHP, here (/index.php executes that file, /login.php executes that file). Is this...
uwsgi + python + nginx + willy nilly file execution
I'm using uwsgi on Nginx to run some Python code. I'd like to bind uwsgi to a directory and make it render any .py file that I call from the server in the browser. I'm thinking like PHP, here (/index.php executes that file, /login.php executes that file). Is this a possibility? Or am I only able to explicitly specify a...
[ "WSGI is not like PHP. You can't just point uwsgi to a directory with a bunch of .py files. In fact, never, ever make your python modules available in a public directory, accessible from the server. You need to hook uwsgi up to a WSGI application, preferably a framework. Read more about WSGI here. Check out bottle ...
[ 10, 3 ]
[]
[]
[ "nginx", "python", "uwsgi" ]
stackoverflow_0006247667_nginx_python_uwsgi.txt
Q: Python - Tree traversal question I have a hard time with tree traversal, and so avoid it like the plague... normally. I have a class that's sort-of (slightly simplified version here, but functionally the same) like: class Branch(object): def __init__(self, title, parent=None): self.title = title ...
Python - Tree traversal question
I have a hard time with tree traversal, and so avoid it like the plague... normally. I have a class that's sort-of (slightly simplified version here, but functionally the same) like: class Branch(object): def __init__(self, title, parent=None): self.title = title self.parent = parent I have a dicti...
[ "http://en.wikipedia.org/wiki/Depth-first_search\nhttp://en.wikipedia.org/wiki/Tree_traversal\nYou traverse as follows in two passes:\n\nFirst pass: Search for the query node with the appropriate key. (This step is unnecessary if you have a hashmap of all the nodes in the entire tree; you have this (good) so this s...
[ 6 ]
[]
[]
[ "algorithm", "binary_tree", "python", "tree_traversal" ]
stackoverflow_0006247751_algorithm_binary_tree_python_tree_traversal.txt
Q: Get Primary Key after Saving a ModelForm in Django How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. def contact_create(request): if request.method == ...
Get Primary Key after Saving a ModelForm in Django
How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact. def contact_create(request): if request.method == 'POST': form = ContactForm(request.POST) ...
[ "The ModelForm's save method returns the saved object.\nTry this:\ndef contact_create(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n new_contact = form.save()\n return HttpResponseRedirect(reverse(contact_details, args=(new_...
[ 66, 13 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0000732952_django_django_forms_django_models_python.txt
Q: How to compress your django project ( along w/ the dependent Python modules ) into one file that can be run on a server The basic core of the problem I've expressed being - portability of the Django Project. I want to give my testing team the project as a single file. How do I go about doing it? A: disutils wi...
How to compress your django project ( along w/ the dependent Python modules ) into one file that can be run on a server
The basic core of the problem I've expressed being - portability of the Django Project. I want to give my testing team the project as a single file. How do I go about doing it?
[ "disutils will allow you to package your project into a single archive that can be extracted and installed.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006248080_django_python.txt
Q: How can i grab the hyperlinks in web page using python I have web page in which i have the structure like <div> <ul> <li class=tree> <a> </a> </li> </ul> </div> NOw i want to grab all those hyperlinks and put in text file in python A: Use BeautifulSoup A: You can use the module xml.dom.minidom, though it is ...
How can i grab the hyperlinks in web page using python
I have web page in which i have the structure like <div> <ul> <li class=tree> <a> </a> </li> </ul> </div> NOw i want to grab all those hyperlinks and put in text file in python
[ "Use BeautifulSoup\n", "You can use the module xml.dom.minidom, though it is not ported to certain versions of python3 if that is an issue.\n" ]
[ 2, 0 ]
[]
[]
[ "html_parsing", "lxml", "python", "urllib2" ]
stackoverflow_0006248099_html_parsing_lxml_python_urllib2.txt
Q: Django models and legacy class integration If I have existing classes (generated off some UML model) from legacy code, what is the best way to integrate them with the Django model classes? I have so far considered using the Django custom fields to serialize the class and let that handle persistence. (The disadvan...
Django models and legacy class integration
If I have existing classes (generated off some UML model) from legacy code, what is the best way to integrate them with the Django model classes? I have so far considered using the Django custom fields to serialize the class and let that handle persistence. (The disadvantage of this being that other applications acces...
[ "If you are trying to move a legacy app to django, I agree with @chrisdpratt and you should try to convert your classes to Django models. It will require a large effort, so when you are ready, you can follow this trail:\n\nCreate a legacy app and put your legacy code there.\nIf you decide your code is not so impor...
[ 2 ]
[]
[]
[ "database", "django", "django_models", "python" ]
stackoverflow_0006224208_database_django_django_models_python.txt
Q: If i have to choose only one html scraping library for python, which should i choose I need to do lot html parsing / scraping /search engine /crawling. There are many libraries currently like Scrapy, Beautiful Soup, lxml , lxml2 requests, pyquery. Now i don't want to try each of these and then decide. basically i ...
If i have to choose only one html scraping library for python, which should i choose
I need to do lot html parsing / scraping /search engine /crawling. There are many libraries currently like Scrapy, Beautiful Soup, lxml , lxml2 requests, pyquery. Now i don't want to try each of these and then decide. basically i want to follow on one and then study in detail and then use that most often. So which libr...
[ "I'm using Beautiful Soup and am very happy with it. So far it answered all my scraping needs. Two main benefits:\n\nIt's pretty good at handling non-perfect HTML. Since browsers are quite lax, many HTML documents aren't 100% well-formed\nIn addition to high-level access APIs, it has low-level APIs which make it ex...
[ 1, 1 ]
[]
[]
[ "parsing", "python", "search", "web_crawler" ]
stackoverflow_0006248424_parsing_python_search_web_crawler.txt
Q: how do I start writing simple Json Rest enable server app in python how do I start write simple (like Hello World) Json Rest enable server app in python, which I can run in Google App Engine. Thanking you A: I used this project for a GAE rest application : http://code.google.com/p/appengine-rest-server/ The docu...
how do I start writing simple Json Rest enable server app in python
how do I start write simple (like Hello World) Json Rest enable server app in python, which I can run in Google App Engine. Thanking you
[ "I used this project for a GAE rest application :\nhttp://code.google.com/p/appengine-rest-server/\nThe documentation is good and there are some examples to understand how it works.\nVery easy to use.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006248216_python.txt
Q: How to detect lines with only a white space in a text? Given that "empty line" is a white space: I am trying to read a text file line by line. I want to ignore whitespace lines. Or in a more correct way, I want to detect empty lines. An empty line can contain spaces, newline characters, etc. And it is still consid...
How to detect lines with only a white space in a text?
Given that "empty line" is a white space: I am trying to read a text file line by line. I want to ignore whitespace lines. Or in a more correct way, I want to detect empty lines. An empty line can contain spaces, newline characters, etc. And it is still considered as an empty line. If you open it up in notepad, in an e...
[ "for line in someopenfile:\n if line.isspace():\n empty_line()\n\n", "Using strip() on any string returns a string with all leading and trailing whitespace stripped. So calling that on a line with only whitespace gives you an empty string. You can then just filter on strings with non-zero length.\n>>> lines=[...
[ 10, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006248932_python_string.txt
Q: EXIF like thing for Videos Is there any standard way to get information from a video file? For images we have EXIF data which can be used to get information about the date/time , size etc of the image file. I was wondering if there is such a thing for videos as well. The use case is - I have lot of videos which I ...
EXIF like thing for Videos
Is there any standard way to get information from a video file? For images we have EXIF data which can be used to get information about the date/time , size etc of the image file. I was wondering if there is such a thing for videos as well. The use case is - I have lot of videos which I shot from my digital camera. I w...
[ "exiftool reads video containers and their metadata.\n", "Unfortunately, most cameras don't actually store enough metadata in the video :(. \nIf they are storing it, due to the wide variety of video codecs and containers like AVI, MOV, MPG, MP4, etc., a good option will to run ffmpeg -i to read it. \n" ]
[ 7, 2 ]
[]
[]
[ "c", "c++", "exif", "perl", "python" ]
stackoverflow_0006248347_c_c++_exif_perl_python.txt
Q: elegant way of using a range using an if statement? I've got this very crude way of writing this IF statement . for a in range (2,3000): if ( a % 1) == 0 and ( a % 2) == 0 and ( a % 3) == 0 and ( a % 4) == 0 and ( a % 5) == 0 and ( a % 6) == 0 and ( a % 7) == 0 and ( a % 8) == 0 and ( a % 9) == 0 and ( a % 10...
elegant way of using a range using an if statement?
I've got this very crude way of writing this IF statement . for a in range (2,3000): if ( a % 1) == 0 and ( a % 2) == 0 and ( a % 3) == 0 and ( a % 4) == 0 and ( a % 5) == 0 and ( a % 6) == 0 and ( a % 7) == 0 and ( a % 8) == 0 and ( a % 9) == 0 and ( a % 10) == 0 : print a I assume there is a much better way...
[ "For a more-or-less direct translation, how about\nfor a in range(2, 3000):\n if all(a % k == 0 for k in range(1,11)):\n print a\n\nalthough of course a % 1 == 0 for all integers a, so that check is unnecessary.\n", "What you need is the multiples of LCM(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) which fall within ...
[ 12, 7 ]
[]
[]
[ "python" ]
stackoverflow_0006248639_python.txt
Q: Need help creating an exe from python script I am wanting to create an exe version of my python script so and I am using a friends computer to test. The script creates a basic text editor which can load, save etc. I am using http://www.py2exe.org/ to create the exe. and I have been using this tutorial: http://www....
Need help creating an exe from python script
I am wanting to create an exe version of my python script so and I am using a friends computer to test. The script creates a basic text editor which can load, save etc. I am using http://www.py2exe.org/ to create the exe. and I have been using this tutorial: http://www.py2exe.org/index.cgi/Tutorial Everything works fin...
[ "You can either build both an x86 and x64 (32-bit and 64-bit) version, or you can build it only as a 32-bit version.\nThe 32-bit version will run on both 64-bit and 32-bit Windows systems.\n" ]
[ 3 ]
[]
[]
[ "exe", "python" ]
stackoverflow_0006249451_exe_python.txt
Q: Socket not visible using Python on Ubuntu Server I'm writing an application that is supposed to listen for a client, and when it connects, it should grab some data. It works fine when I run it locally on either my own computer, or the server, but when I try and run it on the server, and connect from my computer, i...
Socket not visible using Python on Ubuntu Server
I'm writing an application that is supposed to listen for a client, and when it connects, it should grab some data. It works fine when I run it locally on either my own computer, or the server, but when I try and run it on the server, and connect from my computer, it doesn't work at all. The connection times out. I've ...
[ "Instead of server.bind((self.HOST, self.PORT)), try:\nserver.bind(('', self.PORT))\n\nFor IPv4 addresses the empty string represents INADDR_ANY; when receiving a socket bound to this address, your process will receive packets from all interfaces (not just the loop-back or the primary Ethernet interface).\n" ]
[ 3 ]
[]
[]
[ "python", "sockets", "ubuntu" ]
stackoverflow_0006247511_python_sockets_ubuntu.txt
Q: md5 a string multiple times get different result on different platform t.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> static char* unsigned_to_signed_char(const unsigned char* in , int len) { char* res = (char*)malloc(len * 2 + 1); int i = 0; memset(res , 0 , len * 2...
md5 a string multiple times get different result on different platform
t.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md5.h> static char* unsigned_to_signed_char(const unsigned char* in , int len) { char* res = (char*)malloc(len * 2 + 1); int i = 0; memset(res , 0 , len * 2 + 1); while(i < len) { sprintf(res + i * 2 , "%02x" , in[i]); i +...
[ "I think you are allocating bytes exactly for MD5 result, without ending \\0. Then you are calculating MD5 of block of memory that starts with result from previous MD5 calculating but with some random bytes after it. You should allocate one byte more for result and set it to \\0.\nMy proposal:\n...\nunsigned char *...
[ 1, 1, 0 ]
[]
[]
[ "md5", "openssl", "python" ]
stackoverflow_0006249080_md5_openssl_python.txt
Q: How can access MySQL with Python? How can I access MySQL with Python on windows environment ? I took a look to MySQLdb but in the README says: "I don't do Windows. However if someone provides me with a package for Windows, I'll make it available." So is there easy way to access MySQL on Windows or I should insta...
How can access MySQL with Python?
How can I access MySQL with Python on windows environment ? I took a look to MySQLdb but in the README says: "I don't do Windows. However if someone provides me with a package for Windows, I'll make it available." So is there easy way to access MySQL on Windows or I should install Red Hat & go from there?
[ "The README doesn't mean MySQLdb isn't available for Windows. It only means that the library's maintainer doesn't provide binaries for Windows.\nYou can still get these binaries for Windows either by 1) compiling them yourself or 2) getting them compiled from some third party.\nI suggest you to do the latter:\n\nCh...
[ 5 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006249054_mysql_python.txt
Q: Python Error:Unindent does not match any outer uindentation limit As you can see I am a novice in Programming and started with Python, the above said error is occurring on the highlighted line of code. How to ride over this... import random secret= random.randint (1,100) guess=0 tries=0 print "AHOY! I am the de...
Python Error:Unindent does not match any outer uindentation limit
As you can see I am a novice in Programming and started with Python, the above said error is occurring on the highlighted line of code. How to ride over this... import random secret= random.randint (1,100) guess=0 tries=0 print "AHOY! I am the dead pirate Roberts, and I ahve a secret!" print "It is a number from 1 ...
[ "Python uses indentation to denote code blocks. The indentation of your code is not valid (the indentation of the if in question doesn't line up with any previous block; from a quick look over the code, there's at least one more error).\nThe following is a short clear explanation of how indentation works in Python:...
[ 2, 0 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0006249759_indentation_python.txt
Q: Allowing Users logged in with multiple accounts at once to the same Django site I'm creating a widget that gets installed on various different sites and I need distinct users for each site. Problem is, the same person browsing might have 2 different sites open at once that use my widget. This means that I need use...
Allowing Users logged in with multiple accounts at once to the same Django site
I'm creating a widget that gets installed on various different sites and I need distinct users for each site. Problem is, the same person browsing might have 2 different sites open at once that use my widget. This means that I need users to be logged in with multiple accounts simultaneously to the same Django site. Fr...
[ "I ended up storing the per-site data in the user's session, i.e. session['site_id_1'] = user_obj_1, session['site_id_2'] = user_obj_2, etc... \nInstead of logging in, I just store the user data in the appropriate key. Instead of logging out, I delete the key for the site.\n", "I think you have to rewrite the ses...
[ 1, 0 ]
[]
[]
[ "django", "django_sessions", "django_users", "python", "session" ]
stackoverflow_0006184994_django_django_sessions_django_users_python_session.txt
Q: Should Django Python apps be stored in the web server document root? As the title states, I'm trying to figure out the best practice for where to store application files for a Python website on the server. Document root, or no? I come from a land of PHP. :) EDIT - To that end, links to any material describing the ...
Should Django Python apps be stored in the web server document root?
As the title states, I'm trying to figure out the best practice for where to store application files for a Python website on the server. Document root, or no? I come from a land of PHP. :) EDIT - To that end, links to any material describing the best practice differences between Python and PHP are hugely appreciated.
[ "No. WSGI containers don't require the scripts to be in the document root, and so to increase security in case of a transient server error they shouldn't be placed in the document root.\n", "There's no reason to store it in the document root.\nWhile storing the app in the doc root isn't nessescarily a security pr...
[ 4, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006248772_django_python.txt
Q: numpy argmin elegant solution required. In python to find the index of the minimum value of the array I usey = numpy.argmin(someMat) Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way? A: "Can i find the minimum value of this matrix such that it does not...
numpy argmin elegant solution required.
In python to find the index of the minimum value of the array I usey = numpy.argmin(someMat) Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way?
[ "\"Can i find the minimum value of this matrix such that it does not lie within a specified range in a neat way?\"\nIf you only care about the minimum value satisfying some condition and not the location, then\n>>> numpy.random.seed(1)\n>>> m = numpy.random.randn(5.,5.)\n>>> m\narray([[ 1.62434536, -0.61175641, -0....
[ 7, 4 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0006249514_numpy_python_scipy.txt
Q: Checking if ForeignKeys are equal to one another I have a list of tuples of foreign keys of the form [(3,2),(2,3)]. And I want to insert the items into a ManyToMany table within a model: class Place(models.Model): data=models.IntegerField() connected_to=models.ManyToManyField('self') class PlaceMeta(mode...
Checking if ForeignKeys are equal to one another
I have a list of tuples of foreign keys of the form [(3,2),(2,3)]. And I want to insert the items into a ManyToMany table within a model: class Place(models.Model): data=models.IntegerField() connected_to=models.ManyToManyField('self') class PlaceMeta(models.Model): place=models.ForeignKey("places.Place")...
[ "You have one parameter too much in you call to add(). It should look like this:\nif place.data == conn_1 and conn_1 != conn_2:\n # place is the Place instance described by conn_1.\n # Let's connect it to conn_2!\n place.connected_to.add(conn_2)\n\nAnd you don't need to iterate through all the Places, ins...
[ 1 ]
[]
[]
[ "django", "foreign_keys", "mysql", "python" ]
stackoverflow_0006246285_django_foreign_keys_mysql_python.txt
Q: django object ids increment between unit tests I'm using Django 1.2.3-3+squeeze1 on Debian squeeze with PostgreSQL 8.4.7-0squeeze2 (though I don't think PostgreSQL is relevant here), and running Django unit tests based on unittest with the following setUp and tearDown def setUp(self): print "running set...
django object ids increment between unit tests
I'm using Django 1.2.3-3+squeeze1 on Debian squeeze with PostgreSQL 8.4.7-0squeeze2 (though I don't think PostgreSQL is relevant here), and running Django unit tests based on unittest with the following setUp and tearDown def setUp(self): print "running setup" self.c = Client() self.user = Us...
[ "You can reset the ID sequence on each table using the following SQL:\nSELECT pg_catalog.setval(pg_get_serial_sequence('table_name', 'id'), 1);\n\nYou should only do this if your table is empty.\n" ]
[ 5 ]
[]
[]
[ "django", "django_testing", "python", "unit_testing" ]
stackoverflow_0006249936_django_django_testing_python_unit_testing.txt
Q: Best Practice to link Multiple Files to model if number of Files can vary I have an Accounting Module with a model like this: class Accounting_period(models.Model): start_date = models.DateField() end_date = models.DateField() base_pdf = models.FileField() I have a management function that runs every ...
Best Practice to link Multiple Files to model if number of Files can vary
I have an Accounting Module with a model like this: class Accounting_period(models.Model): start_date = models.DateField() end_date = models.DateField() base_pdf = models.FileField() I have a management function that runs every night at midnight and once filter(end_date__lt=datetime.datetime.today()) it ge...
[ "You can use a ForeignKey (one-to-many relationship) for this:\nclass AccountingPeriodBackDated(models.Model):\n accounting_period= models.ForeignKey(AccountingPeriod, related_name=\"backdates\")\n pdf = models.FileField()\n\nThen use\ntemplates.py\n <ul>\n <li><a href=\"{{accounting_period_obj.base_pd...
[ 0 ]
[]
[]
[ "django_models", "filefield", "python" ]
stackoverflow_0004764515_django_models_filefield_python.txt
Q: Working with django and mod_wsgi in Windows I finished installing django on my Windows machine using Apache 2.2/Python 2.6/Django 1.3/mod_wsgi. It seems like everytime I change my Python code (such as settings.py), I need to restart Apache in order for changes to take effect. I understood that using WSGIRestrictEm...
Working with django and mod_wsgi in Windows
I finished installing django on my Windows machine using Apache 2.2/Python 2.6/Django 1.3/mod_wsgi. It seems like everytime I change my Python code (such as settings.py), I need to restart Apache in order for changes to take effect. I understood that using WSGIRestrictEmbedded should solve this issue but the docs for w...
[ "Read:\nhttp://blog.dscpl.com.au/2009/02/source-code-reloading-with-modwsgi-on.html\nIt refers you to how to enable auto reload on Windows when using Apache/mod_wsgi.\nUse of mod_wsgi is important when you need to test the multithread safety of your application and inbuilt development server is not multithreaded.\n...
[ 2, 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python", "windows" ]
stackoverflow_0006243015_apache_django_mod_wsgi_python_windows.txt
Q: How to link a Python project to a WSGI file? I want to link my Python project to a wsgi file. I am using mod_wsgi. I would like my Python project to be located in /var/www/myProject/start.py. I've configured Apache as follows: <VirtualHost *:80> ServerName www.example.me ServerAlias example.me ServerAd...
How to link a Python project to a WSGI file?
I want to link my Python project to a wsgi file. I am using mod_wsgi. I would like my Python project to be located in /var/www/myProject/start.py. I've configured Apache as follows: <VirtualHost *:80> ServerName www.example.me ServerAlias example.me ServerAdmin example@gmail.com DocumentRoot /usr/local/...
[ "It seems that you have start.py in a different directory which you want to invoke from wsgi.py.\n\nIn this case, you need to somehow tell wsgi.py to be able to import a module from a different folder. This thread has some details on that.\n\nA better way will be to have wsgi file in the same folder as the start.p...
[ 1, 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "web.py" ]
stackoverflow_0006240648_apache_mod_wsgi_python_web.py.txt
Q: sqlalchemy filter by count column I have a User query which filters by the amount of orders each user has (ordersCount). User.query.filter('ordersCount>2') If I run it it says: "Unknown column 'ordersCount' in 'where clause'" From my experience I should be using having on such operations because mysql won't allow...
sqlalchemy filter by count column
I have a User query which filters by the amount of orders each user has (ordersCount). User.query.filter('ordersCount>2') If I run it it says: "Unknown column 'ordersCount' in 'where clause'" From my experience I should be using having on such operations because mysql won't allow it for fields not part of the table bu...
[ "See documentation of Ordering, Grouping, Limiting, Offset...ing. Based on the sample code provided and an assumption that your orders are stored in the orders table, your version would look similar to:\n>>> s = select([orders.c.user_id, func.count(orders.c.id)]).\\\n... group_by(orders.c.user_id).having(func.c...
[ 22 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006244038_python_sqlalchemy.txt
Q: Taking Snapshot of a PDF using Python Possible Duplicate: Converting a PDF to a series of images with Python I know the code to open a PDF file using Python: import os os.startfile('C:\file_name.pdf') My query is that whether it is possible for me to save a particular page of the pdf file as an image file (jpeg...
Taking Snapshot of a PDF using Python
Possible Duplicate: Converting a PDF to a series of images with Python I know the code to open a PDF file using Python: import os os.startfile('C:\file_name.pdf') My query is that whether it is possible for me to save a particular page of the pdf file as an image file (jpeg, png)?
[ "It's look helpful for you: Converting a PDF to a series of images with Python\n" ]
[ 1 ]
[]
[]
[ "image", "pdf", "png", "python" ]
stackoverflow_0006250785_image_pdf_png_python.txt
Q: Consolidate dictionary based on repeat values I have a dictionary set up like this { "key1" : [1,2,4], "key2" : [2,4], "key3" : [1,2,4], "key4" : [2,4], .... } What I want is something like this. [ [ ["key1", "key3"], [1,2,4], ], [ ["key2", "key4"], [2,4], ]...
Consolidate dictionary based on repeat values
I have a dictionary set up like this { "key1" : [1,2,4], "key2" : [2,4], "key3" : [1,2,4], "key4" : [2,4], .... } What I want is something like this. [ [ ["key1", "key3"], [1,2,4], ], [ ["key2", "key4"], [2,4], ], ..... ] A list of keys and values based on uni...
[ "You can invert the dictionnary like this :\norig = {\n \"key1\" : [1,2,4],\n \"key2\" : [2,4],\n \"key3\" : [1,2,4],\n \"key4\" : [2,4],\n}\n\nnew_dict = {}\n\nfor k, v in orig.iteritems():\n new_dict.setdefault(tuple(v), []).append(k) #need to \"freeze\" the mutable type into an immutable to...
[ 5, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006184838_dictionary_list_python.txt
Q: Getting LONG_BIT error when installing gammu in Mac OS X using GCC 4 I'm trying to install Python-Gammu on a mac running Snow Leopard. I successfully configured gammu with cmake and GCC 4, but am getting this error on install. It seems to indicate an improperly configured gcc, but i'm not sure what can be done a...
Getting LONG_BIT error when installing gammu in Mac OS X using GCC 4
I'm trying to install Python-Gammu on a mac running Snow Leopard. I successfully configured gammu with cmake and GCC 4, but am getting this error on install. It seems to indicate an improperly configured gcc, but i'm not sure what can be done about this. Has anyone else run into similar problems with GCC on the mac? ...
[ "It looks like Python is somehow miscompiled (or misconfigured).\nYou can always try building Gammu without Python support to workaround this if you don't need it.\n" ]
[ 0 ]
[]
[]
[ "gammu", "gcc", "macos", "python" ]
stackoverflow_0003112211_gammu_gcc_macos_python.txt
Q: How can I impose these constraints on my model using django? This is my model: class MyModel(models.Model): s1 = models.CharField(max_length=255) s2 = models.CharField(max_length=255) I was expecting django not to allow me to have empty strings considered as valid, as I read in the documentation that both bla...
How can I impose these constraints on my model using django?
This is my model: class MyModel(models.Model): s1 = models.CharField(max_length=255) s2 = models.CharField(max_length=255) I was expecting django not to allow me to have empty strings considered as valid, as I read in the documentation that both blank and null are by default false. Example: python manage.py shell ...
[ "blank is a validation-related attribute, which means it will only apply when data is entered via the django-admin site or a form derived from the model using ModelForm.\nExample:\nclass MyForm(forms.ModelForm):\n class Meta:\n model = MyModel\n\n>>> f = MyForm({\"s1\":\"\"})\n>>> f.is_valid()\nFalse\n>>>...
[ 2 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0006251713_django_models_python.txt
Q: python & suds "ImportError: cannot import name getLogger" I'm using Ubuntu 11.04 (natty). I have been using Suds to consume a SOAP web service. Everything was working fine... until it wasn't. I can no longer import Suds. I've uninstalled and re-installed Suds from the Ubuntu repositories but still get the same im...
python & suds "ImportError: cannot import name getLogger"
I'm using Ubuntu 11.04 (natty). I have been using Suds to consume a SOAP web service. Everything was working fine... until it wasn't. I can no longer import Suds. I've uninstalled and re-installed Suds from the Ubuntu repositories but still get the same import error (see IDLE traceback below). I'm using Python 2.7.1 a...
[ "logging is a standard module of Python. There are several possible reasons why Python can't find it anymore:\n\nThe is another logging module in the path (print sys.path to get a list of paths Python will search)\nSomeone changed PYTHONPATH (the default Python search path)\nSomeone messed with the Python installat...
[ 9 ]
[]
[]
[ "importerror", "python", "suds" ]
stackoverflow_0006252660_importerror_python_suds.txt
Q: Python: default comparison In Python 2.7, I define an empty new-style class: In [43]: class C(object): pass ....: then create a list of instances of the new class: In [44]: c = [C() for i in xrange(10)] then attempt to sort the list: In [45]: sorted(c) Out[45]: [<__main__.C object at 0x1950a490>, <__main__.C...
Python: default comparison
In Python 2.7, I define an empty new-style class: In [43]: class C(object): pass ....: then create a list of instances of the new class: In [44]: c = [C() for i in xrange(10)] then attempt to sort the list: In [45]: sorted(c) Out[45]: [<__main__.C object at 0x1950a490>, <__main__.C object at 0x1950a4d0>, ... <_...
[ "I think the only rationale is that it is convenient that objects can be sorted and e.g. used as dictionary keys with some default behavior. The relevant chapter in the language definition is here: https://docs.python.org/2/reference/expressions.html#not-in\n\"The choice whether one object is considered smaller or ...
[ 15, 1, 0 ]
[]
[]
[ "comparison", "object", "python" ]
stackoverflow_0006252758_comparison_object_python.txt
Q: How to implement image upload while creating a user directory if he doesn't have one in django? I have two model in my profile that request image upload. One is just a market place where all the images can be together, i don't care, but the other is a photo gallery. I ready many ways to upload images (most are ver...
How to implement image upload while creating a user directory if he doesn't have one in django?
I have two model in my profile that request image upload. One is just a market place where all the images can be together, i don't care, but the other is a photo gallery. I ready many ways to upload images (most are very old - 2007/2008). and didn't really find the right way yet. So,Here i am, hoping that i will get my...
[ "Maybe you can write your own Storage class which takes into account the current user to determine the directory to store the file? \nMaybe it is even possible to abuse the existing system and change the FileField.storage in for example the constructor. I am not sure if this is easily possible, and it will probably...
[ 3, 1, 0 ]
[]
[]
[ "django", "django_models", "python", "python_imaging_library" ]
stackoverflow_0006251645_django_django_models_python_python_imaging_library.txt
Q: Error on simple MySQL query using Python, but works in MySQL console? I'm trying to run a simple insert query to a database. I have it configured correctly, and it should work, but it doesn't. For some reason I get the following error on this query: Query: INSERT INTO searches (query) VALUES ('test') Error: (1062...
Error on simple MySQL query using Python, but works in MySQL console?
I'm trying to run a simple insert query to a database. I have it configured correctly, and it should work, but it doesn't. For some reason I get the following error on this query: Query: INSERT INTO searches (query) VALUES ('test') Error: (1062, "Duplicate entry 'test' for key 'query'") The query runs without problem...
[ "The way that query is constructed means you will always be inserting 'test' into the database, and seeing the query is likely the primary key in your table, it will be creating duplicate rows.\nThe query should be something like \"INSERT INTO searches (query) VALUES ('\" variable \"')\" so you don't insert the sam...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006252984_mysql_python.txt
Q: Mapping basic typedef aliases with ctypes? I understand how to define structs in Python with ctypes, but I can't seem to find any documentation on how to handle basic aliases. For example 64-bit integers in SQLite: #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_T...
Mapping basic typedef aliases with ctypes?
I understand how to define structs in Python with ctypes, but I can't seem to find any documentation on how to handle basic aliases. For example 64-bit integers in SQLite: #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || de...
[ "While this certainly isn't the 'correct' way to handle this, short of using the C API instead of ctypes, this is the only solution. By the time ctypes runs, the typedef information has been removed - it doesn't appear as symbols in the compiled library.\n" ]
[ 3 ]
[]
[]
[ "c", "ctypes", "python", "typedef" ]
stackoverflow_0006252833_c_ctypes_python_typedef.txt