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: Undefinded Syntax Error? Very new to this, but so far have had a little help in making this. It keeps giving syntax error on line 131.. and many other errors too. Im not really sure on what it is and the person who helped me create this is gone leaving me by my noob self to try and fix this.There is more to the sc...
Undefinded Syntax Error?
Very new to this, but so far have had a little help in making this. It keeps giving syntax error on line 131.. and many other errors too. Im not really sure on what it is and the person who helped me create this is gone leaving me by my noob self to try and fix this.There is more to the script in the middle after -----...
[ "It doesn't look like the you have the proper indention. Remember, in Python, whitespace is very very important. \nThe problem section of code should probably start looking something like:\n elif (struct_item['v'] == -1):\n if type(struct_item['t']) == tuple:\n struct_item['s'] = len(s...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x", "syntax" ]
stackoverflow_0007924244_python_python_3.x_syntax.txt
Q: Determining when a ThreadPool has finished processing a queue I am trying to implement a thread pool that processes a task queue using ThreadPool and Queue. It begins with an initial queue of tasks, and then each of the tasks may also push additional tasks onto the task queue. The problem is I don't know how to bl...
Determining when a ThreadPool has finished processing a queue
I am trying to implement a thread pool that processes a task queue using ThreadPool and Queue. It begins with an initial queue of tasks, and then each of the tasks may also push additional tasks onto the task queue. The problem is I don't know how to block until the queue is empty and the thread pool has finished proce...
[ "\nCall queue.task_done after each task is processed.\nThen you can call queue.join() to block the main thread until all\ntasks have been completed.\nTo terminate the worker threads, put a sentinel (e.g. None) in the queue,\nand have foobar_task break out of the while-loop when it receives the sentinel.\nI think th...
[ 2 ]
[]
[]
[ "multiprocessing", "python", "queue", "threadpool" ]
stackoverflow_0007924179_multiprocessing_python_queue_threadpool.txt
Q: Read integers from file using struct.unpack in Python Suppose I have a file name num.txt as below: 1 2 3 4 5 6 7 8 9 0 I want to read 3 integers from this file, that is 1 2 3. I know that struct.unpack might do the trick, but I just cannot get it right. Here is how I did it: fp = open('num.txt', 'rb') print struc...
Read integers from file using struct.unpack in Python
Suppose I have a file name num.txt as below: 1 2 3 4 5 6 7 8 9 0 I want to read 3 integers from this file, that is 1 2 3. I know that struct.unpack might do the trick, but I just cannot get it right. Here is how I did it: fp = open('num.txt', 'rb') print struct.unpack('iii', fp.read(12)) #right? Anyone can help me w...
[ "You don't use struct to read numbers from a text file. It is for reading data from a binary file -- where the first byte is actually 0x01 rather than a byte order mark or the encoded value of the character '1'.\nYou just want \nthree_ints = [int(x) for x in numfile.readline().strip().split(' ')[:3]]\n\nIf you're o...
[ 5, 4 ]
[]
[]
[ "file_io", "python", "struct" ]
stackoverflow_0007924311_file_io_python_struct.txt
Q: Interface-Based Programming in Python? In superclass in Python, how can I call the function that's overridden in its subclass? class A: @staticmethod def interfaceBasedMethod(): print "Want to delegate to overriding method in subclass" @staticmethod def a(): interfaceBasedMethod() ...
Interface-Based Programming in Python?
In superclass in Python, how can I call the function that's overridden in its subclass? class A: @staticmethod def interfaceBasedMethod(): print "Want to delegate to overriding method in subclass" @staticmethod def a(): interfaceBasedMethod() # <-- I know this causes error. But here ...
[ "Putting aside questions of style, use classmethod not staticmethod. It passes in the class which is being used.\nclass A:\n @classmethod\n def interfaceBasedMethod(cls):\n print \"Want to delegate to overriding method in subclass\"\n\n @classmethod\n def a(cls):\n cls.interfaceBasedMethod...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007924387_python.txt
Q: Python: Read huge number of lines from stdin I'm trying to read a huge amount of lines from standard input with python. more hugefile.txt | python readstdin.py The problem is that the program freezes as soon as i've read just a single line. print sys.stdin.read(8) exit(1) This prints the first 8 bytes but then i...
Python: Read huge number of lines from stdin
I'm trying to read a huge amount of lines from standard input with python. more hugefile.txt | python readstdin.py The problem is that the program freezes as soon as i've read just a single line. print sys.stdin.read(8) exit(1) This prints the first 8 bytes but then i expect it to terminate but it never does. I think...
[ "This should work efficiently in a modern Python:\nimport sys\n\nfor line in sys.stdin:\n # do something...\n print line,\n\nYou can then run the script like this:\npython readstdin.py < hugefile.txt\n\n", "Back in the day, you had to use xreadlines to get efficient huge line-at-a-time IO -- and the docs no...
[ 11, 2 ]
[]
[]
[ "python", "readline", "stdin" ]
stackoverflow_0007923748_python_readline_stdin.txt
Q: How to upload files to MediaWiki using Python? I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: "Unrecognized value for parameter 'action': upload" Here's what I did (site url and password changed): Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29...
How to upload files to MediaWiki using Python?
I'm trying to upload an image (just a random picture for now) to my MediaWiki site, but I keep getting this error: "Unrecognized value for parameter 'action': upload" Here's what I did (site url and password changed): Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Typ...
[ "You need at least MediaWiki 1.16 (which is currently in begta) to be able to upload files via the API. Or you can try mwclient, which automatically falls back to uploading via Special:Upload if an older version of MediaWiki is used (with reduced functionality, such as no error handling etc.)\n", "I got so frustr...
[ 3, 1, 0, 0 ]
[]
[]
[ "file_upload", "mediawiki", "python" ]
stackoverflow_0003182009_file_upload_mediawiki_python.txt
Q: MediaWiki 1.16.4: Script to upload multiple image files I am using MediaWiki 1.16.4 and currently have to migrate from a help site using HTML to a new help site with mediawiki. One problem I bump into is to upload a mass amount of images onto mediawiki without using the web interface (since that would take forever...
MediaWiki 1.16.4: Script to upload multiple image files
I am using MediaWiki 1.16.4 and currently have to migrate from a help site using HTML to a new help site with mediawiki. One problem I bump into is to upload a mass amount of images onto mediawiki without using the web interface (since that would take forever and a half). I am currently trying to use pywikipedia (which...
[ "See the section \"Blatant hack\" here: http://meta.wikimedia.org/wiki/MediaWiki_Bulk_Page_Creator for a PHP script that does just that.\nAs with many of those bot scripts, you'll need the PHP Snoopy library available. This script is pretty old and doesn't use the API, so I'm not sure if it will work with the new C...
[ 1, 1, 0, -1 ]
[]
[]
[ "mediawiki", "php", "python" ]
stackoverflow_0007096466_mediawiki_php_python.txt
Q: Different fields for add and edit Is there a way of doing this? Something like: if not obj: fields = ( field1, ) else: fields = ( field1, field2 ) Thanks in advance. A: The simplest and clearest may be a conditional expression: fields = (field1,field2) if obj else (field1,)
Different fields for add and edit
Is there a way of doing this? Something like: if not obj: fields = ( field1, ) else: fields = ( field1, field2 ) Thanks in advance.
[ "The simplest and clearest may be a conditional expression:\n fields = (field1,field2) if obj else (field1,)\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007924929_django_python.txt
Q: Ruby Packaging Ecosystem As Python Terminolgies I have some experience with Ruby, but it’s less than my Python experience. I've packaged and published several Python packages, but there’s only one Ruby package I've published. I want to learn rapidly about Ruby packaging ecosystem by comparing to Python. I believe...
Ruby Packaging Ecosystem As Python Terminolgies
I have some experience with Ruby, but it’s less than my Python experience. I've packaged and published several Python packages, but there’s only one Ruby package I've published. I want to learn rapidly about Ruby packaging ecosystem by comparing to Python. I believe that there’s the tool equivalent to virtualenv in Ru...
[ "RVM is similar to virtualenv also checkout rbenv (perhaps more like virtualenv)\nBundler is for packaging dependencies for development and deployment, it works like setup.py and pip (I haven't used pip, it seems to have some features of rubygems and Bundler)\nBundler's Gemfile is similar to pip's requirement file\...
[ 11 ]
[]
[]
[ "comparison", "packaging", "python", "ruby", "rubygems" ]
stackoverflow_0007925028_comparison_packaging_python_ruby_rubygems.txt
Q: Python: list of distinct, empty sets I am a python newbie and am attempting to write code for sieve of Eratosthenes. For this I have to initialize a list of empty sets. I tried doing this factors=[set()]*1001, but this produces a shallow copy. I want a deep copy, so that factors[i] and factors[j] point to differen...
Python: list of distinct, empty sets
I am a python newbie and am attempting to write code for sieve of Eratosthenes. For this I have to initialize a list of empty sets. I tried doing this factors=[set()]*1001, but this produces a shallow copy. I want a deep copy, so that factors[i] and factors[j] point to different sets. Is there a simple syntax for doing...
[ "factors = [set() for index in xrange(1001)]\n\n", "Same as always.\nfactors = [set() for x in range(1001)]\n\n", "This is pretty much the standard way of doing it.\nfactors = [set() for x in xrange(1001)]\n\nIt's better to use xrange() instead of range() because xrange() is a generator.\n" ]
[ 14, 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007924709_python.txt
Q: Python Newbie: How to create a progressbar with topwindow module that can show the diffrence between two times(minutes)? Ive just started learning programming in python esp. Pys60, I was wondering if it was possible in pys60, (I hope people still remember pys60). It would help me a lot to create my app. Please kee...
Python Newbie: How to create a progressbar with topwindow module that can show the diffrence between two times(minutes)?
Ive just started learning programming in python esp. Pys60, I was wondering if it was possible in pys60, (I hope people still remember pys60). It would help me a lot to create my app. Please keep the code simple, i may not understand it clearly - cheers:)
[ "The native GUI on symbian 60 has no progress bar so you have to build it yourself using a drawing canvas. Here is a website with an example and python s60 source code:\nhttp://croozeus.com/blogs/?p=1103\n" ]
[ 0 ]
[]
[]
[ "pys60", "python" ]
stackoverflow_0007925292_pys60_python.txt
Q: Deciding to WSGI or Django for new web app I'm in the process of setting up a new web app and deciding whether to just do it with WSGI or go the full framework route with Django. The app's foremost requirements: 1) The app has no UI what so ever and all of the data is exposed to clients via a REST api with JSON. ...
Deciding to WSGI or Django for new web app
I'm in the process of setting up a new web app and deciding whether to just do it with WSGI or go the full framework route with Django. The app's foremost requirements: 1) The app has no UI what so ever and all of the data is exposed to clients via a REST api with JSON. 2) It will have data to persist so MongoDB & pr...
[ "I suggest you consider something between those two extremes. Flask is lightweight, very easy to use, and connects to your web server via wsgi. You can use regular python database connectors with it, and a few databases even have Flask-specific extension modules.\n", "I have worked with Django for a couple of p...
[ 7, 0, 0 ]
[]
[]
[ "django", "django_wsgi", "python", "wsgi" ]
stackoverflow_0007919968_django_django_wsgi_python_wsgi.txt
Q: Store and Retrieve Objects from Python Lists I am new to python and have a difficulty getting an object to be stored and access in an array or a list in Python. I've tried doing something like this: class NodeInfo: def __init__(self, left, value, right): self.l = left self.r = right sel...
Store and Retrieve Objects from Python Lists
I am new to python and have a difficulty getting an object to be stored and access in an array or a list in Python. I've tried doing something like this: class NodeInfo: def __init__(self, left, value, right): self.l = left self.r = right self.v = value tree[0] = NodeInfo(0,1,2) tree[0].l ...
[ "You need to create list first and use append method to add an element to the end of it.\ntree = []\ntree.append(NodeInfo(0,1,2))\n\n# or\ntree = [NodeInfo(0,1,2)]\n\n" ]
[ 8 ]
[]
[]
[ "arrays", "list", "object", "python", "store" ]
stackoverflow_0007925539_arrays_list_object_python_store.txt
Q: Aptana will not let me Run my python modules. Why? Why is the Python Run option not available? I'm running Aptana 3 on Mac OS X 10.6 A: Python run should be available if you have a python file opened in the builtin python editor of Aptana.
Aptana will not let me Run my python modules. Why?
Why is the Python Run option not available? I'm running Aptana 3 on Mac OS X 10.6
[ "Python run should be available if you have a python file opened in the builtin python editor of Aptana.\n" ]
[ 0 ]
[]
[]
[ "aptana", "eclipse", "macos", "pydev", "python" ]
stackoverflow_0007925672_aptana_eclipse_macos_pydev_python.txt
Q: Load/reload a portion of code in Python without restarting main script Intro I've been tinkering with Twisted for the past few days, having picked up python less than a month ago. My first inclination was to play with something I know and use every day, IRC. I've gotten a basic IRC connection up and running thanks...
Load/reload a portion of code in Python without restarting main script
Intro I've been tinkering with Twisted for the past few days, having picked up python less than a month ago. My first inclination was to play with something I know and use every day, IRC. I've gotten a basic IRC connection up and running thanks to the ircLogBot.py example. Question I want to have some arbitrary code th...
[ "Twisted has some built-in functionality in twisted.python.rebuild which provides a more comprehensive implementation of Python's built-in reload function. There are still some limitations, but its chief difference from Python's built-in reload is that it will find old instances of objects and replace their classe...
[ 9, 3, 2, 0 ]
[]
[]
[ "irc", "python", "twisted" ]
stackoverflow_0007912250_irc_python_twisted.txt
Q: Python built-in range function and variable values I'm writing a script where I extract command line arguments using getopt, qualify the values offered, then use those values as limits on a loop. Code fragment is below: try: start_pod, end_pod, topo_value = map(int, args) except ValueError, error_msg: if ...
Python built-in range function and variable values
I'm writing a script where I extract command line arguments using getopt, qualify the values offered, then use those values as limits on a loop. Code fragment is below: try: start_pod, end_pod, topo_value = map(int, args) except ValueError, error_msg: if 'invalid' in str(error_msg): err_funct('Non-inte...
[ "Your call of the script is incorrect:\n>>> range(1,1)\n[]\n\n(start_pod and end_pod will both be 1).\nThe range(i,j) functions returns the following list [i, i + 1, .., j - 1]. Or, differently put, the end point is always removed.\nTry changing the for pod in range... line in:\nfor pod in range(start_pod, end_pod ...
[ 2, 1 ]
[]
[]
[ "loops", "python", "range" ]
stackoverflow_0007926502_loops_python_range.txt
Q: Install error (--site-dirs) python 2.6 and setuptools i can't install setuptools on my nas. i have this error : LeGrappin> python2.6 setup.py build running build running build_py LeGrappin> python2.6 setup.py install running install error: /opt/local/lib/python2.5/site-packages (in --site-dirs) is not on sys.path ...
Install error (--site-dirs) python 2.6 and setuptools
i can't install setuptools on my nas. i have this error : LeGrappin> python2.6 setup.py build running build running build_py LeGrappin> python2.6 setup.py install running install error: /opt/local/lib/python2.5/site-packages (in --site-dirs) is not on sys.path LeGrappin> Any idea ?
[ "It's warning you that the place it is getting installed to will not be a place where python loads modules from.\nTo check which directories are, simply start python, then run\nimport sys; print sys.path\n\nThat should give you all directories that do work. You may have to override the installation prefix as an ar...
[ 0 ]
[]
[]
[ "installation", "linux", "python", "setuptools" ]
stackoverflow_0007923311_installation_linux_python_setuptools.txt
Q: Taking Symbol as input from script [sympy] 1.I'd like to define a function in a module that is interactive and can also take symbolic variables. Let's say the function is (source: texify.com) . Then I want it to work like >>> function() number: 3 6 >>> function() number: x 2*x >>> function() number: a 2*a The re...
Taking Symbol as input from script [sympy]
1.I'd like to define a function in a module that is interactive and can also take symbolic variables. Let's say the function is (source: texify.com) . Then I want it to work like >>> function() number: 3 6 >>> function() number: x 2*x >>> function() number: a 2*a The reason I want to prompt user input is that I'm thi...
[ "When you import it in a module, twice() runs in the module's global namespace and does not have access to the interactive session's global variables, such as x. That's the whole point of modules, after all.\nThis is typically rectified by passing variables to functions rather than having them operate on global var...
[ 2, 1 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0007925154_python_sympy.txt
Q: jython killing parent process that spawns subprocess breaks subprocess stdout to file? Let me start with what I'm really trying to do. We want a platform independent startup script for invoking a JVM with some system properties and a dynamically generated classpath. We picked Jython in particular because we only n...
jython killing parent process that spawns subprocess breaks subprocess stdout to file?
Let me start with what I'm really trying to do. We want a platform independent startup script for invoking a JVM with some system properties and a dynamically generated classpath. We picked Jython in particular because we only need to depend on the standalone jython.jar in our startup script. We decided we could write ...
[ "\nWe want a platform independent startup script for invoking a JVM with some system properties and a dynamically generated classpath.\n\nYou could use a platform independent script to generate a platform specific startup script either at installation time or before each invocation. In the latter case, additionally...
[ 1 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0007922338_jython_python.txt
Q: QNetworkAccessManager: Posting files via HTTP I just need to use QNetworkAccessManager to upload multiple files on an apache server with PHP. I'm asking here because I'm new to Python ad QT (PySide) and I would like to know if someone have a tutorial or example of code (in python) demonstrating this. Note: If thi...
QNetworkAccessManager: Posting files via HTTP
I just need to use QNetworkAccessManager to upload multiple files on an apache server with PHP. I'm asking here because I'm new to Python ad QT (PySide) and I would like to know if someone have a tutorial or example of code (in python) demonstrating this. Note: If this kind of content is not available I will try to do...
[ "Don't know if it's the best way but it's working fine.\n class Upload():\n def __init__(self):\n self.url = QUrl(\"http://www.website.com/up.php\")\n self.manager = QtNetwork.QNetworkAccessManager()\n\n def sendRequest(self, replayfile):\n self.request = QtNetw...
[ 3 ]
[]
[]
[ "pyside", "python", "qt" ]
stackoverflow_0007922015_pyside_python_qt.txt
Q: How to construct endpoints with t.c.telnet My goal is to create telnet clients as endpoints per the TCP4ClientEndpoint implementation. Here's what Im doing: class TelnetClient( TelnetProtocol ): ... factory = Factory() factory.protocol = TelnetClient point = TCP4ClientEndpoint( reactor, x.x.x.x, 23 ) defer = ...
How to construct endpoints with t.c.telnet
My goal is to create telnet clients as endpoints per the TCP4ClientEndpoint implementation. Here's what Im doing: class TelnetClient( TelnetProtocol ): ... factory = Factory() factory.protocol = TelnetClient point = TCP4ClientEndpoint( reactor, x.x.x.x, 23 ) defer = point.connect( factory ) defer.addCallback( tod...
[ "You're correct thatconnectTCP and endpoint.connect are functionally the same (for the most part).\nAssuming that TelnetProtocol is twisted.conch.telnet.TelnetProtocol, the problem here is that TelnetProtocol is not really supposed to connect directly to a TCP transport, it's supposed to connect to a twisted.conch....
[ 1 ]
[]
[]
[ "python", "telnet", "twisted" ]
stackoverflow_0007926110_python_telnet_twisted.txt
Q: Sending mail with SSL with Python 2.3 I'm working with Python 2.3 and I need to send e-mails with SSL. According to the docs, SMTP_SSL was added in Python 2.6. Is there a way to use SSL also in Python 2.3 (maybe with a third-party module)? A: Maybe you can just use starttls() just like: smtp = smtplib.SMTP(mailh...
Sending mail with SSL with Python 2.3
I'm working with Python 2.3 and I need to send e-mails with SSL. According to the docs, SMTP_SSL was added in Python 2.6. Is there a way to use SSL also in Python 2.3 (maybe with a third-party module)?
[ "Maybe you can just use starttls()\njust like:\nsmtp = smtplib.SMTP(mailhost)\nsmtp.starttls()\n\nIn SMTP_SSL doc you can find:\n\nSMTP_SSL should be used for situations where SSL is required from the\n beginning of the connection and using starttls() is not appropriate.\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_2.3", "smtplib", "ssl" ]
stackoverflow_0007926565_python_python_2.3_smtplib_ssl.txt
Q: Portable way to load the C standard library in Python ctypes Is there a portable way to load the C standard library (libc.so, libc.dylib) in Python ctypes? Should I just use if/elif statements about the result of platform.system() function? A: The ctypes library doesn't offer anything of that nature so an if sta...
Portable way to load the C standard library in Python ctypes
Is there a portable way to load the C standard library (libc.so, libc.dylib) in Python ctypes? Should I just use if/elif statements about the result of platform.system() function?
[ "The ctypes library doesn't offer anything of that nature so an if statement is just what you need.\n" ]
[ 1 ]
[]
[]
[ "ctypes", "libc", "python" ]
stackoverflow_0007926617_ctypes_libc_python.txt
Q: How to tell if python's ZipFile.writestr() failed because file is full? Without using zip64 extensions, a Zip file cannot be more than 2GB in size, so trying to write to a file that would put it over that limit won't work. I expected that when such a writing was attempted, it would raise an exception, but I've no...
How to tell if python's ZipFile.writestr() failed because file is full?
Without using zip64 extensions, a Zip file cannot be more than 2GB in size, so trying to write to a file that would put it over that limit won't work. I expected that when such a writing was attempted, it would raise an exception, but I've not been able to cause one to be raised. (The documentation is silent on the m...
[ "import os\n\nsize = os.path.getsize(\"file\") #Get the size of the file.\nsize = size/1073741824 #Converting bytes to GB.\n\nif size < 2: # < is probably safer than <=\n #do the zipping\nelse:\n print \"The file is too large!\"\n\nThis isn't ideal, of course, but it might serve as a temporary solutio...
[ 0, 0 ]
[]
[]
[ "exception", "python", "zip" ]
stackoverflow_0007921210_exception_python_zip.txt
Q: How to pass extra_context to auth_views.password_change in URL handler I have a URL handler for changing passwords, such as this: url(r'^password/change/$', auth_views.password_change, {'template_name' : 'account/password/password_change_...
How to pass extra_context to auth_views.password_change in URL handler
I have a URL handler for changing passwords, such as this: url(r'^password/change/$', auth_views.password_change, {'template_name' : 'account/password/password_change_form.html'}, name='auth_password_change'), All i...
[ "Normally you do that in the urlconf - but you can't pass request.user in extra_context, because the urls.py has no access to the request.\nBut password_change, like all built-in views, uses RequestContext to render the template - which means that there is a user object there automatically (passed in by django.cont...
[ 2 ]
[]
[]
[ "django", "django_registration", "python" ]
stackoverflow_0007927671_django_django_registration_python.txt
Q: Python: variable scope and encapsulation of a list I have a class Map (simplified): from Enums import * import Globals import Tile class Map: tiles = [] #the actual map, it's a 2D list of Tile objects for x in range(Globals.mapWidth): for y in range(Globals.mapHeight): self.tiles[x][y...
Python: variable scope and encapsulation of a list
I have a class Map (simplified): from Enums import * import Globals import Tile class Map: tiles = [] #the actual map, it's a 2D list of Tile objects for x in range(Globals.mapWidth): for y in range(Globals.mapHeight): self.tiles[x][y].addItem(Items.Foliage) And a class Tile: class Tile: ...
[ "Your items is a class attribute, which is why it appears to be shared between all the instances.\nclass Tile:\n def __init__(self, type):\n self.items = []\n self.type = type\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007927885_python.txt
Q: Python Manipulating String I have a "raw" variable that store: *rawVariable =* "Hello" "World" "String 1" "String 2" "String 3" "Sting 4" "Hello" "World" "String 5" "String 6" "String 7" "String 8" "Hello" "World" "String 9" "String 10" "String 11" "String 12" Is it possible that I store the word...
Python Manipulating String
I have a "raw" variable that store: *rawVariable =* "Hello" "World" "String 1" "String 2" "String 3" "Sting 4" "Hello" "World" "String 5" "String 6" "String 7" "String 8" "Hello" "World" "String 9" "String 10" "String 11" "String 12" Is it possible that I store the word in a array with front and back ...
[ "I'm not 100% sure if I understand your question, but I'm guessing the following code might help you:\nimport re\n\ndef splitRawString(s):\n return map(lambda x: re.sub('^\"?([^\"]*)\"?$', r'\\1', x),\n re.split('\"\\s*\"', s))\n\na='\"Hello\" \"World\" \"String 1\" \"String 2\" \"String 3\" \"Sting 4\" \...
[ 1, 1 ]
[]
[]
[ "delimiter", "python", "string" ]
stackoverflow_0007927525_delimiter_python_string.txt
Q: How to close a file in python without assigning a variable How do I close a file in python after opening it this way: line = open("file.txt", "r").readlines()[7] A: Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garb...
How to close a file in python without assigning a variable
How do I close a file in python after opening it this way: line = open("file.txt", "r").readlines()[7]
[ "Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection\nwith open(\"file.txt\", \"r\") as f:\n line = f.readlines()[7]\n\n", "There are several ways, e.g you could just use f = open(...) and del f.\nIf...
[ 4, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007927904_file_io_python.txt
Q: SIGNAL emit works only in one function, but not in others? I have a somewhat strange problem. I'm coding a multithreaded app and am using SIGNALS to communicate the QThread's data to the GUI class data. Without further ado, here is a simplified code. class GUI(uiMainWindow.MainWindow): def __init__(self, paren...
SIGNAL emit works only in one function, but not in others?
I have a somewhat strange problem. I'm coding a multithreaded app and am using SIGNALS to communicate the QThread's data to the GUI class data. Without further ado, here is a simplified code. class GUI(uiMainWindow.MainWindow): def __init__(self, parent=None): super etc self.thread = Thread() ...
[ "I was right in my post. The difference between Thread() and Thread(create=False) was crucial. I had to define a new method (one was self.thread = Thread() and the other self.diff_thread = Thread(create=False)) and connect to different slots to make it work.\n" ]
[ 1 ]
[]
[]
[ "pyqt", "python", "qt", "signals_slots" ]
stackoverflow_0007913843_pyqt_python_qt_signals_slots.txt
Q: Python Sorting Data for loop and if statement data = ['cat', 'dog', 'None', 'Turtle', 'None'] new_data = [] for item in data: if item == 'None': new_data.append(data.index(item)) print new_data >> [2,2] How do I go about getting to this store new data as [2,4]? This is what I want. Thank you! A: Us...
Python Sorting Data for loop and if statement
data = ['cat', 'dog', 'None', 'Turtle', 'None'] new_data = [] for item in data: if item == 'None': new_data.append(data.index(item)) print new_data >> [2,2] How do I go about getting to this store new data as [2,4]? This is what I want. Thank you!
[ "Use enumerate() while looping. This will track both, the current item and its index:\n[index for index, x in enumerate(data) if x == \"None\"]\n\n", "for idx, item in enumerate(data):\n if item == 'None':\n new_data.append(idx)\n\nbetter yet, just use a list comprehension as in Sven's answer\n", "Tr...
[ 6, 2, 1, 1 ]
[]
[]
[ "for_loop", "if_statement", "python" ]
stackoverflow_0007927964_for_loop_if_statement_python.txt
Q: Testing posting to forms in FunkLoad I am trying to test functionality of a web-application using FunkLoad. The page under testing is just a login form - give email and pwd and if successful it redirects to a index page; if not successful it throws an error. I have the below code: self.get(server_url + "/login", d...
Testing posting to forms in FunkLoad
I am trying to test functionality of a web-application using FunkLoad. The page under testing is just a login form - give email and pwd and if successful it redirects to a index page; if not successful it throws an error. I have the below code: self.get(server_url + "/login", description="Get /init/default/login") para...
[ "Setup the funkload proxy recorder and login into your site using your browser as described in the funkload docs: http://funkload.nuxeo.org/recorder.html\nThen you easily check exactly what you are sending via POST. You might be sending other params as you think. In the following example, I am testing a django logi...
[ 2 ]
[]
[]
[ "functional_testing", "funkload", "python", "testing" ]
stackoverflow_0007865977_functional_testing_funkload_python_testing.txt
Q: Generating points not within the range of each other? I am trying to generate a set of points that do not fall within the range of each other in a fixed area. My approach is given below: import collections from random import uniform X = 100.0 Y = 100.0 points = 10 radius = 10 def in_circle(c_x, c_y, radius, x, y...
Generating points not within the range of each other?
I am trying to generate a set of points that do not fall within the range of each other in a fixed area. My approach is given below: import collections from random import uniform X = 100.0 Y = 100.0 points = 10 radius = 10 def in_circle(c_x, c_y, radius, x, y): dist_squared = (c_x - x)**2 + (c_y - y)**2 retur...
[ "This article about poisson disk sampling may be interesting to you. The author explains a strategy for selecting points that aren't too close to each other, and even provides sample code in a few languages, including Python.\nThe problem with the strategy you outlined is, as you noted, that if you want to select ...
[ 3, 2, 2 ]
[]
[]
[ "graphics", "math", "python" ]
stackoverflow_0007928204_graphics_math_python.txt
Q: How to define a chi2 value function for arbitrary function? I am doing some data fitting using the pyminuit Python bindings for the minuit minimisation code (http://code.google.com/p/pyminuit/). The minimiser accepts a function and uses introspection to extract the parameters to be minimised. In general, I want to...
How to define a chi2 value function for arbitrary function?
I am doing some data fitting using the pyminuit Python bindings for the minuit minimisation code (http://code.google.com/p/pyminuit/). The minimiser accepts a function and uses introspection to extract the parameters to be minimised. In general, I want to minimise the chi squared value for a dataset given a particular ...
[ "Since PyMinuit uses introspection, you have to use introspection, too. make_chi_squared() could be implemented like this:\nimport inspect\n\nchi_squared_template = \"\"\"\ndef chi_squared(%(params)s):\n return (((f(data_x, %(params)s) - data_y) / errors) ** 2).sum()\n\"\"\"\n\ndef make_chi_squared(f, data_x, d...
[ 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0007927670_python_scipy.txt
Q: Python pycurl with Twitter Streaming API I'm using pycurl to crawl data from the Twitter Streaming API. However, after several hours, the connection just hangs there. Is there anyway to detect this and exit the program? I know pycurl has TIMEOUT and CONNECTTIMEOUT, but these two params do not apply. A: Do you ge...
Python pycurl with Twitter Streaming API
I'm using pycurl to crawl data from the Twitter Streaming API. However, after several hours, the connection just hangs there. Is there anyway to detect this and exit the program? I know pycurl has TIMEOUT and CONNECTTIMEOUT, but these two params do not apply.
[ "Do you get an exception or something and could you please add some code? :)\nMaybe you should think about using another module like httplib (if you want to\nuse SSL/TLS you could create a new socket and overwrite the connect function of httplib with\nyour secure wrapped socket :) )\n" ]
[ 0 ]
[]
[]
[ "api", "pycurl", "python", "streaming", "twitter" ]
stackoverflow_0007924499_api_pycurl_python_streaming_twitter.txt
Q: Python encryption with only standard libs Possible Duplicate: Can I encrypt email and decrypt it back using python default library set? I need Python to encrypt some data using a pre-set encryption key but I can't find any way to do it without installing new libs (pycrypto etc.). This is for some scripts that wi...
Python encryption with only standard libs
Possible Duplicate: Can I encrypt email and decrypt it back using python default library set? I need Python to encrypt some data using a pre-set encryption key but I can't find any way to do it without installing new libs (pycrypto etc.). This is for some scripts that will be distributed to numerous devices but we c...
[ "Maybe you can fall back to calling the openssl executable on the system itself? This way you could pass the keys as files and data via the stdin/out and not rely on new python modules. You also get all the algorithms from openssl available directly - both symmetric and asymmetric encryption and other nice things.\...
[ 2, 0 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0007927896_encryption_python.txt
Q: Can a django template find out its named url or can a base template know which template is extending it? In my URLConf, I have my URLs neatly named so I can do reverse lookups and keep everything DRY. All my templates extend a universal template named base.html. In base.html, amongst a lot of HTML framework, I dis...
Can a django template find out its named url or can a base template know which template is extending it?
In my URLConf, I have my URLs neatly named so I can do reverse lookups and keep everything DRY. All my templates extend a universal template named base.html. In base.html, amongst a lot of HTML framework, I display a login form. I also have a specific view which uses Django's provided auth_views.login view, which displ...
[ "You could manage this with template inheritance and blocks.\nYour base.html defines a block called login, which surrounds the HTML for the login - and your login.html overrides that block with an empty version:\nbase.html:\n{% block login %}\n ... login form here ...\n{% endblock %}\n\n{% block main %}\n{% endb...
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007928664_django_django_templates_python.txt
Q: python doctest default namespace In the doctests of my module I would like to reference my module with the full namespace, for example: hp.myfunc(1) And I would like to avoid cluttering the doctests by writing: import healpy as hp in each of the doctests. if I run doctest.testmod, I know I can use the globs ...
python doctest default namespace
In the doctests of my module I would like to reference my module with the full namespace, for example: hp.myfunc(1) And I would like to avoid cluttering the doctests by writing: import healpy as hp in each of the doctests. if I run doctest.testmod, I know I can use the globs keyword to provide this, while if I ru...
[ "How are you running the doctests (without nose, that is)? If you are cd'd into the package directory when you attempt to run them, you will run into problems (if you are doing a full import, that is).\nI was able to get a simple doctest (with fully-qualified imports) running with both nosetests and the builtin do...
[ 3, 2 ]
[]
[]
[ "doctest", "nose", "python" ]
stackoverflow_0007682114_doctest_nose_python.txt
Q: How to catch exception in twisted Deferred callback? from twisted.internet import reactor, defer def getDummyData(x): """ This function is a dummy which simulates a delayed result and returns a Deferred which will fire with that result. Don't try too hard to understand this. """ d = de...
How to catch exception in twisted Deferred callback?
from twisted.internet import reactor, defer def getDummyData(x): """ This function is a dummy which simulates a delayed result and returns a Deferred which will fire with that result. Don't try too hard to understand this. """ d = defer.Deferred() # simulate a delayed result by asking t...
[ "It's never called because the code under your comment that says it asks the reactor to stop itself in 4 seconds actually asks the reactor to stop itself in 1 second. The 2-second callLater never gets called, so d is never fired, so nextCall is never called.\nMaybe you should try constructing this example without ...
[ 4 ]
[]
[]
[ "deferred", "python", "twisted" ]
stackoverflow_0007928684_deferred_python_twisted.txt
Q: namespace on python pickle I got an error when I use pickle with unittest. I wrote 3 program files: for a class to be pickled, for a class which use class in #1, unittest for testing class in #2. and the real codes are as follows respectively. #1. ClassToPickle.py import pickle class ClassToPickle(object): ...
namespace on python pickle
I got an error when I use pickle with unittest. I wrote 3 program files: for a class to be pickled, for a class which use class in #1, unittest for testing class in #2. and the real codes are as follows respectively. #1. ClassToPickle.py import pickle class ClassToPickle(object): def __init__(self, x): s...
[ "That because __main__.ClassToPickle != ClassToPickle.ClassToPickle, think of it like this:\nWhen you pickled the class instance of ClassToPickle in the ClassToPickle.py script, the pickle module will pickle all the reference to the class which mean it will pickle the module name where the class was defined, and be...
[ 9 ]
[]
[]
[ "namespaces", "pickle", "python" ]
stackoverflow_0007928450_namespaces_pickle_python.txt
Q: How to parse the output of a Suds Client Request If I print the answer of my request I get the following: (reply){ returnCode = "OK" voucher_code = "123456" voucher_type = "Reloadable" voucher_status = "ok" } How can I parse this? I found an solution with client.last_received() but I don't know if t...
How to parse the output of a Suds Client Request
If I print the answer of my request I get the following: (reply){ returnCode = "OK" voucher_code = "123456" voucher_type = "Reloadable" voucher_status = "ok" } How can I parse this? I found an solution with client.last_received() but I don't know if this will be problematic with many requests at the same...
[ "You don't need to parse anything. Suds already did it. Just access attributes of the object that you've printed.\n" ]
[ 3 ]
[]
[]
[ "python", "suds" ]
stackoverflow_0007927013_python_suds.txt
Q: How to generate a sequence of numbers that can later be used in the command lines in python? what I want to do is to write a script wich get some files as input and then run some command on them! I first want to know how many files dose the user has and then ask for him/her to upload it and later I want to run som...
How to generate a sequence of numbers that can later be used in the command lines in python?
what I want to do is to write a script wich get some files as input and then run some command on them! I first want to know how many files dose the user has and then ask for him/her to upload it and later I want to run some command on it. So I had used this command: for cnt inseq 19 2 31 in a similar situation long tim...
[ "You probably want something like this:\npairs = int(raw_input(\"How many pairs do you have?\"))\nfor pair_n in xrange(1, pairs + 1):\n file1 = raw_input(\"pair%d-a: \" % pair_n)\n file2 = raw_input(\"pair%d-b: \" % pair_n)\n cmd = \"samtools merge pair%d.bam '%s' '%s'\" % (pair_n, file1, file2)\n # os.system(c...
[ 2, 1, 0, 0 ]
[]
[]
[ "numbers", "python", "range" ]
stackoverflow_0007928981_numbers_python_range.txt
Q: Pre-fill a form with attached file taken from some URL in Django I have a form with "subject", "body" and "file" fields on some page on my Django site. If "subject" and/or "body" parameters exist in GET, I pre-fill them in the form from server side. I want to do the same with "file" field - more exactly, I want if...
Pre-fill a form with attached file taken from some URL in Django
I have a form with "subject", "body" and "file" fields on some page on my Django site. If "subject" and/or "body" parameters exist in GET, I pre-fill them in the form from server side. I want to do the same with "file" field - more exactly, I want if there is an "URL" parameter in request.GET, take the file from this U...
[ "You can't pre-fill a file field. But I don't think you need to use one at all, since you're getting the file from a URL, not from the user's local machine. Just use a normal text field for the URL, and get the file server-side (eg using urllib) after the form is submitted.\n", "Most sites that do something like ...
[ 1, 1 ]
[]
[]
[ "django", "javascript", "python" ]
stackoverflow_0007929014_django_javascript_python.txt
Q: How to save the code object in file? How to save the code object (_ _ code _ _) in file? >>> c <code object foo at 0x022E7660, file "<console>", line 1> >>> pickle.dump(c, f) Traceback (most recent call last): File "<console>", line 1, in <module> _pickle.PicklingError: Can't pickle <class 'code'>: attribute lo...
How to save the code object in file?
How to save the code object (_ _ code _ _) in file? >>> c <code object foo at 0x022E7660, file "<console>", line 1> >>> pickle.dump(c, f) Traceback (most recent call last): File "<console>", line 1, in <module> _pickle.PicklingError: Can't pickle <class 'code'>: attribute lookup builtins.code failed >>> f.write(c) T...
[ "Not sure what you are trying to do but you can use the marshal module for this:\n>>> import marshal\n>>> def f():\n... print 'f'\n>>> marshal.dump(f.__code__, open('test.dump'))\n>>> code = marshal.load(open('test.dump'))\n>>> f.__code__ == code\nTrue\n>>> import dis\n>>> dis.dis(code)\n 2 0 LOAD_CON...
[ 10 ]
[ "I googled around and found something which could be useful:\nhttp://python.about.com/od/pythonstandardlibrary/a/pickle_intro.htm\nregards\n" ]
[ -4 ]
[ "python" ]
stackoverflow_0007928419_python.txt
Q: UDP flow control with Python Twisted I have a class that inherits from twisted.internet.protocol.DatagramProtocol class. In my startProtocol() implementation I call startWriting(), so that socket gets notified each time I can write to it without blocking. Two questions: Which method twisted will call once socket ...
UDP flow control with Python Twisted
I have a class that inherits from twisted.internet.protocol.DatagramProtocol class. In my startProtocol() implementation I call startWriting(), so that socket gets notified each time I can write to it without blocking. Two questions: Which method twisted will call once socket will become writable? How should I call st...
[ "Oops. I think I may have answered your question in another thread and lead you to believe that UDP flow control support in Twisted is a little more robust than it actually is. Nevertheless, you can get what you need to do done...\n1. Which method will Twisted call once socket will become writable?\nUnfortunately...
[ 2 ]
[]
[]
[ "flow_control", "python", "twisted", "udp" ]
stackoverflow_0007906615_flow_control_python_twisted_udp.txt
Q: Navigate through lxml categories I have a parse a web and now I want to navigate through the tags, or show a graph. How can I get a graph? Or navigate through the tree. Showing the first step then other,etc. And understant how the tree was built. import urllib from lxml import etree import StringIO resultado=urlli...
Navigate through lxml categories
I have a parse a web and now I want to navigate through the tags, or show a graph. How can I get a graph? Or navigate through the tree. Showing the first step then other,etc. And understant how the tree was built. import urllib from lxml import etree import StringIO resultado=urllib.urlopen('trozo.html') html = resulta...
[ "You achieved the parsing, which you can see if you do the following:\n>>> tree\n<lxml.etree._ElementTree object at 0x0148AF08>\n\nNow you can go through this element using lxml._ElementTree functions, documented here: http://lxml.de/tutorial.html\nHere are some basics, with a simple file I got from my local networ...
[ 3 ]
[]
[]
[ "graph", "lxml", "python" ]
stackoverflow_0007918240_graph_lxml_python.txt
Q: linking to audiolab in python2.6 on osx I've been unable to get scikits.audiolab working on OS X. I've tried easy_install and building from source, but both give me the same error: ----> 1 import scikits.audiolab /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scikits.audiolab-0.11....
linking to audiolab in python2.6 on osx
I've been unable to get scikits.audiolab working on OS X. I've tried easy_install and building from source, but both give me the same error: ----> 1 import scikits.audiolab /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/scikits.audiolab-0.11.0-py2.6-macosx-10.3-fat.egg/scikits/audiolab/...
[ "Audiolab requires libsndfile. I had installed that via MacPorts, but it had built as x86_64 only by default.\nDeleting all installs and reinstalling libsndfile with the +universal flag built it as i386 and x86_64.\nNow I could install audiolab from source and it linked properly. :)\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "scikits", "scipy" ]
stackoverflow_0007919771_macos_python_scikits_scipy.txt
Q: python subprocess deadlock in demonized server I'm trying to set up a remote backup server for dar, along these lines. I'd really like to do all the piping with python if possible, but I've asked a separate question about that. Using netcat in subprocess.Popen(cmd, shell=True), I succeeded in making a differentia...
python subprocess deadlock in demonized server
I'm trying to set up a remote backup server for dar, along these lines. I'd really like to do all the piping with python if possible, but I've asked a separate question about that. Using netcat in subprocess.Popen(cmd, shell=True), I succeeded in making a differential backup, as in the examples on the dar site. The o...
[ "I'd cut my losses and start over. This solution attempt is very complicated and kludgy. There are many ready-made solutions in the area:\n\n10 outstanding Linux backup utilities\n\nFwbackups sounds good if you want to take the easy route, rsync+ssh for the hard core.\n", "\nUse Popen.communicate() instead of P...
[ 1, 1 ]
[]
[]
[ "deadlock", "python", "subprocess" ]
stackoverflow_0007922477_deadlock_python_subprocess.txt
Q: dict.__getitem__ performance with strings I'm using a dict to store cached paths in a filesystem I've implemented. The keys in the dict are all strings. After some profiling I've demonstrated that lookups in the dictionary are a bottleneck. My understanding is that dict is highly optimized. Unfortunately the preci...
dict.__getitem__ performance with strings
I'm using a dict to store cached paths in a filesystem I've implemented. The keys in the dict are all strings. After some profiling I've demonstrated that lookups in the dictionary are a bottleneck. My understanding is that dict is highly optimized. Unfortunately the precision of cProfile does not include the inner wor...
[ "I think, there is a necessity to evaluate the source code to understand what makes the difference. Recently i've tried to port Python2 code to Python3, come up with same poor lookup times, Python2 is ~30% faster than Python3. This is not actual code but a dummy class to figure out where the problem actually is. Sa...
[ 0 ]
[]
[]
[ "dictionary", "python", "python_3.x", "string", "unicode" ]
stackoverflow_0006273191_dictionary_python_python_3.x_string_unicode.txt
Q: Trying to insert variables from two lists into strings - how do I do it? So I have the following code: optionlist = [ '<option value="id=%s+%s">%s - %s</option>' % (x, y, x, y) for x in numlist, y in numlist2 ] What I would like is for the values from x to be inserted in the first %s, val...
Trying to insert variables from two lists into strings - how do I do it?
So I have the following code: optionlist = [ '<option value="id=%s+%s">%s - %s</option>' % (x, y, x, y) for x in numlist, y in numlist2 ] What I would like is for the values from x to be inserted in the first %s, values from y to be inserted in the second %s, the same value from x to be insert...
[ "['<option value=\"id=%s+%s\">%s - %s</option>' % (x, y, x, y) for x, y in zip(numlist, numlist2)]\n\n", "Do you mean like this:\nIn [1]: l1 = [1, 2, 3]\n\nIn [2]: l2 = ['a', 'b', 'c']\n\nIn [3]: ['<option value=\"id={0}+{1}\">{0} - {1}</option>'.format(i, j)\n ...: for i, j in zip(l1, l2)]\nOut[3]: \n['<optio...
[ 2, 1, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0007929469_list_python_string.txt
Q: using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field I am using Ubuntu 9.04 I have installed the following package versions: unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 I have configured /etc/unixodbc.ini like this...
using pyodbc on linux to insert unicode or utf-8 chars in a nvarchar mssql field
I am using Ubuntu 9.04 I have installed the following package versions: unixodbc and unixodbc-dev: 2.2.11-16build3 tdsodbc: 0.82-4 libsybdb5: 0.82-4 freetds-common and freetds-dev: 0.82-4 I have configured /etc/unixodbc.ini like this: [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /us...
[ "I can remember having this kind of stupid problems using odbc drivers, even if that time it was a java+oracle combination.\nThe core thing is that odbc driver apparently encodes the query string when sending it to the DB. Even if the field is Unicode, and if you provide Unicode, in some cases it does not seem to m...
[ 22, 2, 1, 0 ]
[]
[]
[ "pyodbc", "python", "sql_server", "unicode", "utf_8" ]
stackoverflow_0000947077_pyodbc_python_sql_server_unicode_utf_8.txt
Q: Python: Using Tensordot for tensor x matrix multiplication Hi im tying to multiply a tensor with a matrix in the following fashion: dimensions W: a x b x c V: a x c I want Z such that Z[i]=dot(W[i],V[i]) Z is then of dimension a x ( (b x c) . (c x 1)), so (a x b) Ive tried numpy.tensordot to do this but havent be...
Python: Using Tensordot for tensor x matrix multiplication
Hi im tying to multiply a tensor with a matrix in the following fashion: dimensions W: a x b x c V: a x c I want Z such that Z[i]=dot(W[i],V[i]) Z is then of dimension a x ( (b x c) . (c x 1)), so (a x b) Ive tried numpy.tensordot to do this but havent been able to. Can it do what I want? If not how can I do this WITH...
[ "np.einsum(\"abc,ac -> ab\", w, v):\nimport numpy as np\n\ndef z_loop(w,v): # define it to check that `einsum()` gives necessary result\n z = np.empty(w.shape[:-1], dtype=w.dtype)\n for i in range(z.shape[0]):\n z[i,:] = np.dot(w[i,:], v[i,:])\n return z\n\nw = np.random.uniform(size=(3,4,5))\nv = n...
[ 5, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005198005_numpy_python.txt
Q: What does gobject.type_register() do? In PyGTK, what does gobject.type_register() do? The documentation merely says registers the specified Python class as a PyGTK type Well, duh. What does registering a class as a PyGtk type do? A: A PyGTK type can be used as the type of a PyGTK property. To be known to the G...
What does gobject.type_register() do?
In PyGTK, what does gobject.type_register() do? The documentation merely says registers the specified Python class as a PyGTK type Well, duh. What does registering a class as a PyGtk type do?
[ "A PyGTK type can be used as the type of a PyGTK property. To be known to the GObject type system, a type has to be registered. I don't think you actually have to call this function in PyGTK, it is probably done automatically when you call __gobject_init__.\nSometimes the PyGTK docs are too succinct. In that case y...
[ 5 ]
[]
[]
[ "gobject", "gtk", "pygtk", "python" ]
stackoverflow_0007927284_gobject_gtk_pygtk_python.txt
Q: Python SUDS return type other than XML I am working with a somewhat non-standard SOAP webservice. Most of the calls to the webservice return the standard SOAP XML as you would expect, but one call in particular returns a JSON string instead. This fouls up the xml parser on the client side. My question is; is the...
Python SUDS return type other than XML
I am working with a somewhat non-standard SOAP webservice. Most of the calls to the webservice return the standard SOAP XML as you would expect, but one call in particular returns a JSON string instead. This fouls up the xml parser on the client side. My question is; is there a way to designate the return type on a p...
[ "I would use the Python JSON encoder to validate first if it is JSON before feeding it to the XML parser.\ntry:\n json.loads(json_to_test)\nexcept ValueError:\n print \"Invalid json\"\n\n" ]
[ 1 ]
[]
[]
[ "json", "python", "suds" ]
stackoverflow_0007733180_json_python_suds.txt
Q: Python: best practice and securest way to connect to MySQL and execute queries What is the safest way to run queries on MySQL? I am aware of the dangers involved with MySQL and SQL injection. However, I do not know how I should run my queries to prevent injection on the variables to which other users (webclients) ...
Python: best practice and securest way to connect to MySQL and execute queries
What is the safest way to run queries on MySQL? I am aware of the dangers involved with MySQL and SQL injection. However, I do not know how I should run my queries to prevent injection on the variables to which other users (webclients) can manipulate. I used to write my own escape function, but apparently this is "not-...
[ "To avoid injections, use execute with %s in place of each variable, then pass the value via a list or tuple as the second parameter of execute. Here is an example from the documentation:\nc=db.cursor()\nmax_price=5\nc.execute(\"\"\"SELECT spam, eggs, sausage FROM breakfast\n WHERE price < %s\"\"\", (max_p...
[ 100, 86 ]
[]
[]
[ "mysql", "python", "sql_injection" ]
stackoverflow_0007929364_mysql_python_sql_injection.txt
Q: python map object methods I am looping through an array of objects, calling a method on each like so: for cell in cells: cell.update_type(next_cells[cell.index]) Is there a way to do the equivalent with map()? A: It appears update_type returns None, so you could use: any(cell.update_type(next_cells[cell.ind...
python map object methods
I am looping through an array of objects, calling a method on each like so: for cell in cells: cell.update_type(next_cells[cell.index]) Is there a way to do the equivalent with map()?
[ "It appears update_type returns None, so you could use:\nany(cell.update_type(next_cells[cell.index]) for cell in cells)\n\nbut unless there is a problem with a normal loop, just stick with that. It's the most readable and you shouldn't optimize prematurely.\nYou shouldn't use map here because there is no way to av...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0007929789_python.txt
Q: python string good practise: ' vs " Possible Duplicate: Single quotes vs. double quotes in Python I have seen that when i have to work with string in Python both of the following sintax are accepted: mystring1 = "here is my string 1" mystring2 = 'here is my string 2' Is anyway there any difference? Is it by a...
python string good practise: ' vs "
Possible Duplicate: Single quotes vs. double quotes in Python I have seen that when i have to work with string in Python both of the following sintax are accepted: mystring1 = "here is my string 1" mystring2 = 'here is my string 2' Is anyway there any difference? Is it by any reason better use one solution rather...
[ "No, there isn't. When the string contains a single quote, it's easier to enclose it in double quotes, and vice versa. Other than this, my advice would be to pick a style and stick to it.\nAnother useful type of string literals are triple-quoted strings that can span multiple lines:\ns = \"\"\"string literal...\n.....
[ 6, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "string", "syntax" ]
stackoverflow_0007929066_python_string_syntax.txt
Q: Python, Cloud - Online Web Scraping Tool with scheduling capabilities I'm planning to develop a Web/cloud application using python which does the following, 1. Upload Perl/Python scraping scripts and execute. 2. Uploaded scripts to run on a Schedule. 3. Run multiple instance of same script with different input par...
Python, Cloud - Online Web Scraping Tool with scheduling capabilities
I'm planning to develop a Web/cloud application using python which does the following, 1. Upload Perl/Python scraping scripts and execute. 2. Uploaded scripts to run on a Schedule. 3. Run multiple instance of same script with different input parameters. 4. Measure scripts performance. 5. View Scripts standard output/lo...
[ "Use Scrapy as the base for your work:\nhttp://scrapy.org/\nFor uploading, script performance and output (through web interface, I assume) you need to write your custom web front end which stores this information in a database where you can then explore it. One option for this is Pyramid:\nhttp://pypi.python.org/py...
[ 1 ]
[]
[]
[ "cloud", "python" ]
stackoverflow_0007927362_cloud_python.txt
Q: Best Way to Import Other Modules in Python when PYTHONPATH Cannot Be Modified? I'm coding my first project in python, and I'm unsure as to how to handle importing. I'm working on computers at my university and cannot modify the PYTHONPATH variable. I am also working on this project from a variety of computers/OS...
Best Way to Import Other Modules in Python when PYTHONPATH Cannot Be Modified?
I'm coding my first project in python, and I'm unsure as to how to handle importing. I'm working on computers at my university and cannot modify the PYTHONPATH variable. I am also working on this project from a variety of computers/OSs (so the path to the project is not always the same). I have a number of different ...
[ "First, you should read some of the stuff about Python paths in the following documents:\n\nhttp://docs.python.org/tutorial/modules.html#the-module-search-path\nhttp://www.doughellmann.com/PyMOTW/site/index.html\n\nTo solve your problem you could probably use a pth (python-search-path) file containing list of paths...
[ 1, 1, 0 ]
[]
[]
[ "directory", "import", "module", "project", "python" ]
stackoverflow_0007929706_directory_import_module_project_python.txt
Q: How to get updated data from the server without reloading the page in web2py I have made search bar functionality in a web2py application, getting results from a database. However, if the contents of the database are changed while the page is up, it needs to be reloaded to reflect the different content. My questio...
How to get updated data from the server without reloading the page in web2py
I have made search bar functionality in a web2py application, getting results from a database. However, if the contents of the database are changed while the page is up, it needs to be reloaded to reflect the different content. My question is how I can read the contents of the database into javascript variables without...
[ "Assuming your loadFromDB function is defined in the testDB view, then everything inside the {{ }} in loadFromDB will be filled in at the time the original page is created when testDB is called. The web2py template code does not get executed with the Javascript on the client side -- it is used to generate the initi...
[ 0 ]
[]
[]
[ "ajax", "database", "python", "web2py" ]
stackoverflow_0007926636_ajax_database_python_web2py.txt
Q: MySQLdb Python - does my code look correct? c.execute("""DELETE FROM data WHERE user = %s AND machine = %s""" , (user, machine)) I have two variables that were sent with get (technically they were machine+user, and then I split the variable based on the plus), who were then respectively assigned to the variables ...
MySQLdb Python - does my code look correct?
c.execute("""DELETE FROM data WHERE user = %s AND machine = %s""" , (user, machine)) I have two variables that were sent with get (technically they were machine+user, and then I split the variable based on the plus), who were then respectively assigned to the variables machine and user. Theoretically this script shoul...
[ "See my data won't go away. Hint: commit() needed\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0007929995_mysql_mysql_python_python.txt
Q: Attaching a single file to an e-mail Please forgive me up front. When I've tried to research this question I end up looking at code that I simply can't comprehend. I have about 3 hours of experience with Python and am probably attempting more than I can handle. The problem is simple. I can successfully call Pyt...
Attaching a single file to an e-mail
Please forgive me up front. When I've tried to research this question I end up looking at code that I simply can't comprehend. I have about 3 hours of experience with Python and am probably attempting more than I can handle. The problem is simple. I can successfully call Python from R (my analysis software) to send ...
[ "You might try using 'mailer' instead of trying to use SMTP directly. Mailer can be found here.\nHere is some simple code that shows how it works.\nmessages=[]\nmessage = mailer.Message()\nmessage.attach('filename.txt')\nmessage.From = 'Cool guy <cool.guy@example.com>'\nmessage.To = 'Random Dude <random.dude@examp...
[ 1, 0 ]
[]
[]
[ "attachment", "email", "python" ]
stackoverflow_0007922053_attachment_email_python.txt
Q: Thead-safe object and dict types in python I have two questions about creating thread safe types in python, and one related question about multiple inheritance. 1) Are there any problematic implications with using the following subclasses in my threaded application as a sort of "lazy" thread-safe type? I realize ...
Thead-safe object and dict types in python
I have two questions about creating thread safe types in python, and one related question about multiple inheritance. 1) Are there any problematic implications with using the following subclasses in my threaded application as a sort of "lazy" thread-safe type? I realize that whomever sets values which may be altered b...
[ "As to your first and second questions, the dict, list, etc. types are already thread-safe. You do not have to add thread safety to them. However you may find this useful. It's a decorator that basically implements the synchronized keyword from Java, using function scope to define a critical section. Using a si...
[ 1 ]
[]
[]
[ "python", "thread_safety" ]
stackoverflow_0007925535_python_thread_safety.txt
Q: wxFrame not closing I have a frame which I use as the main form (mainFrame), it inherits from mainFrameBase, which inherits from wxFrame. It has a "close" system button. When it is pressed the app shuts down. All very much to my liking. I inherit another frame from mainFrameBase (progScreen). When a button is pres...
wxFrame not closing
I have a frame which I use as the main form (mainFrame), it inherits from mainFrameBase, which inherits from wxFrame. It has a "close" system button. When it is pressed the app shuts down. All very much to my liking. I inherit another frame from mainFrameBase (progScreen). When a button is pressed, the progScreen is sh...
[ "What I would do is create two panels with the controls you want, one for the regular screen and one for the programming screen. Then when you want to switch, you hide one panel and show the other. That way, both screens are contained in one frame that when closed, exits the program. I actually have a tutorial that...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007921850_python_wxpython.txt
Q: Indexing into channel data (numpy arrays) using OpenCV python bindings I am trying to do a channel compare on two numpy arrays generated from the OpenCV (2.3.1) Python bindings. So, I have a mask (array/image/channel) of shape (x, y) that I want to compare against each channel of an RGB array/image of shape (x,y,3...
Indexing into channel data (numpy arrays) using OpenCV python bindings
I am trying to do a channel compare on two numpy arrays generated from the OpenCV (2.3.1) Python bindings. So, I have a mask (array/image/channel) of shape (x, y) that I want to compare against each channel of an RGB array/image of shape (x,y,3). Having halfway wrapped my head around numpy's slicing, I can get closer t...
[ "Don't use a slice, but rather a simple index:\nchannel = ndarr[..., i]\n\nThis actually behaves the same as slicing and indexing normal Python lists. Using a slice of length one results in a sublist, and using simple indexing results in the element being returned:\n>>> a = [0, 1, 2, 3, 4]\n>>> a[2:3]\n[2]\n>>> a[...
[ 4 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0007930679_numpy_opencv_python.txt
Q: Modify `PATH` environment variable globally and permanently using Python Is that possible to modify PATH environment variable, globally and permanently, in a platform-independent way using Python (distutils)? Background I have some application (a plugin for Serna XML Editor), and now I'm going to make an installer...
Modify `PATH` environment variable globally and permanently using Python
Is that possible to modify PATH environment variable, globally and permanently, in a platform-independent way using Python (distutils)? Background I have some application (a plugin for Serna XML Editor), and now I'm going to make an installer for it, probably using python distutils (setup.py). After the installation se...
[ "As far as I know, distutils has no cross-platform utility for permanently changing environment variables. So you will have to write platform specific code.\nIn Windows, environment variables are stored in the registry. This is a sample code to read and set some of it's keys. I use only the standard librarie (no ne...
[ 3, 0 ]
[]
[]
[ "cross_platform", "distutils", "environment_variables", "python" ]
stackoverflow_0007914505_cross_platform_distutils_environment_variables_python.txt
Q: Python-Integrate then save text file To all: This question pertains to some MS research I am doing. What I want to do is seemingly simple. I have a text file of values( time, .....values). I then want to integrate from 0 to those values for all times, then save that value to a text file. from numpy import * from...
Python-Integrate then save text file
To all: This question pertains to some MS research I am doing. What I want to do is seemingly simple. I have a text file of values( time, .....values). I then want to integrate from 0 to those values for all times, then save that value to a text file. from numpy import * from pylab import * import os, sys, shutil imp...
[ "The value of int is a float but savetxt requires an array. You want to create a numpy array for all the integration results, then save it at the end using savetxt. I think something like this should do the trick:\nint_array = apply_along_axis(trapz, 0, data)\nsavetxt('int.txt', int_array)\n\nKeep in mind that this...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007930671_numpy_python.txt
Q: setting permissions of python module (python setup install) I am configuring a distutils-based setup.py for a python module that is to be installed on a heterogeneous set of resources. Due to the heterogeneity, the location where the module is installed is not the same on each host however disutils picks the host...
setting permissions of python module (python setup install)
I am configuring a distutils-based setup.py for a python module that is to be installed on a heterogeneous set of resources. Due to the heterogeneity, the location where the module is installed is not the same on each host however disutils picks the host-specific location. I find that the module is installed without o...
[ "I'm not very knowledgeable about disutils, but I am guessing that If you dig through it until You find the place where your files are written then you will see the path variable on that line.\nthis page might help you\n", "os.path.dirname(__file__) may be what you're looking for. __file__ in a module returns the...
[ 0, 0, 0 ]
[]
[]
[ "distutils", "permissions", "python", "setup.py" ]
stackoverflow_0002753966_distutils_permissions_python_setup.py.txt
Q: Problems running a python script as a service I have used this question to learn install my python script as a service with ActivePython. I am able to install my script and remove it, as I would expect, but my problem is that once I start the script running, I then lose the ability to stop it or remove it. It ju...
Problems running a python script as a service
I have used this question to learn install my python script as a service with ActivePython. I am able to install my script and remove it, as I would expect, but my problem is that once I start the script running, I then lose the ability to stop it or remove it. It just runs permanently and I cannot get rid of it. Th...
[ "Of course you can't stop it, you're stuck in an infinite loop. Replace:\ntime.sleep(5)\n\nwith this:\nif win32event.WaitForSingleObject(self.hWaitStop, 5000) == win32event.WAIT_OBJECT_0: \n break\n\nShould do the trick.\n", "\"Checking a flag\" means having the script (inside the while True loop) look for som...
[ 6, 0 ]
[]
[]
[ "activepython", "python", "service", "windows" ]
stackoverflow_0007930447_activepython_python_service_windows.txt
Q: Django ManyToMany FIeld: 'tuple' object has no attribute 'user' Having a little django problem i'm stuck with... My Model: class Mymodel(models.Model): [...] user = models.ManyToManyField(User) My attempt to create a new user on it mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time) # T...
Django ManyToMany FIeld: 'tuple' object has no attribute 'user'
Having a little django problem i'm stuck with... My Model: class Mymodel(models.Model): [...] user = models.ManyToManyField(User) My attempt to create a new user on it mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time) # This one gives a solid Mymodel object i can play with mymodel.user.add...
[ "get_or_create returns a tuple consisting of (object, created). To get just the model, use:\nmymodel, _ = Mymodel.objects.get_or_create(date=date, day=day, time=time)\n\nor\nmymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time)[0]\n\n" ]
[ 11 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007931025_django_django_models_python.txt
Q: Python Installation Manager Often when I install .exe files made from python files I get an installation manager that is blue and has the logo "python powered". What is the name of this manager? I'd like to use it to make some installable python files. A: This is called distutils. A: More precisely, it may be...
Python Installation Manager
Often when I install .exe files made from python files I get an installation manager that is blue and has the logo "python powered". What is the name of this manager? I'd like to use it to make some installable python files.
[ "This is called distutils.\n", "More precisely, it may be the product of the distutils bdist_winsinst command, or the bdist_msi command, or maybe the product of py2exe, a third-party project building on distutils.\n" ]
[ 1, 0 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0003696183_distutils_python.txt
Q: Searching a Parallel Array in Python This is a homework question, I got the basics down, but I can't seem to find the correct method of searching two parallel arrays. Original Question: Design a program that has two parallel arrays: a String array named people that is initialized with the names of seven people, an...
Searching a Parallel Array in Python
This is a homework question, I got the basics down, but I can't seem to find the correct method of searching two parallel arrays. Original Question: Design a program that has two parallel arrays: a String array named people that is initialized with the names of seven people, and a String array named phoneNumbers that i...
[ "Since this is homework, I'll refrain from giving the code outright.\nYou can create a dict that works as a lookup table with the name as the key and the phone number as its value. \nCreating the lookup table:\nYou can easily convert the parallel arrays into a dict using dict() and zip(). Something along the lines ...
[ 6, 0 ]
[]
[]
[ "arrays", "parallel_arrays", "python" ]
stackoverflow_0007930980_arrays_parallel_arrays_python.txt
Q: CTRL-C terminate in python Currently, I have an exe that I need to pass commands to thru python. The code worked when it was by itself. When I merged that snippet with my final program, it failed to work. Basically, after the first two files upload using the program shell_start (upload is -f in the program i'm pa...
CTRL-C terminate in python
Currently, I have an exe that I need to pass commands to thru python. The code worked when it was by itself. When I merged that snippet with my final program, it failed to work. Basically, after the first two files upload using the program shell_start (upload is -f in the program i'm passing commands to), python decid...
[ "You may have better results by replacing the os.system calls with subprocess. \n\nThe subprocess module allows you to spawn new processes, connect to\n their input/output/error pipes, and obtain their return codes. This\n module intends to replace several other, older modules and functions,\n such as:\nos.syste...
[ 2 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0007931240_cmd_python.txt
Q: Can't save a shortcut into startup folder in windows xp with an "access is denied" com error I've written a Python program which uses comtypes/ctypes to create a shortcut and saves it in the Startup folder. In development mode, everything works great but when the program is built using py2exe and run, the followin...
Can't save a shortcut into startup folder in windows xp with an "access is denied" com error
I've written a Python program which uses comtypes/ctypes to create a shortcut and saves it in the Startup folder. In development mode, everything works great but when the program is built using py2exe and run, the following error occurs: (-2147024891, 'Access is denied.', (None, None, None, 0, None)) os is winxp sp3, t...
[ "Run your py2exe program with administrator privileges. \n", "Solved, the problem was that Commodo security center was blocking access to the aforementioned folder. So I just added the app to the trust list. As for the R6034 error, I just had to make sure to imbed the following in py2exe manifest xml section:\n ...
[ 1, 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0007924280_py2exe_python.txt
Q: Python formatting of strings with line breaks I'm trying to nicely format some text data from database to send in emails in Django. I'm encountering some problems with strings with line breaks. In particular,my desired output is: 1) t1 t2 t1_continue t2_end t1_end 2) s1 ...
Python formatting of strings with line breaks
I'm trying to nicely format some text data from database to send in emails in Django. I'm encountering some problems with strings with line breaks. In particular,my desired output is: 1) t1 t2 t1_continue t2_end t1_end 2) s1 s3 s1_continue s1_end ...
[ "How \\t is displayed will differ by OS, application, ect. For true string formatting, I would recommend checking the docs. For your example,\nprint('{0}) {1:<25} {2}'.format(index,col1,col2))\n\nWill do what you want, assuming that col1 is never larger than 24 characters. If it is, you can always adjust that v...
[ 3, 1, 1, 0 ]
[]
[]
[ "django", "python", "string_formatting" ]
stackoverflow_0007917814_django_python_string_formatting.txt
Q: Get the version from distutils setup.py How can I import or read the VERSION from the setup.py file so that I can log the version at runtime. This way I can make sure that the results obtained are from this particular version of my package. The following is the contents of my setup.py file (simplified to have the ...
Get the version from distutils setup.py
How can I import or read the VERSION from the setup.py file so that I can log the version at runtime. This way I can make sure that the results obtained are from this particular version of my package. The following is the contents of my setup.py file (simplified to have the necessary part) import distutils.core VERSION...
[ "There is a way to get the version from your setup script:\npython setup.py --version\n\nBut I’m not sure I understand what you mean with “log the version at runtime”; the setup script is normally not installed with your modules, so people use other ways to put a version number in their code, like a __version__ att...
[ 3, 0 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0006138386_distutils_python.txt
Q: python(numpy) -- another way to produce array (from another array) i did this code : from scitools.std import * npoints=10 vectorpoint=array(random.uniform(-1,1,[1,2])) experiment=array(random.uniform(-1,1,[npoints,2])) print("vectorpoint=",vectorpoint) print("experiment=",experiment) print(vectorpoint.shape) pr...
python(numpy) -- another way to produce array (from another array)
i did this code : from scitools.std import * npoints=10 vectorpoint=array(random.uniform(-1,1,[1,2])) experiment=array(random.uniform(-1,1,[npoints,2])) print("vectorpoint=",vectorpoint) print("experiment=",experiment) print(vectorpoint.shape) print(experiment.shape) which works fine. I wanted to ask if the "experi...
[ "If you want experiment to be an array with npoints lines which are all equal to vectorpoint, you can use\nexperiment = vstack([vectorpoint] * npoints)\n\nIf you want experiment to have npoints lines independently generated by random.uniform(), you have to call the latter function again, since vectorpoint only cont...
[ 1 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0007931545_arrays_numpy_python.txt
Q: How can I add post-install scripts to easy_install / setuptools / distutils? I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install). In my project, PySmell, I have some support files for Vim and Emacs. When a user inst...
How can I add post-install scripts to easy_install / setuptools / distutils?
I would like to be able to add a hook to my setup.py that will be run post-install (either when easy_install'ing or when doing python setup.py install). In my project, PySmell, I have some support files for Vim and Emacs. When a user installs PySmell the usual way, these files get copied in the actual egg, and the user...
[ "It depends on how the user installs your package. If the user actually runs \"setup.py install\", it's fairly easy: Just add another subcommand to the install command (say, install_vim), whose run() method will copy the files you want in the places where you want them. You can add your subcommand to install.sub_co...
[ 8, 0 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0000250038_distutils_python_setuptools.txt
Q: In Pyramid, how do I return raw HTML from a view? I'm really new to Pyramid (and pretty new to web frameworks in general). I'm trying to get to the stage where I can return raw HTML from a view, so that I can markup data returned from my mongoDB store. My __init__.py in my pyramid project is standard: def main(glo...
In Pyramid, how do I return raw HTML from a view?
I'm really new to Pyramid (and pretty new to web frameworks in general). I'm trying to get to the stage where I can return raw HTML from a view, so that I can markup data returned from my mongoDB store. My __init__.py in my pyramid project is standard: def main(global_config, **settings): """ This function returns a Py...
[ "To prevent Chameleon from escaping the ${result} variable, you need to use ${structure: result}, as per the documentation: http://chameleon.readthedocs.org/en/latest/reference.html#structure\n", "The string is being escaped, which is the default for strings inserted into templates to prevent naughty code being i...
[ 6, 0 ]
[]
[]
[ "html", "mongodb", "pyramid", "python" ]
stackoverflow_0007931492_html_mongodb_pyramid_python.txt
Q: How can I run a Makefile in setup.py? I need to compile ICU using it's own build mechanism. Therefore the question: How can I run a Makefile from setup.py? Obviously, I only want it to run during the build process, not while installing. A: The method I normally use is to override the command in question: from di...
How can I run a Makefile in setup.py?
I need to compile ICU using it's own build mechanism. Therefore the question: How can I run a Makefile from setup.py? Obviously, I only want it to run during the build process, not while installing.
[ "The method I normally use is to override the command in question:\nfrom distutils.command.install import install as DistutilsInstall\n\nclass MyInstall(DistutilsInstall):\n def run(self):\n do_pre_install_stuff()\n DistutilsInstall.run(self)\n do_post_install_stuff()\n\n...\n\nsetup(..., cm...
[ 43, 2, 0 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0001754966_distutils_python.txt
Q: Loops and totals in Python I am trying to write a program to draw a histogram of the lengths of words present in a list, so far I am up the stage of increasing the number of words present of a certain length by one every time the loop finds a word with that certain length, at the moment I have: L = [] for i in ran...
Loops and totals in Python
I am trying to write a program to draw a histogram of the lengths of words present in a list, so far I am up the stage of increasing the number of words present of a certain length by one every time the loop finds a word with that certain length, at the moment I have: L = [] for i in range(L): length = len(i) for len(i...
[ "In Python 2.7 or above, you could use a Counter:\nfrom collections import Counter\na = [\"basically\", \"in\", \"Python\", \"I\", \"am\", \"trying\", \"to\", \"write\",\n \"a\", \"program\", \"to\", \"draw\", \"a\", \"histogram\", \"of\", \"the\",\n \"lengths\", \"of\", \"words\", \"present\", \"in\", \"a\...
[ 2, 1, 0, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007931180_loops_python.txt
Q: What is the better way if at least one of some keys exists in a dictionary in python? I need check if at least one of a list of keys exist in a dict, I mean, I have a list of keys: keys = ['key1','key2','key3','key4','key5'] dict_ = {'key1': 1,'key2':2} # I could do something like if 'key1' in dict_ or 'key2' in d...
What is the better way if at least one of some keys exists in a dictionary in python?
I need check if at least one of a list of keys exist in a dict, I mean, I have a list of keys: keys = ['key1','key2','key3','key4','key5'] dict_ = {'key1': 1,'key2':2} # I could do something like if 'key1' in dict_ or 'key2' in dict_ or 'key3' in dict_: print True But I wonder if exist a more pythonic way to do th...
[ "Use Python's built-in any(), it takes an iterable and returns True if any of the elements are true, and it short circuits when it finds a match just like your chained or checks.\nif any(key in dict_ for key in keys):\n # do stuff\n\n", "You could use sets:\nIn [4]: len(set(dict_.keys()) & set(keys)) > 0\nOut[...
[ 9, 3 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0007931831_dictionary_list_python.txt
Q: Search for messages with attachments with GMail IMAP How to find all emails with attachments in GMail account using IMAP access? I'm on Python but is there only way to do this is to check each message? Thanks A: You may want to check out the IMAPClient library which gets rid of a lot of the frustrations of deali...
Search for messages with attachments with GMail IMAP
How to find all emails with attachments in GMail account using IMAP access? I'm on Python but is there only way to do this is to check each message? Thanks
[ "You may want to check out the IMAPClient library which gets rid of a lot of the frustrations of dealing with IMAP.\nThis is how you would get emails with attachments using IMAPClient:\nfrom imapclient import IMAPClient\n\nHOST = 'imap.gmail.com'\nUSERNAME = ''\nPASSWORD = ''\nssl = True\n\nserver = IMAPClient(HOST...
[ 7 ]
[]
[]
[ "gmail", "gmail_imap", "imap", "imaplib", "python" ]
stackoverflow_0007930686_gmail_gmail_imap_imap_imaplib_python.txt
Q: Python list issue I need some hints or an example, how can i localize in a list a the list b, then replace it with list c. a=[1,3,6,2,6,7,3,4,5,6,6,7,8] input the b list (this is the sublist the program searches for in list a). b=[6,7] when found return me the indexes were the sublist has been found and replace ...
Python list issue
I need some hints or an example, how can i localize in a list a the list b, then replace it with list c. a=[1,3,6,2,6,7,3,4,5,6,6,7,8] input the b list (this is the sublist the program searches for in list a). b=[6,7] when found return me the indexes were the sublist has been found and replace it each time with c=[0,...
[ "Here's a more efficient approach than my first, using list-slicing:\n>>> for i in xrange(len(a) - len(b) + 1):\n... if a[i:i+len(b)] == b:\n... a[i:i+len(b)] = c\n... \n>>> a\n[1, 3, 6, 2, 0, 0, 3, 4, 5, 6, 0, 0, 8]\n\n\nFirst attempt, for posterity....\nIf you don't need the intermediate indices, here...
[ 4, 3, 1, 0 ]
[]
[]
[ "indexing", "list", "python", "return", "search" ]
stackoverflow_0007913291_indexing_list_python_return_search.txt
Q: How can I securely gain programmatic access to supervisord via xmlrpc? I need to be able to manage the supervisord setup programmatically. Furthermore, not any user on the system should be able to to gain access to configuration of supervisord. For this reason, communication needs to be secured somehow. I know tha...
How can I securely gain programmatic access to supervisord via xmlrpc?
I need to be able to manage the supervisord setup programmatically. Furthermore, not any user on the system should be able to to gain access to configuration of supervisord. For this reason, communication needs to be secured somehow. I know that supervisord offers programmatic access in the form of XML-RPC. I read the ...
[ "Supervisor supports options to set permissions on the Unix domain socket.\nhttp://supervisord.org/configuration.html#unix-http-server-section-example\nI don't know the details but you should be able to call the xmlrpc interface over UNIX domain socket the same way that supervisorctl.py does. It's calling options....
[ 1 ]
[]
[]
[ "linux", "python", "security", "supervisord", "xml_rpc" ]
stackoverflow_0007854945_linux_python_security_supervisord_xml_rpc.txt
Q: Finding an optimal solution that minimizes a constraint? Let us call this problem the Slinger-Bird problem (actually the Slinger is analogous to a server and the bird to a request but I was having a nervous breakdown thinking about it so I changed them hoping to get a different perspective!). There are S stone t...
Finding an optimal solution that minimizes a constraint?
Let us call this problem the Slinger-Bird problem (actually the Slinger is analogous to a server and the bird to a request but I was having a nervous breakdown thinking about it so I changed them hoping to get a different perspective!). There are S stone throwers (slingers) and B birds. The slingers are not within t...
[ "This is not an optimal assignment problem, because slingers kill all birds in view.\nYou have a two-dimensional objective function, so there can be a number of tradeoffs between shots and time. Determining the minimum number of shots for a particular time limit is exactly the set cover problem (as mhum suggests). ...
[ 4, 1, 1 ]
[]
[]
[ "algorithm", "dynamic_programming", "python" ]
stackoverflow_0007927787_algorithm_dynamic_programming_python.txt
Q: Python call __init__() method only one time Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class? A: If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the follo...
Python call __init__() method only one time
Is there any way to call the init() method of a class only one time. Or how can I disable calling of init() when I create an object from a class?
[ "If you want a singleton, where there is only ever one instance of a class then you can create a decorator like the following as gotten from PEP18:\ndef singleton(cls):\n instances = {}\n def getinstance():\n if cls not in instances:\n instances[cls] = cls()\n return instances[cls]\n ...
[ 7, 2, 1, 0 ]
[]
[]
[ "init", "python" ]
stackoverflow_0007932093_init_python.txt
Q: Equivalent of python's int('hex-string', 16) in Javascript? Possible Duplicate: How to convert decimal to hex in JavaScript? Is there an equivalent of python's int('hex-string', 16) function in Javascript? A: You can use parseInt(): var result = parseInt("0x42", 16); // 66
Equivalent of python's int('hex-string', 16) in Javascript?
Possible Duplicate: How to convert decimal to hex in JavaScript? Is there an equivalent of python's int('hex-string', 16) function in Javascript?
[ "You can use parseInt():\nvar result = parseInt(\"0x42\", 16); // 66\n\n" ]
[ 7 ]
[]
[]
[ "hex", "javascript", "python" ]
stackoverflow_0007932210_hex_javascript_python.txt
Q: Python: Replacing certain Unicode entities with entities from dictionary I have read already much about the problem of backslash escaping in python strings (and backslash recognition in Python in different encodings) and using backslashes in regular expressions, but still cannot solve my problem. I would highly ap...
Python: Replacing certain Unicode entities with entities from dictionary
I have read already much about the problem of backslash escaping in python strings (and backslash recognition in Python in different encodings) and using backslashes in regular expressions, but still cannot solve my problem. I would highly appreciate any help (links, code examples, etc). I am trying to replace hexade...
[ "The sample text doesn't contain any backslashes. The \\u201c is just a way of representing a unicode character:\n>>> text = u'Try \\u201cquotated text should be here\\u201d try'\n>>> '\\\\' in text\nFalse\n>>> print text\nTry “quotated text should be here” try\n\nA regex is not really required here. Just translate...
[ 0 ]
[]
[]
[ "backslash", "python", "regex", "unicode" ]
stackoverflow_0007931100_backslash_python_regex_unicode.txt
Q: Is adding attributes dynamically frowned upon in Python? In Python, you can assign an arbitrary attribute from outside the defining class: class Profile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=140) p = Profile() p.age = 42 The underlying mechanism here is __d...
Is adding attributes dynamically frowned upon in Python?
In Python, you can assign an arbitrary attribute from outside the defining class: class Profile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length=140) p = Profile() p.age = 42 The underlying mechanism here is __dict__ attribute that maintains a dictionary of all attributes....
[ "My view is that it is a bad practice.\nThe object doesn't know that you're messing with its attributes. Consider, for example, what would happen if Profile were later expanded to have an attribute called age, unrelated to p.age in your code.\nIf you want to add attributes, why not subclass Profile, or have an exte...
[ 8, 5, 3 ]
[]
[]
[ "design_principles", "dynamic_languages", "encapsulation", "oop", "python" ]
stackoverflow_0007932124_design_principles_dynamic_languages_encapsulation_oop_python.txt
Q: change format sorl thumbnail can someone please give me an example of how to change the SORL-thumbnail format in the django template tag. I've read the documentation here: http://thumbnail.sorl.net/template.html#thumbnail and have tried various ways of implimenting to no avail. I get errors similar to: 'thumbnail'...
change format sorl thumbnail
can someone please give me an example of how to change the SORL-thumbnail format in the django template tag. I've read the documentation here: http://thumbnail.sorl.net/template.html#thumbnail and have tried various ways of implimenting to no avail. I get errors similar to: 'thumbnail' tag received a bad argument: 'for...
[ "Unfortunately Satchmo uses SORL-Thumbnail version 3.2.5, those docs are for 11. My guess is they didn't support formats in version 3.x. I haven't had any luck finding docs for it but you can probably dig through the code to be sure.\nIf I remember correctly you can swap out the library for version 11, but you'll h...
[ 3 ]
[]
[]
[ "django", "django_templates", "python", "satchmo", "sorl_thumbnail" ]
stackoverflow_0007863500_django_django_templates_python_satchmo_sorl_thumbnail.txt
Q: Something wrong with Mysqldb for python on mac Hi I'm trying to install mysqldb for python on a mac and below is the trace. Can anyone help? >>> import MySQLdb /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Lib...
Something wrong with Mysqldb for python on mac
Hi I'm trying to install mysqldb for python on a mac and below is the trace. Can anyone help? >>> import MySQLdb /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/_mysql.py:3: UserWarning: Module _mysql was already imported from /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2...
[ "Found the answer here. Not exactly sure what the symbolic link does though and if there are any better alternative solutions.\nMySQLdb error when running python server on MacOSX10.6\nsudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0007926626_mysql_mysql_python_python.txt
Q: Python script for monitoring Admin Console properties in Webshpere I've a requirement for writing a script in Python or JACL script in which I need to monitor and pull the information from Admin Console of the application running on remote server. I require to pull following information: jdbc jms web container ...
Python script for monitoring Admin Console properties in Webshpere
I've a requirement for writing a script in Python or JACL script in which I need to monitor and pull the information from Admin Console of the application running on remote server. I require to pull following information: jdbc jms web container threads default work manager threads. If anyone can help me writing thi...
[ "Create a file called config.py and paste the follwing into it.\n#\n## Récupération du fichier de config à partir des paramètres du script\n#\nimport sys\nif (len(sys.argv) > 0):\nconfigFile = sys.argv[0]\nelse:\nconfigFile = 'F:\\config.xml'\n\n#\n### Variables d'environnement du script\n#\nserver = AdminControl.q...
[ 5 ]
[]
[]
[ "ibm_mq", "jacl", "python", "scripting", "websphere" ]
stackoverflow_0007822546_ibm_mq_jacl_python_scripting_websphere.txt
Q: How should my users install a Python command line app for Mac? I want to create a command line app which would be run from the Terminal on Mac OS X (and eventually other platforms). I can make the Python script and have it running in Terminal, etc, but the problem comes for the user. I'd like the user to download ...
How should my users install a Python command line app for Mac?
I want to create a command line app which would be run from the Terminal on Mac OS X (and eventually other platforms). I can make the Python script and have it running in Terminal, etc, but the problem comes for the user. I'd like the user to download the app and install it as one normally would, and then call the app ...
[ "For a simple command line app on Mac OS X, you wouldn't need to package it as an OS X application bundle, which is what py2app and the deprecated BundleBuilder do. And an app bundle is not the normal way to access a command line utility since the user would have to \"reach in\" and execute something inside of the...
[ 5, 1, 1 ]
[]
[]
[ "command_line", "macos", "objective_c", "python" ]
stackoverflow_0007931613_command_line_macos_objective_c_python.txt
Q: How can I get all RelatedManagers from a particular Django Model instance? Let's say I have a set of Django Models: class Article(models.Model): title = models.CharField(max_length=100, default='') content = models.TextField(default='', blank=False) created_at = models.DateTimeField(auto_now=True) ...
How can I get all RelatedManagers from a particular Django Model instance?
Let's say I have a set of Django Models: class Article(models.Model): title = models.CharField(max_length=100, default='') content = models.TextField(default='', blank=False) created_at = models.DateTimeField(auto_now=True) creator = models.ForeignKey(User, null=True, blank=True) score = models.Fore...
[ "This seems to work for me:\ndef get_related_managers(self):\n managers = []\n for related_object in self._meta.get_all_related_objects():\n managers.append(getattr(self, related_object.get_accessor_name()))\n return managers\n\nYou will also have to loop through self._meta.get_all_related_many_to_m...
[ 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007932053_django_django_models_python.txt
Q: Is it acceptable to use **kwargs and a decorator to prevent repetitive code? I'm currently writing an api library in python and I'm wondering if the following code is too unpythonic: @accepts('video_id', 'reference_id', 'page_size', 'page_number', 'get_item_count', 'fields', 'video_fields', 'custom_fields...
Is it acceptable to use **kwargs and a decorator to prevent repetitive code?
I'm currently writing an api library in python and I'm wondering if the following code is too unpythonic: @accepts('video_id', 'reference_id', 'page_size', 'page_number', 'get_item_count', 'fields', 'video_fields', 'custom_fields', 'media_delivery', 'output') @requires('video_id', 'reference_id') def ...
[ "I'd definitely put the required fields in the method signature:\ndef find_related_videos(self, video_id, reference_id, **params):\n params.update({'video_id': video_id, 'reference_id': reference_id})\n return ItemCollection(read_request(params))\n\nIf possible, I'd even modify read_request to take keyword ar...
[ 1, 1, 0, 0 ]
[]
[]
[ "api", "decorator", "python" ]
stackoverflow_0007930929_api_decorator_python.txt
Q: python(numpy) -- create array and how to implement an expression i have this : npoints=10 vectorpoint=random.uniform(-1,1,[1,2]) experiment=random.uniform(-1,1,[npoints,2]) and now i want to create an array with dimensions [1,npoints]. I can't think how to do this. For example table=[1,npoints] Also, i want to ...
python(numpy) -- create array and how to implement an expression
i have this : npoints=10 vectorpoint=random.uniform(-1,1,[1,2]) experiment=random.uniform(-1,1,[npoints,2]) and now i want to create an array with dimensions [1,npoints]. I can't think how to do this. For example table=[1,npoints] Also, i want to evaluate this: for i in range(1,npoints): if experiment[i,0]**2+ex...
[ "Try:\ntable = (experiment[:,0]**2 + experiment[:,1]**2 <= 1).astype(int)\n\nYou can leave off the astype(int) call if you're happy with an array of booleans rather than an array of integers. As Joe Kington points out, this can be simplified to:\ntable = 1 - (experiment**2).sum(axis=1).astype(int)\n\nIf you really...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007932757_numpy_python.txt
Q: Regular expression in python - help needed Like many other people posting questions here, I recently started programming in Python. I'm faced with a problem trying to define the regular expression to extract a variable name (I have a list of variable names saved in the list) from a string. I am parsing part of the...
Regular expression in python - help needed
Like many other people posting questions here, I recently started programming in Python. I'm faced with a problem trying to define the regular expression to extract a variable name (I have a list of variable names saved in the list) from a string. I am parsing part of the code which I take line by line from a file. I m...
[ "It sounds like you just need to anchor your regex with ^ and $, unless I'm not understanding you properly:\n>>> mylist = ['var1', 'var2', 'var3_something', 'var1_text', 'var1var1']\n>>> import re\n>>> r = re.compile(r'^var1$')\n>>> matches = [item for item in mylist if r.match(item)]\n>>> print matches\n['var1']\n...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007931953_python_regex.txt
Q: Tkinter-Create Buttons according to dictionary keys I am trying to create a GUI for a small plotting program of logging files. I have all the data in a dictionary(actually a dict{dict{dict{dict{}}}}})and would like to use the keys to create tab-quantities for top keys checkboxes that basically will be selected to ...
Tkinter-Create Buttons according to dictionary keys
I am trying to create a GUI for a small plotting program of logging files. I have all the data in a dictionary(actually a dict{dict{dict{dict{}}}}})and would like to use the keys to create tab-quantities for top keys checkboxes that basically will be selected to plot the quantity versus time for the subkeys. I have loo...
[ "One way is to store references to your associated variables in a dictionary. Here's an example:\nimport Tkinter as tk\n\ndata = {\"Field 1\": 1,\n \"Field 2\": 2,\n \"Field 3\": 3,\n \"Field 4\": 4,\n}\n\nclass SampleApp(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007931470_python_tkinter.txt
Q: Using interpreter to lookup module 'sys' in Python So I just installed the python interpreter and wanted to use the help(sys) feature to get more information about the sys module, but I got this error and had no idea what went wrong. C:\Users\Jake>python Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64...
Using interpreter to lookup module 'sys' in Python
So I just installed the python interpreter and wanted to use the help(sys) feature to get more information about the sys module, but I got this error and had no idea what went wrong. C:\Users\Jake>python Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credi...
[ "Python uses the more program to show the help text. It's saying it can't find the more program. It should be at C:\\Windows\\System32\\more.com. You need to have C:\\Windows\\System32 in your PATH environment variable.\n", "more is a program used to display text in the terminal. I believe it generally comes ...
[ 8, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007924967_python.txt
Q: Simplify a date comparison I've got the following python code that does a date comparison for a list sort function (e.g. date_list.sort(cmp=dcmp). I'm wondering if it's possibly to remove the cmp/if testing and make it a oneliner. def dcmp(a, b): amm, add, ayy = [int(v) for v in a.split('/')] bmm, bdd, b...
Simplify a date comparison
I've got the following python code that does a date comparison for a list sort function (e.g. date_list.sort(cmp=dcmp). I'm wondering if it's possibly to remove the cmp/if testing and make it a oneliner. def dcmp(a, b): amm, add, ayy = [int(v) for v in a.split('/')] bmm, bdd, byy = [int(v) for v in b.split('/...
[ "You can use key instead of cmp. It is a lot easier to write a key function, and can be done in one line.\ndate_list.sort(key = lambda s: datetime.strptime(s, '%m/%d/%Y'))\n\nYou will also need this import:\nfrom datetime import datetime\n\n", "It's certainly cleaner to convert these values to actual dates (thoug...
[ 2, 0, 0, 0 ]
[ "Forget the date conversions, you can do this as strings. Just rearrange them to the proper order.\namm, add, ayy = a.split('/')\nbmm, bdd, byy = b.split('/')\nreturn cmp(ayy+amm+add, byy+bmm+bdd)\n\nI prefer to use the ISO date format which puts things in the proper order for comparison: YYYY-MM-DD. It also has th...
[ -1 ]
[ "python" ]
stackoverflow_0007921917_python.txt