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: Using IPMI inside a python script (OpenIPMI) I'd like to use IPMI to set a machine to PXE boot (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis bootdev pxe) and then power cycle it (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis power cycle). However, I'd like to do this in a ...
Using IPMI inside a python script (OpenIPMI)
I'd like to use IPMI to set a machine to PXE boot (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis bootdev pxe) and then power cycle it (i.e. ipmitool -I lan -U username -P password -H ipaddress chassis power cycle). However, I'd like to do this in a python script so I'm trying to use OpenIPMI and it...
[ "For something so simple it is much easier to just run those commands using the subprocess module.\nHowever, if you still choose the openimpi module here is an example of how to use it:\nhttp://www.mail-archive.com/ipmitool-devel@lists.sourceforge.net/msg01445.html\n", "I found the document IPMI – A Gentle Introd...
[ 3, 0 ]
[]
[]
[ "boot", "python" ]
stackoverflow_0003160525_boot_python.txt
Q: Pattern recognizing With an IQ of 70, I'm simply not smart enough to find out how I should do this. But! What I want is... to let Python e.g. read a table from MySQL and find a pattern for columns! Like, column X usually is value 'foo' when column Y is around '1.56' AND colum Z is around '756' e.g. That it finds a...
Pattern recognizing
With an IQ of 70, I'm simply not smart enough to find out how I should do this. But! What I want is... to let Python e.g. read a table from MySQL and find a pattern for columns! Like, column X usually is value 'foo' when column Y is around '1.56' AND colum Z is around '756' e.g. That it finds all this 'OBVIOUS' data......
[ "This is a complex topic. If you want to get started, try clustering your data using the scipy clustering libraries.\n" ]
[ 0 ]
[]
[]
[ "pattern_recognition", "python" ]
stackoverflow_0004340607_pattern_recognition_python.txt
Q: In python, what is contained in the info property of a module object? I'm looking into creating a Plugin structure for a program and making it so even the core library is treated as plugins. in my research I came across this code that is dynamically importing modules. def __initialize_def(self, module): """Att...
In python, what is contained in the info property of a module object?
I'm looking into creating a Plugin structure for a program and making it so even the core library is treated as plugins. in my research I came across this code that is dynamically importing modules. def __initialize_def(self, module): """Attempt to load the definition""" # Import works the same for py files an...
[ "py> import sys,os\npy> sys.modules[\"os\"].info[\"class\"]\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'module' object has no attribute 'info'\n\nSo this info attribute must be specific to modules that can be used as plugins in this program. \n", "Reserved names ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004341169_python.txt
Q: Convert a list of 2D numpy arrays to one 3D numpy array? I have a list of several hundred 10x10 arrays that I want to stack together into a single Nx10x10 array. At first I tried a simple newarray = np.array(mylist) But that returned with "ValueError: setting an array element with a sequence." Then I found the on...
Convert a list of 2D numpy arrays to one 3D numpy array?
I have a list of several hundred 10x10 arrays that I want to stack together into a single Nx10x10 array. At first I tried a simple newarray = np.array(mylist) But that returned with "ValueError: setting an array element with a sequence." Then I found the online documentation for dstack(), which looked perfect: "...Thi...
[ "newarray = np.dstack(mylist)\n\nshould work. For example:\nimport numpy as np\n\n# Here is a list of five 10x10 arrays:\nx = [np.random.random((10,10)) for _ in range(5)]\n\ny = np.dstack(x)\nprint(y.shape)\n# (10, 10, 5)\n\n# To get the shape to be Nx10x10, you could use rollaxis:\ny = np.rollaxis(y,-1)\nprint(y...
[ 44 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004341359_numpy_python.txt
Q: Apache with mod_wsgi segfaults I use apache2 mod_wsgi django to communicate with another soap to get information and return this information use soap! The apache will return none,and the log with child pid * exit signal Segmentation fault (11)! Who can help me?my English is badly,do you understand what i said? A...
Apache with mod_wsgi segfaults
I use apache2 mod_wsgi django to communicate with another soap to get information and return this information use soap! The apache will return none,and the log with child pid * exit signal Segmentation fault (11)! Who can help me?my English is badly,do you understand what i said?
[ "Read:\nhttp://code.google.com/p/modwsgi/wiki/FrequentlyAskedQuestions#Apache_Process_Crashes\n" ]
[ 2 ]
[]
[]
[ "django", "mod_wsgi", "python", "soap", "zsi" ]
stackoverflow_0004331310_django_mod_wsgi_python_soap_zsi.txt
Q: Slice specific characters in CSV using python I have data in tab delimited format that looks like: 0/0:23:-1.03,-7.94,-83.75:69.15 0/1:34:-1.01,-11.24,-127.51:99.00 0/0:74:-1.02,-23.28,-301.81:99.00 I am only interested in the first 3 characters of each entry (ie 0/0 and 0/1). I figured the best way to d...
Slice specific characters in CSV using python
I have data in tab delimited format that looks like: 0/0:23:-1.03,-7.94,-83.75:69.15 0/1:34:-1.01,-11.24,-127.51:99.00 0/0:74:-1.02,-23.28,-301.81:99.00 I am only interested in the first 3 characters of each entry (ie 0/0 and 0/1). I figured the best way to do this would be to use match and the genfromtxt in ...
[ "Unless you really want to use NumPy, try this:\nfile = open('home/python/batch1.hg19.table')\nfor line in file:\n for cell in line.split('\\t'):\n print(cell[:3])\n\nWhich just iterates through each line of the file, tokenizes the line using the tab character as the delimiter, then prints the slice of th...
[ 4, 3, 1, 0 ]
[]
[]
[ "csv", "numpy", "python" ]
stackoverflow_0004341405_csv_numpy_python.txt
Q: In Django templates, `Context` is a stack. What for? Django docs say that Context object is a stack: from django.template import Context c = Context() c['a'] = 1 c.push() # Make a new Context level c['a'] = 2 print(repr(c)) # [{'a': 1}, {'a': 2}] Also the docs say Using a Context as a stack comes in handy in som...
In Django templates, `Context` is a stack. What for?
Django docs say that Context object is a stack: from django.template import Context c = Context() c['a'] = 1 c.push() # Make a new Context level c['a'] = 2 print(repr(c)) # [{'a': 1}, {'a': 2}] Also the docs say Using a Context as a stack comes in handy in some custom template tags However, there's no example for th...
[ "The use case would be scoping, for example in loops and template inheritance.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0004341576_django_python_templates.txt
Q: How can I define an array in Python with undefined keys? searchindexnodes = [] searchindexnodes[1036592] = 'Apparel' searchindexnodes[672123011] = 'Apparel' searchindexnodes[165796011] = 'Baby' This doesn't appear to be working. Any thoughts? A: I think a better solution would be to use a dictionary. If you wa...
How can I define an array in Python with undefined keys?
searchindexnodes = [] searchindexnodes[1036592] = 'Apparel' searchindexnodes[672123011] = 'Apparel' searchindexnodes[165796011] = 'Baby' This doesn't appear to be working. Any thoughts?
[ "I think a better solution would be to use a dictionary. If you wanted a list with empty elements you'd be creating a list with over 100,000,000 elements which would be a huge waste of memory.\nsearchindexnodes = {}\nsearchindexnodes[1036592] = 'Apparel'\n\nPython implements searching quickly in dictionary data st...
[ 5, 3 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0004341931_arrays_python.txt
Q: How do I print out the full traceback in my except call? Right now, I do this: try: blah except Exception, e: print e time.sleep(9999) Instead of print e, I want to print out the entire traceback. And then sleep it for 999. A: import traceback traceback.print_exc()
How do I print out the full traceback in my except call?
Right now, I do this: try: blah except Exception, e: print e time.sleep(9999) Instead of print e, I want to print out the entire traceback. And then sleep it for 999.
[ "import traceback \ntraceback.print_exc() \n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004342021_python.txt
Q: How do I do parsing in Django templates? post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] } Suppose I pass that to my Django templates. Now, I want to display the title where width = 200. How can I do that, without doing it the brute-force way: {{ post.sizes.1.title }} I want to do it the parsed...
How do I do parsing in Django templates?
post = { sizes: [ { w:100, title="hello"}, {w:200, title="bye"} ] } Suppose I pass that to my Django templates. Now, I want to display the title where width = 200. How can I do that, without doing it the brute-force way: {{ post.sizes.1.title }} I want to do it the parsed way.
[ "A neat way to do it is with a filter template tag.\nfrom django.template import Library\n\nregister = Library()\n\n@register.filter('titleofwidth')\ndef titleofwidth(post, width):\n \"\"\"\n Get the title of a given width of a post.\n\n Sample usage: {{ post|titleofwidth:200 }}\n \"\"\"\n\n for i in...
[ 2, 0 ]
[]
[]
[ "dictionary", "django", "list", "python", "templates" ]
stackoverflow_0004341944_dictionary_django_list_python_templates.txt
Q: Why doesn't my Python script work? This function raises an exception no matter what I change: def some_func(name=None): if name isn't None: print(name) Then I try to run it: some_func('Tom') It raises this exception: Sorry, there was an error in processing this form action "some_func". Please report ...
Why doesn't my Python script work?
This function raises an exception no matter what I change: def some_func(name=None): if name isn't None: print(name) Then I try to run it: some_func('Tom') It raises this exception: Sorry, there was an error in processing this form action "some_func". Please report the error or try again later. (Error cal...
[ "use\nis not None\n\ninstead of\nisn't None\n\n", "isn't isn't a keyword. It should be is not.\n" ]
[ 2, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0004342285_exception_python.txt
Q: Can hasattr go multiple children deep in Python? If I have node.child1.child2, can I use hasattr(node, 'child1.child2') effectively? Will it error if there's no child1 or simply return false? A: hasattr doesn't take a dotted name like that and navigate down attribute chains. But you can write a function to do i...
Can hasattr go multiple children deep in Python?
If I have node.child1.child2, can I use hasattr(node, 'child1.child2') effectively? Will it error if there's no child1 or simply return false?
[ "hasattr doesn't take a dotted name like that and navigate down attribute chains. But you can write a function to do it:\ndef get_deep_attr(obj, attrs):\n for attr in attrs.split(\".\"):\n obj = getattr(obj, attr)\n return obj\n\ndef has_deep_attr(obj, attrs):\n try:\n get_deep_attr(obj, att...
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0004342168_python.txt
Q: Python C API: Call a Python function with argument(s) passed by reference I'm writing a python module in C and I need to have it call a Python function with one of the arguments passed by "reference". The end result should be that what the Python function does to the argument gets saved into the original C variab...
Python C API: Call a Python function with argument(s) passed by reference
I'm writing a python module in C and I need to have it call a Python function with one of the arguments passed by "reference". The end result should be that what the Python function does to the argument gets saved into the original C variable. int *resume; // this int is actually passed in to this body of co...
[ "I think you're misunderstanding something about how variables work in Python. Variables in Python do not contain values; they refer to them - like in Java, except there are no \"primitives\" (not even int). Assignment to a variable doesn't overwrite the old value; it simply causes the variable to refer to the new ...
[ 4 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0004342560_c_python_python_c_api.txt
Q: Recursive Selection Sort python There is a recursive selection sort in the upcoming question that has to be done. def selsort(l): """ sorts l in-place. PRE: l is a list. POST: l is a sorted list with the same elements; no return value. """ l1 = list("sloppy joe's hamburger...
Recursive Selection Sort python
There is a recursive selection sort in the upcoming question that has to be done. def selsort(l): """ sorts l in-place. PRE: l is a list. POST: l is a sorted list with the same elements; no return value. """ l1 = list("sloppy joe's hamburger place") vl1 = l1 print l1 # shou...
[ "So. Do you understand the problem?\nLet's look at what you were asked to do:\n\nextract the maximum element, instead of the minimum, only to .append(...) it on to a recursively sorted sublist.\n\nSo, we do the following things:\n1) Extract the maximum element. Do you understand what \"extract\" means here? Do you ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004342042_python.txt
Q: python tennis scoreboard Need some help with a year end tennis program assignment: In this problem you will provide an interface and display for a tennis match. Here are the rules for scoring a tennis match. • There are two players. Let’s call them Player 1 and Player 2. • Players rally the ball back and forth, an...
python tennis scoreboard
Need some help with a year end tennis program assignment: In this problem you will provide an interface and display for a tennis match. Here are the rules for scoring a tennis match. • There are two players. Let’s call them Player 1 and Player 2. • Players rally the ball back and forth, and the winner of each rally ear...
[ "Write a function that returns if someone (optionally who) wins, and another function that tests the players' scores and returns the score situation string. Loop through calling umpire(), accumulating the points, and getting and outputting the situation until someone wins (hint: while not winnerfunc(...):).\n", "...
[ 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0004341934_loops_python.txt
Q: Is it possible to put a python dictionary in AMQP? Usually I'm used to putting strings in beanstalkc. But I'd like to put a dictionary as a job in amqp. A: json.dumps()
Is it possible to put a python dictionary in AMQP?
Usually I'm used to putting strings in beanstalkc. But I'd like to put a dictionary as a job in amqp.
[ "json.dumps()\n" ]
[ 1 ]
[]
[]
[ "amqp", "dictionary", "python" ]
stackoverflow_0004342167_amqp_dictionary_python.txt
Q: Jython, Jepp or Pylons for the performance I'm trying to incorporate server-based code diff and highlighting in my GWT (Java) project. I managed to incorporate Pygments and difflib into my code using Jython. The basic idea is to generate complete markup on the server and then simply inject code into the page as in...
Jython, Jepp or Pylons for the performance
I'm trying to incorporate server-based code diff and highlighting in my GWT (Java) project. I managed to incorporate Pygments and difflib into my code using Jython. The basic idea is to generate complete markup on the server and then simply inject code into the page as innerHTML. I found Jython completely inadequate a...
[ "Having a separate service sounds like the best way to go. For Pygments, there is already a service available (on Google App Engine). The source for the app is BSD open source and on GitHub here. You could adapt this to add difflib functionality too, of course.\n", "I'm going to accept answer above since it coin...
[ 0, 0 ]
[]
[]
[ "jython", "performance", "pylons", "python" ]
stackoverflow_0004329303_jython_performance_pylons_python.txt
Q: How to 'import *' and call imported functions when package is directory not file If I'm developing a client-server app and have 3 files (client.py, server.py, and common.py,) and common.py has a useful function (e.g. normalize()), it's easy from both client and server to do something like this: from common import ...
How to 'import *' and call imported functions when package is directory not file
If I'm developing a client-server app and have 3 files (client.py, server.py, and common.py,) and common.py has a useful function (e.g. normalize()), it's easy from both client and server to do something like this: from common import * url = normalize(url) However if, for various strange reasons, I'd rather have sepa...
[ "Anything the __init__.py within the directory imports will be imported on import * provided it's not restricted by __all__.\n", "Move client.py to client/__init__.py, server.py to server/__init__.py and common to common/__init__.py and all will work as before.\nAs far as naming is concerned, client.py is a modul...
[ 5, 0 ]
[]
[]
[ "client_server", "import", "package", "python" ]
stackoverflow_0004343074_client_server_import_package_python.txt
Q: Is there anyway to give a Zookeeper node a NULL ACL via python-bindings? I'm trying to create a node using the python bindings that are bundled with the zookeeper distribution ( src/contrib/zkpython/ ). Using zookeeper-3.3.1. The pydoc for create states that if the ACL is NULL then that node will inherit its paren...
Is there anyway to give a Zookeeper node a NULL ACL via python-bindings?
I'm trying to create a node using the python bindings that are bundled with the zookeeper distribution ( src/contrib/zkpython/ ). Using zookeeper-3.3.1. The pydoc for create states that if the ACL is NULL then that node will inherit its parents ACL however setting this parameter to None causes an invalid ACL exception....
[ "I had the same problem and found no solution. As workaround you could add an additional step. Example:\nimport zookeeper as zk\nparent_path = \"/\"\nstat, acl = zk.get_acl(zoohandle, parent_path)\nret = zk.create(zoohandle, node_path, \"\", acl, 0)\n\nFurther tip: In zookeeper-3.3.1 the zk.get() only returns up to...
[ 2 ]
[]
[]
[ "apache_zookeeper", "python" ]
stackoverflow_0004329940_apache_zookeeper_python.txt
Q: How to upload multiple file in django admin models file = models.FileField(upload_to=settings.FILE_PATH) For uploading a file in django models I used the above line. But For uploading multiple file through django admin model what should I do? I found this But this is for forms. Can I use this for models? A: I...
How to upload multiple file in django admin models
file = models.FileField(upload_to=settings.FILE_PATH) For uploading a file in django models I used the above line. But For uploading multiple file through django admin model what should I do? I found this But this is for forms. Can I use this for models?
[ "If you want to have multiple files for the same field you would have to write your own field and widget based on the form field you have found otherwise have a separate model for file with a foreign key to your main model and use ModelInline.\nmodels.py\nclass Page(models.Model):\n title = models.CharField(max_...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004343413_django_python.txt
Q: Does a django query save its result after it's been called? I'm trying to determine whether or not a simple caching trick will actually be useful. I know Django querysets are lazy to improve efficiency, but I'm wondering if they save the result of their query after the data has been called. For instance, if I hav...
Does a django query save its result after it's been called?
I'm trying to determine whether or not a simple caching trick will actually be useful. I know Django querysets are lazy to improve efficiency, but I'm wondering if they save the result of their query after the data has been called. For instance, if I have two models: class Klass1(models.Model): k2 = models.Fore...
[ "Django will not cache it for you.\nInstead of Klass1.objects.filter(k2=self), you could just do self.klass1_set.all().\nBecause Django always create a set in the many side of 1-n relations.\nI guess this kind of cache is complicated because it should remember all filters, excludes and order_by used. Although it co...
[ 1, 1, 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0004341741_django_django_models_django_queryset_python.txt
Q: Parallel programming using python's multiprocessing and process defunc I have a problem with creating parallel program using multiprocessing. AFAIK when I start a new process using this module (multiprocessing) I should do "os.wait()" or "childProcess.join()" to get its' exit status. But placing above functions in...
Parallel programming using python's multiprocessing and process defunc
I have a problem with creating parallel program using multiprocessing. AFAIK when I start a new process using this module (multiprocessing) I should do "os.wait()" or "childProcess.join()" to get its' exit status. But placing above functions in my program can occur in stopping main process if something happens to child...
[ "Though ars' answer should solve your immediate issues, you might consider looking at celery: http://ask.github.com/celery/index.html. It's a relatively developer-friendly approach to accomplishing these goals and more. \n", "You may have to provide more information or actual code to figure this out. Have you ...
[ 2, 0 ]
[]
[]
[ "join", "multiprocessing", "parallel_processing", "python", "wait" ]
stackoverflow_0003297980_join_multiprocessing_parallel_processing_python_wait.txt
Q: Repeatedly write to stdin and read from stdout of a process from python I have a piece of fortran code that reads some numbers from STDIN and writes results to STDOUT. For example: do read (*,*) x y = x*x write (*,*) y enddo So I can start the program from a shell and get the following sequence of inputs/ou...
Repeatedly write to stdin and read from stdout of a process from python
I have a piece of fortran code that reads some numbers from STDIN and writes results to STDOUT. For example: do read (*,*) x y = x*x write (*,*) y enddo So I can start the program from a shell and get the following sequence of inputs/outputs: 5.0 25.0 2.5 6.25 Now I need to do this from within python. After fut...
[ "Found a solution using the subprocess module, so I'm posting it here for reference if anyone needs to do the same thing.\nimport subprocess as sbp\n\nclass ExternalProg:\n\n def __init__(self, arg_list):\n self.opt = sbp.Popen(arg_list, stdin=sbp.PIPE, stdout=sbp.PIPE, shell=True, close_fds=True)\n\n ...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003503861_python.txt
Q: After inserting an item into MongoDb, how do you get its ObjectID? last inserted objectid, just like the one MYSQL has. A: If you're using the standard Python API, it returns the ObjectID when you call insert. Are you expecting/trying to get the ObjectID in some other manner?
After inserting an item into MongoDb, how do you get its ObjectID?
last inserted objectid, just like the one MYSQL has.
[ "If you're using the standard Python API, it returns the ObjectID when you call insert. Are you expecting/trying to get the ObjectID in some other manner?\n" ]
[ 6 ]
[]
[]
[ "database", "mongodb", "mysql", "python" ]
stackoverflow_0004344365_database_mongodb_mysql_python.txt
Q: Proper way to publish and find services on a LAN using Python My app opens a TCP socket and waits for data from other users on the network using the same application. At the same time, it can broadcast data to a specified host on the network. Currently, I need to manually enter the IP of the destination host to b...
Proper way to publish and find services on a LAN using Python
My app opens a TCP socket and waits for data from other users on the network using the same application. At the same time, it can broadcast data to a specified host on the network. Currently, I need to manually enter the IP of the destination host to be able to send data. I want to be able to find a list of all hosts ...
[ "Zeroconf/DNS-SD is an excellent idea in this case. It's provided by Bonjour on OS X and Windows (but must be installed separately or as part of an Apple product on Windows), and by Avahi on FOSS *nix.\n", "\nit can broadcast data to a specified host on the network\n\nThis is a non-sequitur.\nI'm presuming that y...
[ 2, 2, 0, 0 ]
[]
[]
[ "bonjour", "networking", "python", "zeroconf" ]
stackoverflow_0004343575_bonjour_networking_python_zeroconf.txt
Q: Python Imaging, how to quantize an image to 16bit depth? I would like to quantize a 24bit image to 16bit color depth using Python Imaging. PIL used to provide a method im.quantize(colors, **options) however this has been deprecated for out = im.convert("P", palette=Image.ADAPTIVE, colors=256) Unfortunately 256 is ...
Python Imaging, how to quantize an image to 16bit depth?
I would like to quantize a 24bit image to 16bit color depth using Python Imaging. PIL used to provide a method im.quantize(colors, **options) however this has been deprecated for out = im.convert("P", palette=Image.ADAPTIVE, colors=256) Unfortunately 256 is the MAXIMUM number of colors that im.convert() will quantize t...
[ "You might want to look into converting your image to a numpy array, performing your quantisation, then converting back to PIL.\nThere are modules in numpy to convert to/from PIL images.\n" ]
[ 3 ]
[]
[]
[ "imaging", "python", "python_imaging_library" ]
stackoverflow_0004345337_imaging_python_python_imaging_library.txt
Q: Python: unpack dictionary inside a method In Python, I want to create a new object by loading a number of variables into it. The easiest way is to pass a dictionary, but that makes programming very annoying: instead of self.health I have to call self.params['health'] all the time. Is there any way to set variable ...
Python: unpack dictionary inside a method
In Python, I want to create a new object by loading a number of variables into it. The easiest way is to pass a dictionary, but that makes programming very annoying: instead of self.health I have to call self.params['health'] all the time. Is there any way to set variable names (fields) dynamically? I have: DEFAULT_PA...
[ "class Name(object):\n def __init__(self, *params):\n self.__dict__.update(DEFAULT_PARAMS)\n self.__dict__.update(params)\n\nb = Name(position=[1,2])\nprint b.position\n\n", "You can use\nsetattr(self, name, value)\n\nto create a new attritbute of self with the dynamic name name and the value val...
[ 5, 2, 2, 0 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0004345500_python_variables.txt
Q: Writing a small yet flexible HTTP client I'm looking to find out how people would go about writing a quick (small) yet flexible HTTP client. By quick I mean not much code, (I'll leave it up to you to decide what that means), and preferably using built-in language functions as opposed to downloaded or custom librar...
Writing a small yet flexible HTTP client
I'm looking to find out how people would go about writing a quick (small) yet flexible HTTP client. By quick I mean not much code, (I'll leave it up to you to decide what that means), and preferably using built-in language functions as opposed to downloaded or custom libraries, such that a basic knowledge of socket pro...
[ "Perl has LWP. I suggest you use it.\n", "Similar to @Santa's example, only in Ruby:\nrequire 'open-uri'\nprint open('http://www.example.com').read\n\nIf you want to parse the content, Ruby's Nokogiri gem is awesome. It's built on top of libXML.\nMany other HTTP client gems are available, including HTTParty and T...
[ 9, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "http", "perl", "python", "ruby" ]
stackoverflow_0004220601_http_perl_python_ruby.txt
Q: Html element position in Python I'm using lxml.html for some html parsing in python. I'd like to get a rough estimate of the location of elements within the page after it would be rendered by a browser. It does not have to be exact, but generally correct. For simplicity I will ignore the effects of Javascript o...
Html element position in Python
I'm using lxml.html for some html parsing in python. I'd like to get a rough estimate of the location of elements within the page after it would be rendered by a browser. It does not have to be exact, but generally correct. For simplicity I will ignore the effects of Javascript on element location. As an end result...
[ "PyQt with webkit:\nimport sys\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtWebKit import *\n\nclass MyWebView(QWebView):\n def __init__(self):\n QWebView.__init__(self)\n QObject.connect(self,SIGNAL('loadFinished(bool)'),self.showelements)\n\n def showelements(self):\n ...
[ 5, 1 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0004345258_html_lxml_python.txt
Q: Is there a better way to create this model? (Django) I have a model that pings a REST service and saves the results. class StoreStatus(models.Model): store = models.OneToOneField(Store) status = models.TextField() def save(self, *args, **kwargs): self.status = get_store_information(self.store...
Is there a better way to create this model? (Django)
I have a model that pings a REST service and saves the results. class StoreStatus(models.Model): store = models.OneToOneField(Store) status = models.TextField() def save(self, *args, **kwargs): self.status = get_store_information(self.store.code) self.pk = self.store.pk super(...
[ "That looks quite bad.\nFirst, associating the retrieval of the status information with the saving of the object is quite a bad idea. If 'updating' is the only action you'll ever perform on this model, then maybe a better idea would be to write a an \"update()\" method that automatically saves once the status is up...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004314897_django_django_models_python.txt
Q: How to resolve this GAE status 500 error Hi I'm looking for how to resolve an error on the production server where AFAIK the instruction looks correct: from google.appengine.ext.webapp import template When at the log it says <type 'exceptions.ImportError'>: cannot import name template On the local dev server it ...
How to resolve this GAE status 500 error
Hi I'm looking for how to resolve an error on the production server where AFAIK the instruction looks correct: from google.appengine.ext.webapp import template When at the log it says <type 'exceptions.ImportError'>: cannot import name template On the local dev server it works normally. I suspect it's a problem with ...
[ "I had a similar problem this morning. \nIf you just updated to the new version (1.4) that was released today, you might need to update you paths. (I use mac and hade do lunch the Google App Engine Launcher to set the new paths.)\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004346070_google_app_engine_python.txt
Q: Python : generate a graph for a social network I have installed matplotlib and networkx packages. Can someone tell me the function present in these packages that can be used to generate a social network graph like graph for film actor collaborations, co-authorship or even a graph for a P2P network. A: I think th...
Python : generate a graph for a social network
I have installed matplotlib and networkx packages. Can someone tell me the function present in these packages that can be used to generate a social network graph like graph for film actor collaborations, co-authorship or even a graph for a P2P network.
[ "I think that matplotlib is not too suitable for this task. Try PIL instead. \nAlso, this post shows how Christian S. Perone used Ubigraph to create 3D visualization of Twitter users\n", "I would use PyDot, it's the pythton binding of the graphviz library.\n", "Count this as a second vote for Graphviz. The for...
[ 3, 2, 1, 1 ]
[]
[]
[ "python", "social_networking" ]
stackoverflow_0002085676_python_social_networking.txt
Q: SQL Server - Query logs? any idea where I can read logs of recent queries? Errors are coming back when using Django for queries that seem to be alright, and cannot understand what is wrong. Any ideas? A: As I understanded you need MS SQL Profiler. But it log only new queries. A: There are no logs of recent qu...
SQL Server - Query logs?
any idea where I can read logs of recent queries? Errors are coming back when using Django for queries that seem to be alright, and cannot understand what is wrong. Any ideas?
[ "As I understanded you need MS SQL Profiler. But it log only new queries.\n", "There are no logs of recent queries. You can use SQL Profiler / SQL Trace to monitor queries ongoing though.\nYou can also look in sys.dm_exec_cached_plans for recent plans and associated text which might help depending on whether the...
[ 4, 3, 1 ]
[]
[]
[ "django", "python", "sql", "sql_server", "sql_server_2008" ]
stackoverflow_0004346164_django_python_sql_sql_server_sql_server_2008.txt
Q: pygtk assertion fail when using a generator to thread and callback to add elements to a treeview due to treeviewiter parent Using the Generator class from http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html, the following code makes my program fail: import gtk import gobject from GeneratorTask impor...
pygtk assertion fail when using a generator to thread and callback to add elements to a treeview due to treeviewiter parent
Using the Generator class from http://unpythonic.blogspot.com/2007/08/using-threads-in-pygtk.html, the following code makes my program fail: import gtk import gobject from GeneratorTask import GeneratorTask GeneratorTask(self.get_playlist, self.load_playlist).start(playlist_id, model, iter, child) def get_playlist(se...
[ "Just remembered, that when I was going through lablgtk tutorial, there was a hint that Gtk.tree_iters are short-lived and there was a suggestion to use Gtk.row_references instead. Sorry, this is not python, however You may find it useful: lablgtk:treeview:referring to rows\n" ]
[ 1 ]
[]
[]
[ "events", "gtktreeview", "multithreading", "pygtk", "python" ]
stackoverflow_0004346545_events_gtktreeview_multithreading_pygtk_python.txt
Q: Should user data be stored in a config file? I'm developing a CLI for a web todolist service. I'm done with the backend and have just started to write the CLI functions. Before I start, I tought what the best way was to store user data. I'm using ConfigParser for storing user specified preferencies. These are stor...
Should user data be stored in a config file?
I'm developing a CLI for a web todolist service. I'm done with the backend and have just started to write the CLI functions. Before I start, I tought what the best way was to store user data. I'm using ConfigParser for storing user specified preferencies. These are stored in ~/.confrc. The user data is in the form of ...
[ "If there is only one file to store, using ~/.${PROJECT}rc is a good idea, otherwise, use a separate directory ~/.${PROJECT}.\nYou could also refer to the XDG Base Directory Specification.\n" ]
[ 5 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0004346658_configparser_python.txt
Q: How to programmatically get SVN revision number? Like this question, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the .svn fol...
How to programmatically get SVN revision number?
Like this question, but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is a bad idea). I assume this info is in a file in the .svn folder somewhere, but where, and how do I parse it? I wan...
[ "Subversion includes the svnversion tool for exactly this purpose. A working copy may actually have local modifications, or may consist of a mix of revisions. svnversion knows how to handle that; see the examples in the linked documentation.\nYou can invoke svnversion from python like this:\nimport subprocess\n\nde...
[ 13, 4, 3, 3, 3, 2, 2, 1, 0 ]
[]
[]
[ "php", "python", "svn" ]
stackoverflow_0001499811_php_python_svn.txt
Q: Genshi pluralisation Anyone know how I could show entry/entries as appropriate, in the following fragment of Genshi syntax? <span py:if="c.page.item_count"> ${c.page.item_count} entries. </span> Thanks! A: Not pretty, but should work <span py:if="c.page.item_count"> ${c.page.item_count} ${['entries','...
Genshi pluralisation
Anyone know how I could show entry/entries as appropriate, in the following fragment of Genshi syntax? <span py:if="c.page.item_count"> ${c.page.item_count} entries. </span> Thanks!
[ "Not pretty, but should work\n<span py:if=\"c.page.item_count\">\n ${c.page.item_count} ${['entries','entry'][c.page.item_count==1]}.\n</span>\n\nor\n<span py:if=\"c.page.item_count\">\n ${c.page.item_count} ${'entry' if c.page.item_count==1 else 'entries'}.\n</span>\n\n" ]
[ 0 ]
[]
[]
[ "genshi", "python" ]
stackoverflow_0004346871_genshi_python.txt
Q: How to parse through string containing url changing them to proper links Let's say I have a following string from twitter: "This is my sample test blah blah http://t.co/pE6JSwG, hello all" How I can parse through this string changing this link to <a href="link">link</a> ? Here's a code that parses user tags : ...
How to parse through string containing url changing them to proper links
Let's say I have a following string from twitter: "This is my sample test blah blah http://t.co/pE6JSwG, hello all" How I can parse through this string changing this link to <a href="link">link</a> ? Here's a code that parses user tags : tweet = s.text; user_regex = re.compile(r'@[0-9a-zA-Z+_]*',re.IGNORECASE) ...
[ "Perhaps you could get inspiration from the source code of the django-oembed project.\n", ">>> test = \"This is my sample test blah blah http://t.co/pE6JSwG, hello all\"\n\n>>> re.sub('http://[^ ,]*', lambda t: \"<a href='%s'>%s</a>\" % (t.group(0), t.group(0)), test)\n\n>>> This is my sample test blah blah <a hr...
[ 1, 1 ]
[]
[]
[ "django", "parsing", "python", "string_parsing", "twitter" ]
stackoverflow_0004346895_django_parsing_python_string_parsing_twitter.txt
Q: How can I INSERT into a MySQL table in Python with a variable number of columns? I have a variable row_data = (searchindex, asin, title, browsenode, salesrank, brand, listprice, saleprice) and either of those elements might be NULL, to insert into a database, I'm using sql = "INSERT INTO table (searchindex,asin,ti...
How can I INSERT into a MySQL table in Python with a variable number of columns?
I have a variable row_data = (searchindex, asin, title, browsenode, salesrank, brand, listprice, saleprice) and either of those elements might be NULL, to insert into a database, I'm using sql = "INSERT INTO table (searchindex,asin,title,browsenode, salesrank, brand, listprice, saleprice) VALUES ('%s','%s','%s','%s', '...
[ "Please don't use string interpolation to construct SQL, as it is very unsafe. Use the appropriate features in your MySQL library to pass in the values as parameters to the query.\nThe number of columns in a table should hardly change as your program is developed. Maybe once every few months, at which point it's ra...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004347107_mysql_python.txt
Q: Printing during different times of week Welp, I'm a noob when it comes to Python. No doubt about it. Have done some VBS and VB so I have a bit of understanding. What I am tasked to do using Python seems easy: run an action only during these times: Mon: between 1:30 am and 7:30 am Tues – Fri: between 3:00 am 7:30 a...
Printing during different times of week
Welp, I'm a noob when it comes to Python. No doubt about it. Have done some VBS and VB so I have a bit of understanding. What I am tasked to do using Python seems easy: run an action only during these times: Mon: between 1:30 am and 7:30 am Tues – Fri: between 3:00 am 7:30 am Sat: between 1:00 am and 9:00 am and 5:00 p...
[ "Instead of using the time module you should try the datetime module. It's much easier for tasks like these.\nIf you use a fictional date (or replace the date in your checks) than you can do it like this:\n>>> x = datetime.datetime(1, 1, 1, 13, 37, 40)\n>>> a = datetime.datetime(1, 1, 1, 1, 30, 0)\n>>> b = datetime...
[ 2, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0004345541_datetime_python.txt
Q: How do I use the Python SDK for Google Appengine? I normally use Java development and the Google Eclipse plugin, which integrates GoogleAppEngine deploy capability. Now I have found a Python application with source code that I want to bring into Eclipse and deploy from Eclipse, but I don't even know if Eclipse sup...
How do I use the Python SDK for Google Appengine?
I normally use Java development and the Google Eclipse plugin, which integrates GoogleAppEngine deploy capability. Now I have found a Python application with source code that I want to bring into Eclipse and deploy from Eclipse, but I don't even know if Eclipse supports Python. What do I have to do to deploy the Python...
[ "\nDownload PyDev from its Eclipse update site.\nCreate a new PyDev Google App Engine Project, say using the 'Hello webapp world' template.\nSet the application in app.yaml to your GAE application ID.\nRight-click the src folder of your project and select Run As | PyDev:Google App Run.\nTest the application works a...
[ 4, 1, 1 ]
[]
[]
[ "eclipse_plugin", "google_app_engine", "python" ]
stackoverflow_0004347157_eclipse_plugin_google_app_engine_python.txt
Q: Jquery doesn't find element in selenium sel.add_script( sel.get_location(), "jquery.js") #here I get u'fd6c42bcc770ca9decc4f358df3688290a4257ad'` idOfResultWithSomeImage=sel.get_eval("window.jQuery('#result').find('img').filter('[alt=SeleImage]').eq(0).parents('form:first').find('a').eq(1).attr('id')"...
Jquery doesn't find element in selenium
sel.add_script( sel.get_location(), "jquery.js") #here I get u'fd6c42bcc770ca9decc4f358df3688290a4257ad'` idOfResultWithSomeImage=sel.get_eval("window.jQuery('#result').find('img').filter('[alt=SeleImage]').eq(0).parents('form:first').find('a').eq(1).attr('id')")` #here I get u"window.jQuery('#fd6c42b...
[ "If you want to use a CSS/jQuery style selector in Selenium, I think you have to go all the way to using the CSS selector. In other words, you need something like:\npathOfButton = \"css=#\" + idOfResultWithSomeImage + \" ~ button\"\nif (!sel.is_element_present(pathOfButton))\n pathOfButton = \"css=button ~ #\" ...
[ 0 ]
[]
[]
[ "c#", "jquery", "python", "selenium", "selenium_rc" ]
stackoverflow_0004347346_c#_jquery_python_selenium_selenium_rc.txt
Q: Is there a way to look up the parent object in couchdbkit? I have run into this a lot in couchdbkit - as far as I can tell the child objects under a couchdbkit Document object have no reference back to the parent. I hope I am wrong though: class Child(DocumentSchema): name = StringProperty() def parent(sel...
Is there a way to look up the parent object in couchdbkit?
I have run into this a lot in couchdbkit - as far as I can tell the child objects under a couchdbkit Document object have no reference back to the parent. I hope I am wrong though: class Child(DocumentSchema): name = StringProperty() def parent(self): # How do I get a reference to the parent object her...
[ "I just chatted with the author of couchdbkit and apparently what I am trying to do is not supported now.\n", "What I sometimes do is write a get_child or get_children method on parent that sets a _parent attribute before returning. ie:\nclass Parent(Document):\n something = BooleanProperty()\n children = S...
[ 1, 1 ]
[]
[]
[ "couchdb", "couchdbkit", "python" ]
stackoverflow_0004294281_couchdb_couchdbkit_python.txt
Q: How to redirect python interpreter output and catch it in a string in C++ program? i am using python C++ API to run python commands from C++ program. I want to catch all the python output to a string, I've managed by the following redirection, to catch pythons stdout and stderr output: #python script , redirect_py...
How to redirect python interpreter output and catch it in a string in C++ program?
i am using python C++ API to run python commands from C++ program. I want to catch all the python output to a string, I've managed by the following redirection, to catch pythons stdout and stderr output: #python script , redirect_python_stdout_stderr.py class CatchOutput: def __init__(self): self.value = ''...
[ "The Python interpreter will run inside your C++ process, so all its output will go to the stderr and stdout of the C++ program itself. How to capture this output is described in this answer. Note that with this approach you won't need to capture the output in the Python script any more -- just let it go to stdou...
[ 4 ]
[]
[]
[ "c++", "python", "python_c_api", "python_embedding", "redirect" ]
stackoverflow_0004347983_c++_python_python_c_api_python_embedding_redirect.txt
Q: Passing a variable to a method in a class I'm new to using classes and I'm trying to pass a variable to one of the methods inside of my class. How do I do it? Here's an example of what I'm trying to accomplish: class a_class(): def a_method(txt): print txt instance = a_class() instance.a_method('he...
Passing a variable to a method in a class
I'm new to using classes and I'm trying to pass a variable to one of the methods inside of my class. How do I do it? Here's an example of what I'm trying to accomplish: class a_class(): def a_method(txt): print txt instance = a_class() instance.a_method('hello world!) P.S. I don't understand the whole ...
[ "When writing an instance method for a class in Python- which looks exactly like what you've just coded up- you can't avoid using self. The first parameter to an instance method in Python is always the object the method is being called on. self is not a reserved word in Python- just the traditional name for that fi...
[ 5, 4, 2, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004348283_class_python.txt
Q: ctypes, pyrex, swig, or cython for this problem? I have about 20 simple C++ classes that represent various probability distributions. I would like to make these available in Python. What is the easiest way to do this? I don't mind having a program automatically generate wrappers, but I don't want to retype the ...
ctypes, pyrex, swig, or cython for this problem?
I have about 20 simple C++ classes that represent various probability distributions. I would like to make these available in Python. What is the easiest way to do this? I don't mind having a program automatically generate wrappers, but I don't want to retype the classes. Also, some of my classes use Boost uBLAS libr...
[ "Actually, none of those.\nI use Boost.Python extensively to operate a C++ library from Python.\nThere are easy converters for uBlas and NumPy, if you don't mind copying values around. If you do, you can try to get PyUblas to work, which enables memory sharing between NumPy and uBlas.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "cython", "pyrex", "python", "swig" ]
stackoverflow_0004348477_ctypes_cython_pyrex_python_swig.txt
Q: Comparing output to a list/array I consider myself a very beginner at python(and programming in general!), but I am working though "learn python the hard way" by Zed A Shaw and slowing picking things up. I'm writing a little script to check if the live mx records of a domain are to be as expected and have not been...
Comparing output to a list/array
I consider myself a very beginner at python(and programming in general!), but I am working though "learn python the hard way" by Zed A Shaw and slowing picking things up. I'm writing a little script to check if the live mx records of a domain are to be as expected and have not been changed (long story) and so far I hav...
[ "You mean:\nx.to_text() in {'cluster1a.eu.messagelabs.com', 'cluster1.eu.messagelabs.com'}\n\n?\n", "The results are returned in the format 'XX dns_entry', so you can do:\nimport dns.resolver\ndomain = 'bbc.co.uk'\nresults = []\nfor x in dns.resolver.query(domain,'MX',):\n results.append(x.to_text().split(' ')...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "arrays", "list", "mx_record", "python" ]
stackoverflow_0004347554_arrays_list_mx_record_python.txt
Q: How do I add form-level validation to a Flatland Form class? I have a flatland form for a proxy website that looks something like this: class doSomethingForm(Form): '''Do an action with account credentials''' username = String.using(default='', validators=[Present(), UsernameFormat()]) password = String....
How do I add form-level validation to a Flatland Form class?
I have a flatland form for a proxy website that looks something like this: class doSomethingForm(Form): '''Do an action with account credentials''' username = String.using(default='', validators=[Present(), UsernameFormat()]) password = String.using(default='', validators=[Present(), PasswordFormat()]) ...
[ "After reading a bit of the docs I would assume you can simply do your_form.validate().\nThe Form class inherits the Dict class so the way you can do validation is identical to how the container-level validation normally works.\nDisclaimer: until your question I've never heard of \"flatland\" so I can be really off...
[ 1, 1 ]
[]
[]
[ "forms", "python" ]
stackoverflow_0004340727_forms_python.txt
Q: file compression without using built in functions python programmers, I'm am new to python ,I read that we have built in functions to achieve file compression in python . I just wanted to know if a file compression can be done without using these built in functions (maybe a longer code perhaps) .I wanted to unders...
file compression without using built in functions
python programmers, I'm am new to python ,I read that we have built in functions to achieve file compression in python . I just wanted to know if a file compression can be done without using these built in functions (maybe a longer code perhaps) .I wanted to understand the working of these built in functions(how they a...
[ "Well there are lots of different ways to compress data, but it can be quite a task to undertake. One area you might want to research is Huffman Coding which can help with compression, especially for plain text. The reason I point it out is that it is more approachable than other compression techniques, and can be ...
[ 2, 1 ]
[]
[]
[ "compression", "file", "python" ]
stackoverflow_0004348660_compression_file_python.txt
Q: All possible combinations of numbers of length 5 in a 4X4 matrix i have a matrix 1 9 2 3 5 0 0 6 8 4 4 8 2 3 7 8 I need to find all possible combinations of numbers of length 5. constraints: Starting form a any position in the matrix you can only move to your next immediate neighbor i.e if u start form say (0,0...
All possible combinations of numbers of length 5 in a 4X4 matrix
i have a matrix 1 9 2 3 5 0 0 6 8 4 4 8 2 3 7 8 I need to find all possible combinations of numbers of length 5. constraints: Starting form a any position in the matrix you can only move to your next immediate neighbor i.e if u start form say (0,0) your neighbor must be (0,1),(1,1),(1,0) and if you pick a position t...
[ "Here is a solution in Scala (for the 5x5 version with 9 digits, starting from the middle) (with an ideone.com demo). It took 5 seconds to execute on my (fairly slow) computer.\nobject Main {\n\n val matrix = List(List(\"1\", \"9\", \"2\", \"3\", \"1\"),\n List(\"5\", \"0\", \"0\", \"6\", \"...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "combinatorics", "python", "recursion" ]
stackoverflow_0004339503_combinatorics_python_recursion.txt
Q: How to create tables in sqlite 3? I just downloaded sqlite3.exe. It opens up as a command prompt. I created a table test & inserted a few entries in it. I used .backup test just in case. After I exit the program using .exit and reopened it I don't find the table listed under .tables nor can I run any query on it. ...
How to create tables in sqlite 3?
I just downloaded sqlite3.exe. It opens up as a command prompt. I created a table test & inserted a few entries in it. I used .backup test just in case. After I exit the program using .exit and reopened it I don't find the table listed under .tables nor can I run any query on it. I need to quickly run an open source py...
[ "sqlite is built in to Python.\nYou should be able to access your table like this:\nimport sqlite3\nconn = sqlite3.connect('/path/to/my.db')\ncurs = conn.cursor()\ncurs.execute(\"SELECT a_column FROM my_table;\").fetchone()\ncurs.close()\nconn.close()\n\nYou can execute your DDL statements from Python as well.\nMak...
[ 4, 1, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004348658_python_sqlite.txt
Q: Subprocess Variables 1 import subprocess 2 raw = raw_input("Filename:").lower() 3 ip = raw_input("Host:").lower() 4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True) So this is my script. I everything works besides one key objective, using the raw input. It allows me to input anyt...
Subprocess Variables
1 import subprocess 2 raw = raw_input("Filename:").lower() 3 ip = raw_input("Host:").lower() 4 cmd = subprocess.call("tcpdump -c5 -vvv -w" + " raw " + " ip ",shell=True) So this is my script. I everything works besides one key objective, using the raw input. It allows me to input anything i want, but when it g...
[ "Don't use shell=True. That should be False.\nYou are making subtle mistakes with the input. Specifically, if you have two strings:\n>>> s1 = 'Hello'\n>>> s2 = 'Hi'\n>>> s1 + s2\n'HelloHi'\n\nNotice, there is no space between Hello and Hi. So don't do this. (Your line 4)\nYou should do (the good way):\n>>> raw = ra...
[ 28, 24 ]
[]
[]
[ "python", "subprocess", "tcpdump" ]
stackoverflow_0004348524_python_subprocess_tcpdump.txt
Q: How to do "if-for" statement in python? With python, I would like to run a test over an entire list, and, if all the statements are true for each item in the list, take a certain action. Pseudo-code: If "test involving x" is true for every x in "list", then do "this". It seems like there should be a simple way to ...
How to do "if-for" statement in python?
With python, I would like to run a test over an entire list, and, if all the statements are true for each item in the list, take a certain action. Pseudo-code: If "test involving x" is true for every x in "list", then do "this". It seems like there should be a simple way to do this. What syntax should I use in python?...
[ "Use all(). It takes an iterable as an argument and return True if all entries evaluate to True. Example:\nif all((3, True, \"abc\")):\n print \"Yes!\"\n\nYou will probably need some kind of generator expression, like\nif all(x > 3 for x in lst):\n do_stuff()\n\n", ">>> x = [True, False, True, False]\n>>>...
[ 28, 6, 4, 3, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004348678_python.txt
Q: is Video tag in html a POST request or GET request? I am iusing in my html. I am trying to handle the request on server side using python BaseHTTPServer. I want to figure out how the request from video tag looks like??? A: It will be a simple GET request, just like any other resource embedded in an HTML docume...
is Video tag in html a POST request or GET request?
I am iusing in my html. I am trying to handle the request on server side using python BaseHTTPServer. I want to figure out how the request from video tag looks like???
[ "It will be a simple GET request, just like any other resource embedded in an HTML document.\nIf you really want to examine exactly what browsers send, then use something like Charles or the Net tab of Firebug.\n", "POST is usually reserved for form submissions because you are POSTing form information to the serv...
[ 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0004348707_html_python.txt
Q: Python Open Multiple URL Connections - urllib2 I'm trying to create a python script that will allow me to load up multiple connections similar to having multiple tabs open on a browser, more explicitly I have a code like this: https://github.com/eWizardII/SOC357-Twitter-Facebook-Project/blob/master/chuck.py Using ...
Python Open Multiple URL Connections - urllib2
I'm trying to create a python script that will allow me to load up multiple connections similar to having multiple tabs open on a browser, more explicitly I have a code like this: https://github.com/eWizardII/SOC357-Twitter-Facebook-Project/blob/master/chuck.py Using urlv, etc, I load up multiple connections to the API...
[ "Use the shell.\n#!/bin/bash\npython chuck.py \"request 1\" &\npython chuck.py \"request 2\" &\npython chuck.py \"request 3\" &\npython chuck.py \"request 4\" &\npython chuck.py \"request 5\" &\n\nThis will run 5 copies of your program. It will tie up as many cores and CPUs as it can. And -- bonus -- no programmi...
[ 4, 1, 0 ]
[]
[]
[ "connection", "facebook", "python", "twitter", "urllib2" ]
stackoverflow_0004348352_connection_facebook_python_twitter_urllib2.txt
Q: Selecting Datastore ID in Google App Engine? I'm trying to make a query that selects everything where the id is 6. The problem is that I cant seem to get it to work. This is what the code looks like at the moment: query = db.GqlQuery("SELECT * FROM Users WHERE id = 6") result = query.get() for resu...
Selecting Datastore ID in Google App Engine?
I'm trying to make a query that selects everything where the id is 6. The problem is that I cant seem to get it to work. This is what the code looks like at the moment: query = db.GqlQuery("SELECT * FROM Users WHERE id = 6") result = query.get() for result in query: self.response.out.write(resul...
[ "If you're using the id value assigned by the datastore, there can only be a single entity with a given id.\nHow about this instead:\nidNum = 6\n# handy function the datastore API provides...\nuser = Users.get_by_id(idNum)\nself.response.out.write(user.username)\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004348969_google_app_engine_google_cloud_datastore_python.txt
Q: Using imported modules in more than one file This question is a bit dumb but I have to know it. Is there any way to use imported modules inside other imported modules? I mean, if I do this: -main file- import os import othermodule othermodule.a() -othermodule- def a(): return os.path.join('/', 'example') #...
Using imported modules in more than one file
This question is a bit dumb but I have to know it. Is there any way to use imported modules inside other imported modules? I mean, if I do this: -main file- import os import othermodule othermodule.a() -othermodule- def a(): return os.path.join('/', 'example') # Without reimporting the os module The os module ...
[ "There's no need to do that, Python only loads modules once (unless you unload them).\nBut if you really have a situation in which a module can't access the standard library (care to explain???), you can simply access the os module within the main module (e.g. mainfile.os, modules are just variables when imported i...
[ 5, 3, 1 ]
[]
[]
[ "import", "module", "python", "reusability" ]
stackoverflow_0004349111_import_module_python_reusability.txt
Q: Is the W3C or any standards body working on a single standard for Entity Attribute ORM definitions? There are literally dozens of XML, YAML, JSON, and nested array based (that whole convention over configuration thang) standards for describing : Database tables, Classes, Maps between Tables and Classes, Constraint...
Is the W3C or any standards body working on a single standard for Entity Attribute ORM definitions?
There are literally dozens of XML, YAML, JSON, and nested array based (that whole convention over configuration thang) standards for describing : Database tables, Classes, Maps between Tables and Classes, Constraints, User Interface descriptions, Maps between Entities and User Interfaces, Rules for user Interfaces, etc...
[ "To answer the question: no; not that I am aware of.\nThis being said, XForms doesn't much to do with ORM. With XRX, it can be seen as the opposite of ORM, the goal being to avoid mapping, and the complexity it creates. If you use the same data structure (XML in the case of XRX) to hold data all the way, from your ...
[ 1 ]
[]
[]
[ ".net", "orm", "php", "python", "xforms" ]
stackoverflow_0004331894_.net_orm_php_python_xforms.txt
Q: Puppy Linux - import gtk throws error in Python I am using Linux version 2.6.24.16. I believe it is using Puppy Linux 4.2. I am actually using Puppy Arcade, which is a specialized branch. Their help file hints that it is 4.2, however. I am using Python 2.6.4 which I installed through a puppy package released here:...
Puppy Linux - import gtk throws error in Python
I am using Linux version 2.6.24.16. I believe it is using Puppy Linux 4.2. I am actually using Puppy Arcade, which is a specialized branch. Their help file hints that it is 4.2, however. I am using Python 2.6.4 which I installed through a puppy package released here: http://code.google.com/p/puppy-development/downloads...
[ "It looks like pygtk package you are trying to use is compiled against newer glib (and, possibly gtk+) libraries. Just from observation (I'm not puppy user) it looks like you've downloaded pygtk package for 4.3 (with possible newer runtime libraries).\n" ]
[ 1 ]
[]
[]
[ "gtk", "linux", "pygtk", "python" ]
stackoverflow_0004349024_gtk_linux_pygtk_python.txt
Q: Does Future work on App Engine? Does the Future library works on App Engine? If not, what is a good alternative library that does work on top of GAE? A: You cannot use threading on App Engine. See Are there any third-party libraries not supported by Google App Engine?, which includes the bullet point "Threading...
Does Future work on App Engine?
Does the Future library works on App Engine? If not, what is a good alternative library that does work on top of GAE?
[ "You cannot use threading on App Engine. See Are there any third-party libraries not supported by Google App Engine?, which includes the bullet point \"Threading is not available\".\nYou might be able to accomplish what you need to accomplish via the Task Queue api. See Python Threads (or their equivalent) on Goo...
[ 4 ]
[]
[]
[ "google_app_engine", "multithreading", "python" ]
stackoverflow_0004349511_google_app_engine_multithreading_python.txt
Q: Google App Engine redirection problem I'm trying to make a user verification script that redirects the user if the password and username cookies are empty or false. But no matter what I do it always sends the user to "/wrong2". It doesnt even bother checking the if. This is what the code looks like at the moment: ...
Google App Engine redirection problem
I'm trying to make a user verification script that redirects the user if the password and username cookies are empty or false. But no matter what I do it always sends the user to "/wrong2". It doesnt even bother checking the if. This is what the code looks like at the moment: dictionary = self.request.str_cooki...
[ "You're using hasattr to check to see if a dict contains a particular key, but you should be using the in operator instead. The hasattr function just checks to see if an object has a particular attribute.\nSo, you could instead write:\nif 'username' in self.request.cookies and 'password' in self.request.cookies:\n...
[ 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004349776_google_app_engine_google_cloud_datastore_python.txt
Q: Cron Jobs, Task Queue or Deferred Tasks? In Google App Engine, for a task like scanning some RSS feeds and adding new entries from the feed to the datastore every 10-15 seconds, should I use Cron Jobs, Task Queue or Deferred Tasks? I'm really confused. A: Invoke a cron job every 1 minute, which would get the RSS...
Cron Jobs, Task Queue or Deferred Tasks?
In Google App Engine, for a task like scanning some RSS feeds and adding new entries from the feed to the datastore every 10-15 seconds, should I use Cron Jobs, Task Queue or Deferred Tasks? I'm really confused.
[ "Invoke a cron job every 1 minute, which would get the RSS and sleep for 15 seconds four times. You can locks to prevent overlapping (although the database insertion provides some measure of concurrency control). \nPython-like pseudo code:\nif cant_get_lock:\n exit\nelse:\nfor i in (1,2,3,4):\n get RSS\n s...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python", "task" ]
stackoverflow_0004349945_google_app_engine_python_task.txt
Q: Difference between Systems programming language and Application programming languages What are the differences between a systems programming language and Application programming language? A: A few factors should in my opinon come into consideration In a system programming language you must be able to reach low-...
Difference between Systems programming language and Application programming languages
What are the differences between a systems programming language and Application programming language?
[ "A few factors should in my opinon come into consideration\n\nIn a system programming language you must be able to reach low-level stuff, getting close to the real hardware world. In an application language instead there is a sort of \"virtual world\" (hopefully nicer and easier to interact with) that has been desi...
[ 16, 9, 5, 2, 2 ]
[]
[]
[ "c#", "java", "perl", "programming_languages", "python" ]
stackoverflow_0004343014_c#_java_perl_programming_languages_python.txt
Q: C# scripting (python) Does a way to interoperate in C# and Python exist? I know and have used IronPython (obviously, it became really sweet with the dynamic keyword), and it allows to interpret Python scripts inside a C# application. But I want this Python script to access C# classes and methods. I know, for examp...
C# scripting (python)
Does a way to interoperate in C# and Python exist? I know and have used IronPython (obviously, it became really sweet with the dynamic keyword), and it allows to interpret Python scripts inside a C# application. But I want this Python script to access C# classes and methods. I know, for example, this can be implemented...
[ "Well you could compile your C# code to a DLL using csc and use ctypes to access the DLL from your script but if you can use IronPython, then that's the route I'd go with. \nUsing C# modules from IronPython is as simple as a call to clr.AddReference. For example, here's a script to make your computer talk to you (t...
[ 6 ]
[]
[]
[ "c#", "python", "scripting" ]
stackoverflow_0004350191_c#_python_scripting.txt
Q: How to display an image from blobstore? I am trying to understand the documentation Using the Images Python API and I am confused about how to get the key and display the avatar. Documentation says that the Image handler will serve the image off the /img path. I am confused about what this Image handler does. I co...
How to display an image from blobstore?
I am trying to understand the documentation Using the Images Python API and I am confused about how to get the key and display the avatar. Documentation says that the Image handler will serve the image off the /img path. I am confused about what this Image handler does. I comment below how understand it; please correct...
[ "\n\"img_id\" comes from the GET part of the url (something like \"www.example.com/img?img_id=12312\"). The engine assigns a new unique key for every model in the database.\ngreeting.avatar is the avatar property of the model with the key img_id. So, in some sense, you can think of it like img_id.avatar, although t...
[ 3 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0004350193_blobstore_google_app_engine_python.txt
Q: urllib & cookielib - downloading images this is what i got so far: import urllib, urllib2, cookielib jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) login_data = urllib.urlencode({'User' : 'c1300', 'Pass' : '5800009'}) opener.open('http://www.sis.com/default.asp', login...
urllib & cookielib - downloading images
this is what i got so far: import urllib, urllib2, cookielib jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) login_data = urllib.urlencode({'User' : 'c1300', 'Pass' : '5800009'}) opener.open('http://www.sis.com/default.asp', login_data) i got this code from somewhere around...
[ "You're going to need to obtain a cookie from the site by logging in, which means interacting with the login form, storing the cookie you get, and sending it back to the webserver when you attempt to get the image. Instead, consider Mechanize: http://wwwsearch.sourceforge.net/mechanize/. This library abstracts out ...
[ 5 ]
[]
[]
[ "cookielib", "python", "urllib", "urllib2" ]
stackoverflow_0004350063_cookielib_python_urllib_urllib2.txt
Q: Regarding running a script from another Is there a way that I can run a script from another while getting output as readily as I get by executing it by itself. For example: I use the os.popen3 command to execute abc.py, but I am unable to get output from abc.py as readily as I would with doing python abc.py; it se...
Regarding running a script from another
Is there a way that I can run a script from another while getting output as readily as I get by executing it by itself. For example: I use the os.popen3 command to execute abc.py, but I am unable to get output from abc.py as readily as I would with doing python abc.py; it seems that I need to wait for os.popen3 command...
[ "import subprocess\npro = subprocess.Popen('abc.py')\n\nIs a much better way of fiddling with another scripts ins, outs, and errors.\n", "You mentioned PyGtk but you can give a try to PyQt and particularly QProcess class wich has some nice signals like :\n\nreadyReadStandardError\nreadyReadStandardOutput\n\nLook ...
[ 2, 0, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004333406_pygtk_python.txt
Q: Do overridden methods inherit decorators in python? Just like the title says, do overridden methods inherit decorators? class A: @memoized def fun(self, arg): return None class B(A): def fun(self, arg): #computations return something so does B.fun() maintain the decorator? A:...
Do overridden methods inherit decorators in python?
Just like the title says, do overridden methods inherit decorators? class A: @memoized def fun(self, arg): return None class B(A): def fun(self, arg): #computations return something so does B.fun() maintain the decorator?
[ "Think about it this way\nclass A(object):\n def fun(self, arg):\n return None\n fun = memoized(fun)\n\n", "No. It's a completely different function. But you can try that for yourself with a dummy decorator.\n", "No, it doesn't.\n" ]
[ 21, 7, 1 ]
[]
[]
[ "decorator", "inheritance", "python" ]
stackoverflow_0004350260_decorator_inheritance_python.txt
Q: does python BaseHttpServer support Html5? I am using BaseHttpServer of Python-2.6.6. I could not make it work with tag. Does Python-2.6 really support HTML5 ? This could be more helpful: Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/SocketSer...
does python BaseHttpServer support Html5?
I am using BaseHttpServer of Python-2.6.6. I could not make it work with tag. Does Python-2.6 really support HTML5 ? This could be more helpful: Traceback (most recent call last): File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/SocketServer.py", line 283, in _handle_request_noblock ...
[ "HTML5 support lives at the browser level primarily, not at the language level. So yes, Python does support HTML5 implicitly.\n", "It seems you have misdiagnosed your problem. HTML5 is entirely browser side. The broken pipe is indicative of something else.\n" ]
[ 3, 0 ]
[]
[]
[ "html", "http", "python" ]
stackoverflow_0004350074_html_http_python.txt
Q: Tkinter Integral Symbol I want to be able to pack an integral symbol into a label like this: result = 5 Label(root,text='INTEGRAL x: ' + result).pack() Is there a way to get that squiggly S in there? A: The integral symbol is U+222B in Unicode. I'm leaving in around 30 seconds (or so I was told two minutes ago)...
Tkinter Integral Symbol
I want to be able to pack an integral symbol into a label like this: result = 5 Label(root,text='INTEGRAL x: ' + result).pack() Is there a way to get that squiggly S in there?
[ "The integral symbol is U+222B in Unicode. I'm leaving in around 30 seconds (or so I was told two minutes ago), so I can't test it right now, but it should display just fine.\nCheers.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004350366_python_tkinter.txt
Q: Is it possible to change the title of a notification? Is it possible to change the title of a pynotify.Notification? If so what is the method call to use? Also, it is possible to merge notifications using set_hint_string('append', ''). Is it possible to change a title and keep them merged. I want something like th...
Is it possible to change the title of a notification?
Is it possible to change the title of a pynotify.Notification? If so what is the method call to use? Also, it is possible to merge notifications using set_hint_string('append', ''). Is it possible to change a title and keep them merged. I want something like the following (not real code, just a description of the effec...
[ "Perhaps use the update method:\nimport pynotify\nimport time \n\npynotify.init('app name')\nn=pynotify.Notification(\"title\",\"Something is happening\")\nn.show()\ntime.sleep(2)\nn.update(\"new title\",\"2 things are happening\")\nn.show()\n\n" ]
[ 1 ]
[]
[]
[ "notifications", "pynotify", "python" ]
stackoverflow_0004350393_notifications_pynotify_python.txt
Q: Python: division error Heres my method: def geometricSum(commonRatio, firstTerm, lastTerm): return ((firstTerm - lastTerm) * commonRatio) / (1 - commonRatio) Interpreter testing: >>> geometricSum(1.0,1.0,100.0) Traceback (most recent call last): File "<interactive input>", line 1, in <module> ...
Python: division error
Heres my method: def geometricSum(commonRatio, firstTerm, lastTerm): return ((firstTerm - lastTerm) * commonRatio) / (1 - commonRatio) Interpreter testing: >>> geometricSum(1.0,1.0,100.0) Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "F:\PortablePytho...
[ "You're dividing by zero. commonRatio is 1.0 so the denominator is 1-1.0 = 0.\n", "Haha man, I'm sorry to be blunt, but this has nothing to do with doubles. You are DIVIDING BY ZERO! You could have blown up the universe if it wasn't for python's exception handling!\n", "1 - commonRatio = 1 - 1 = 0.\n\nDivision ...
[ 10, 9, 7, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004350406_python.txt
Q: How to put arbitrary widgets into a gtk.Menu? How can any gtk.Widget (eg. a progress bar) be put into a gtk.Menu as one of the menu items? A: Quoting from the PyGTK documentation: The gtk.MenuItem and its derived widget subclasses are the only valid children of menus. So the answer is: You can't. But: As...
How to put arbitrary widgets into a gtk.Menu?
How can any gtk.Widget (eg. a progress bar) be put into a gtk.Menu as one of the menu items?
[ "Quoting from the PyGTK documentation:\n\nThe gtk.MenuItem and its derived\n widget subclasses are the only valid\n children of menus.\n\nSo the answer is: You can't. But:\n\nAs a gtk.MenuItem is a subclass of gtk.Bin it can hold any valid child widget.\n\nIf you create a MenuItem without a label:\nitem = gtk.Me...
[ 7 ]
[]
[]
[ "gtk", "menu", "pygtk", "python" ]
stackoverflow_0004350470_gtk_menu_pygtk_python.txt
Q: How is a Python project set up? I am doing some heavy commandline stuff (not really web based) and am new to Python, so I was wondering how to set up my files/folders/etc. Are there "header" files where I can keep all the DB connection stuff? How/where do I define classes and objects? A: Just to give you an exam...
How is a Python project set up?
I am doing some heavy commandline stuff (not really web based) and am new to Python, so I was wondering how to set up my files/folders/etc. Are there "header" files where I can keep all the DB connection stuff? How/where do I define classes and objects?
[ "Just to give you an example of a typical Python module's source, here's something with some explanation. This is a file named \"Dims.py\". This is not the whole file, just some parts to give an idea what's going on.\n#!/usr/bin/env python\n\nThis is the standard first line telling the shell how to execute this f...
[ 8, 3, 0, 0, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004349714_class_python.txt
Q: On a fresh install of ActivePython-2.6, pip is giving an import error I installed Cent OS on a virtual machine, and it comes with Python 2.4 out of the box. I needed to install Python 2.6, so I installed a separate python binary from ActivePython which installed itself in a different directory. When I run pip (/op...
On a fresh install of ActivePython-2.6, pip is giving an import error
I installed Cent OS on a virtual machine, and it comes with Python 2.4 out of the box. I needed to install Python 2.6, so I installed a separate python binary from ActivePython which installed itself in a different directory. When I run pip (/opt/ActivePython-2.6/bin/pip) I get this error: # pip Traceback (most recent ...
[ "Find _md5.so in /opt/ActivePython-2.6 and run ldd on it. Yeah.\nInstall EPEL, install python26 via yum, have fun.\n" ]
[ 0 ]
[]
[]
[ "activepython", "centos", "python" ]
stackoverflow_0004350416_activepython_centos_python.txt
Q: Other uses of the __name__ attribute I'm learning Python by reading Dive Into Python online, and in Chapter 2 I see that you can use the __name__ attribute for testing purposes, so I was wondering, does anyone knows about other uses for this attribute? Thanks A: I once had a decorator for a command-line script f...
Other uses of the __name__ attribute
I'm learning Python by reading Dive Into Python online, and in Chapter 2 I see that you can use the __name__ attribute for testing purposes, so I was wondering, does anyone knows about other uses for this attribute? Thanks
[ "I once had a decorator for a command-line script file.\nThe decorator was used like this:\n@command\ndef someFunc():\n # code goes here\n\nThe decorator was doing something like this:\ncommands = {}\ndef command(func)\n commands[func.__name__] = func\n return func\n\nAnd then I could do something like thi...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004350592_python.txt
Q: Code sharing between small student group I'm currently in college, and we work in groups of three to create small python projects on a weekly basis. We code with Eclipse and PyDev but we've got a problem when it comes to sharing our work. We end up sending an infinite stream of emails with compressed projects. Wha...
Code sharing between small student group
I'm currently in college, and we work in groups of three to create small python projects on a weekly basis. We code with Eclipse and PyDev but we've got a problem when it comes to sharing our work. We end up sending an infinite stream of emails with compressed projects. What we need is a way to keep the source code upd...
[ "Use Git and Github. This way your code is in version control ( which is a good practice) and it can be shared with other people in your project through github. ( github was built with good git integration). \n", "I'd suggest using a version control system.\nGit might be good for you - it doesn't require a centra...
[ 6, 3, 2, 1 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0004350627_eclipse_python.txt
Q: Python JIRA SOAPpy annoying redirect on findIssue I am trying to do WSDL SOAP connection to our JIRA server using SOAPpy (Python SOAP Library). All seems to be fine except when I try finding specific issues. Through the web browser looking up the bug ID actually redirects to a bug (with a different ID), however it...
Python JIRA SOAPpy annoying redirect on findIssue
I am trying to do WSDL SOAP connection to our JIRA server using SOAPpy (Python SOAP Library). All seems to be fine except when I try finding specific issues. Through the web browser looking up the bug ID actually redirects to a bug (with a different ID), however it is the bug in question just moved to a different proje...
[ "Yes, there's an existing bug on this I've seen. Use the JIRA issue id instead of the key to locate it, as a workaround.\n" ]
[ 2 ]
[]
[]
[ "jira", "python", "soap", "wsdl" ]
stackoverflow_0004320135_jira_python_soap_wsdl.txt
Q: Open file and read to find first instance of number. Python Im stuck on a problem for an assignment, I need to write a program that opens a file on my computer, and scans that file for the first instance of a number. Once it is found it will return The first number in , filenm is x otherwise it will say there is ...
Open file and read to find first instance of number. Python
Im stuck on a problem for an assignment, I need to write a program that opens a file on my computer, and scans that file for the first instance of a number. Once it is found it will return The first number in , filenm is x otherwise it will say there is no number in filenm. My code so far is below: When i run it no ma...
[ "That's all you need:\nimport re\n\nwith open(\"filename\") as f:\n for line in f:\n s=re.search(r'\\d+',line)\n if s:\n print(s.group())\n break\n\n", "\nopen the file;\nread it in a loop char-by-char;\ncheck if the char is digit, print whatever you want;\nit means there ar...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004349056_python.txt
Q: converting white space in python files? I have some tab formatted code in python and I have some space formatted code in python. Integrating the code in a pain... my editor wants to work in tabs or spaces, but not both. Is there a command line function in linux or, well, anything which will convert python code for...
converting white space in python files?
I have some tab formatted code in python and I have some space formatted code in python. Integrating the code in a pain... my editor wants to work in tabs or spaces, but not both. Is there a command line function in linux or, well, anything which will convert python code formatting one way or the other?
[ "reindent.py is a nifty utility script which converts any python .py file into one using 4-space indents and no tabs. \nThis is useful for \"normalizing\" code from disparate sources, assuming you're willing to settle on the 4-space standard. (Or, if you want tabs, you could run reindent.py followed by the unix une...
[ 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004350879_python.txt
Q: How to use Images Python API correctly to display an avatar with user comments? This is a follow up question to my previous question. I am trying to upload and display an image as an avatar following the sample app here. This is the code I am using: In upload.py I have: from google.appengine.api import images cla...
How to use Images Python API correctly to display an avatar with user comments?
This is a follow up question to my previous question. I am trying to upload and display an image as an avatar following the sample app here. This is the code I am using: In upload.py I have: from google.appengine.api import images class Upload(webapp.RequestHandler): def get(self): self.response.out.write(""" ...
[ "In the log, you're seeing different image IDs because you're requesting up to 10 user objects from the Datastore, and the Datastore query is looking for the users regardless of whether or not they have an image stored (maybe you made 8 User objects in the course of testing).\nAs to why the avatars aren't saving:\n...
[ 1 ]
[]
[]
[ "blobstore", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004351375_blobstore_google_app_engine_google_cloud_datastore_python.txt
Q: Problem logging errors with Python's logging module I'm logging an error with python's logging module. I made a logger object inside my class, as follows: self.my_logger = logging.getLogger('my_logger') self.my_logger.setLevel(logging.ERROR) when I try to log an error later in the code, as: self.my_logger.error(...
Problem logging errors with Python's logging module
I'm logging an error with python's logging module. I made a logger object inside my class, as follows: self.my_logger = logging.getLogger('my_logger') self.my_logger.setLevel(logging.ERROR) when I try to log an error later in the code, as: self.my_logger.error("My error") then I get the error: AttributeError: FileHa...
[ "Check that you haven't defined any modules whose names clash with standard ones. The slightly modified script below runs on my system without error. Try it on yours and if it works, double check that you are not redefining any classes with the same names.\nimport logging\nimport os\nimport time\n\nclass SomeClass:...
[ 8 ]
[]
[]
[ "error_handling", "error_logging", "logging", "python" ]
stackoverflow_0004347382_error_handling_error_logging_logging_python.txt
Q: Python: Class design - List Transformations (critique my code) I have been thinking about a class which could be useful for list transformations. Here is my current implementation: class ListTransform(object): """Specs: stores original list + transformations. Transformations are stored in a list. Every...
Python: Class design - List Transformations (critique my code)
I have been thinking about a class which could be useful for list transformations. Here is my current implementation: class ListTransform(object): """Specs: stores original list + transformations. Transformations are stored in a list. Every transformation is a func call, with one parameter, transformati...
[ "Do not use an empty list as default argument. Use None and test for it:\ndef some_method(self, arg=None):\n if arg is None:\n arg = []\n do_your_thing_with(arg)\n\nI's a well known Python's beginner pitfall.\n", "Having a general scope and not a particular use case in mind, I would look at this in a...
[ 2, 2, 0 ]
[]
[]
[ "class_design", "python" ]
stackoverflow_0004348939_class_design_python.txt
Q: Is there a good python library that can turn numbers into their respective "symbols"? 0 = 0 1 = 1 ... 9 = 9 10 = a 11 = b ... 35 = z 36 = A 37 = B ... 60 = Z 61 = 10 62 = 11 ... 70 = 19 71 = 1a 72 = 1b I don't know what this is called. Base something? All I want is a function that can convert the numbers into th...
Is there a good python library that can turn numbers into their respective "symbols"?
0 = 0 1 = 1 ... 9 = 9 10 = a 11 = b ... 35 = z 36 = A 37 = B ... 60 = Z 61 = 10 62 = 11 ... 70 = 19 71 = 1a 72 = 1b I don't know what this is called. Base something? All I want is a function that can convert the numbers into these, and these back to numbers. Is there an easy function that can do this?
[ ">>> int(\"a\", 36)\n10\n>>> int(\"z\", 36)\n35\n>>> int(\"10\", 36)\n36\n\nThe other direction is more complicated, but try this ActiveState recipe.\nNormally base conversions make no distinction between cases. I'm not sure how to completely extend this to make that distinction, but the recipe should give you a s...
[ 4, 2 ]
[]
[]
[ "base", "computer_science", "int", "numbers", "python" ]
stackoverflow_0004351467_base_computer_science_int_numbers_python.txt
Q: Python: Specify end-of-line format for reading files I'm writing a Python script which processes a text file. I expect to process files generated from different people, working under different operating systems. Is there a nice way to figure out which OS created the text file, and specify the end-of-line conventio...
Python: Specify end-of-line format for reading files
I'm writing a Python script which processes a text file. I expect to process files generated from different people, working under different operating systems. Is there a nice way to figure out which OS created the text file, and specify the end-of-line convention to make parsing line-by-line trivial?
[ "Use universal newline mode when opening the file.\nwith open('input.txt', 'rU') as fp:\n for line in fp:\n print line\n\n", "splitlines() handles various line terminators:\n>>> 'foo\\nbar'.splitlines()\n['foo', 'bar']\n>>> 'foo\\rbar'.splitlines()\n['foo', 'bar']\n>>> 'foo\\r\\nbar'.splitlines()\n['foo', 'ba...
[ 3, 2, 1, 1 ]
[]
[]
[ "end_of_line", "file_io", "python" ]
stackoverflow_0004351492_end_of_line_file_io_python.txt
Q: Can I write this as a two-level list comprehension? I've got this bit: for line in entireResult.split('\n'): print line.split(',')[0] ... and I feel like it can be list-comprehended, but I'm a bit too Friday-nighted. I tried something like: [for l[0] in line.split(',') for line in entireResult('\n')] but tha...
Can I write this as a two-level list comprehension?
I've got this bit: for line in entireResult.split('\n'): print line.split(',')[0] ... and I feel like it can be list-comprehended, but I'm a bit too Friday-nighted. I tried something like: [for l[0] in line.split(',') for line in entireResult('\n')] but that didn't fly (line not defined). Is there a way to do thi...
[ "You only have one loop.\n[line.split(',')[0] for line in entireResult.split('\\n')]\n\nOf course, you should do it as a generator if possible.\nprint '\\n'.join(line.split(',')[0] for line in entireResult.split('\\n'))\n\n" ]
[ 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004352070_list_comprehension_python.txt
Q: Python Twisted sendLine() No not you again. Well anyway I've been struggling with this for quite some time. So basically I have my twisted application and now I'm writing a PyQt interface for it. There's only one thing I haven't been able to bridge between the Twisted script and the new interface yet. That's when ...
Python Twisted sendLine()
No not you again. Well anyway I've been struggling with this for quite some time. So basically I have my twisted application and now I'm writing a PyQt interface for it. There's only one thing I haven't been able to bridge between the Twisted script and the new interface yet. That's when a button is being pressed get T...
[ "You can't just instantiate Twisted() and then use it; it's a Protocol, and Protocols must be instantiated via a Factory, in response to either connecting a client or accepting an incoming connection as a server. The error that you're seeing is telling you that Twisted's transport doesn't exist at the point where ...
[ 2 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0004351537_python_twisted.txt
Q: Can someone help me on why this python script won't run? import numbers class base62(numbers.Number): digits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def __init__(self,value): if isinstance(value,int): self.value=value if value==0: se...
Can someone help me on why this python script won't run?
import numbers class base62(numbers.Number): digits='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' def __init__(self,value): if isinstance(value,int): self.value=value if value==0: self.string='0' else: self.string=''...
[ "base62 appears to be the name of both your module and your function inside that module. Try:\n>>> import base62\n>>> b = base62.base62(3)\n\n", "Read the error message:\nTypeError: 'module' object is not callable\nTypeError means there was an Error because something was of the wrong Type. The thing in question i...
[ 3, 2 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0004352311_debugging_python.txt
Q: Using selfmade functions in Google App Engine I'm trying to make a function that checks if the user is logged in. I've placed the function outside of the mainpage class and it gives no errors until I try to use it insie the def get(self) within the MainPage class. The function looks like this: def LoginCheck(): us...
Using selfmade functions in Google App Engine
I'm trying to make a function that checks if the user is logged in. I've placed the function outside of the mainpage class and it gives no errors until I try to use it insie the def get(self) within the MainPage class. The function looks like this: def LoginCheck(): username = self.request.cookies.get('username') pass...
[ "You'll have to add \"self\" to your function definition. See section 9.3.2 of python's tutorial.\ndef LoginCheck(self):\n username = self.request.cookies.get('username') \n password = self.request.cookies.get('password')\n if username and password:\n checkq = db.GqlQuery(\"SELECT * FROM Users WHERE...
[ 5 ]
[]
[]
[ "function", "google_app_engine", "python" ]
stackoverflow_0004352503_function_google_app_engine_python.txt
Q: sgml parsing in python3.1 I was trying to port feedparser over to Python3.1 and I realized that sgmllib had been deprecated from Python2.7 upward and subsequently removed. Which alternatives would you suggest I use in Python3.1 to perform analogous tasks? A: use lxml, it is very efficient as it is written in c, ...
sgml parsing in python3.1
I was trying to port feedparser over to Python3.1 and I realized that sgmllib had been deprecated from Python2.7 upward and subsequently removed. Which alternatives would you suggest I use in Python3.1 to perform analogous tasks?
[ "use lxml, it is very efficient as it is written in c, another popular HTML parser is there BeautifulSoup but again it is based on sgmllib so i would recommend that you should go for lxml.\n" ]
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004352320_python_python_3.x.txt
Q: Anyone know this Python data structure? The Python class has six requirements as listed below. Only bold terms are to be read as requirements. Close to O(1) performance for as many of the following four operations. Maintaining sorted order while inserting an object into the container. Ability to peek at last valu...
Anyone know this Python data structure?
The Python class has six requirements as listed below. Only bold terms are to be read as requirements. Close to O(1) performance for as many of the following four operations. Maintaining sorted order while inserting an object into the container. Ability to peek at last value (the largest value) contained in the objec...
[ "Your requirements seem to be:\n\nO(1) pop from each end \nEfficient len\nSorted order\nPeek at last value\n\nfor which you can use a deque with a custom insert method which rotates the deque, appends to one end, and unrotates.\n>>> from collections import deque\n>>> import bisect\n>>> class FunkyDeque(deque):\n......
[ 12, 9, 2 ]
[]
[]
[ "deque", "insert", "performance", "python", "sorting" ]
stackoverflow_0004098179_deque_insert_performance_python_sorting.txt
Q: Google App Engine HTTP information being printed somehow I'm just wanting to return a JSON object, but HTTP information is being printed below it. I'm using Google App Engine and https://github.com/simplegeo/python-oauth2 #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.weba...
Google App Engine HTTP information being printed somehow
I'm just wanting to return a JSON object, but HTTP information is being printed below it. I'm using Google App Engine and https://github.com/simplegeo/python-oauth2 #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp import util from django.utils import simplejson as json imp...
[ "Add the proper Content-Type and switch to self.response.out.write\nself.response.headers['Content-Type'] = 'application/json' \nself.response.out.write(data)\n\n", "Instead of print use self.response:\n self.response.out.write(\"Some Text\")\n\nI suppose that the RequestHandler automatically prints a default HT...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "http", "python" ]
stackoverflow_0004352689_google_app_engine_http_python.txt
Q: Django -- Common Scenario: Product with M2M -> Categories. How do I efficiently query all categories on a product queryset? I'm trying to cut down on my query counts and have a question. I have a typical product model set up that can have multiple categories. Product M2M -> Category I have a function defined that ...
Django -- Common Scenario: Product with M2M -> Categories. How do I efficiently query all categories on a product queryset?
I'm trying to cut down on my query counts and have a question. I have a typical product model set up that can have multiple categories. Product M2M -> Category I have a function defined that pulls the main category (lets just say its the latest one): class Category(models.Model): name = models.CharField(max_length...
[ "Here's what I would do. Create a through model for the ManyToMany relationship, and stick a boolean field on that model to indicate the main_category status. Then, you can just query that model, using select_related() so it automatically follows the two foreign keys - and now you can iterate through the through ob...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004352056_django_python.txt
Q: PY_MAJOR_VERSION undefined when compiling Python C module for Python 3.x I am trying to upgrade a small C module to work with Python 3.x and having trouble getting it to compile. My roadblock right now is that the preprocessor defines I am supposed to be using to check the Python version aren't working. The module...
PY_MAJOR_VERSION undefined when compiling Python C module for Python 3.x
I am trying to upgrade a small C module to work with Python 3.x and having trouble getting it to compile. My roadblock right now is that the preprocessor defines I am supposed to be using to check the Python version aren't working. The module contains two .c files at the moment (I've temporarily commented out the rest)...
[ "I figured out what I was doing wrong. It's Python.h that defines PY_MAJOR_VERSION. By putting my #defines ahead of my #includes, I missed out on the definition. I don't know why I was thinking that the build system would define it for me...\nMoving the #if PY_MAJOR_VERSION >= 3 so that it executes after #include \...
[ 7 ]
[]
[]
[ "c", "python", "python_3.x", "visual_studio_2008" ]
stackoverflow_0004352847_c_python_python_3.x_visual_studio_2008.txt
Q: TCP port using python - how to forward command output to tcp port? I want to develop a code in python which will open a port in the localhost and will send the logs to that port. Logs will be nothing but the command output of a python file. like : hello.py i = 0 while True: print "hello printed %s times."...
TCP port using python - how to forward command output to tcp port?
I want to develop a code in python which will open a port in the localhost and will send the logs to that port. Logs will be nothing but the command output of a python file. like : hello.py i = 0 while True: print "hello printed %s times." % i i+=1 this will continuously print the statement. I want this...
[ "Here is what i came up with.\nto use with your script you do :\nhello.py | thisscript.py\n\nHope it is was you wanted.\nimport socket\nimport sys\n\nTCP_IP = '127.0.0.1'\nTCP_PORT = 5005\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((TCP_IP, TCP_PORT))\nwhile True:\n line = sys.stdin.readlin...
[ 14, 4 ]
[]
[]
[ "command_line", "python", "send", "tcp" ]
stackoverflow_0004342697_command_line_python_send_tcp.txt
Q: Reading n lines from file (but not all) in Python How to read n lines from a file instead of just one when iterating over it? I have a file which has well defined structure and I would like to do something like this: for line1, line2, line3 in file: do_something(line1) do_something_different(line2) do_...
Reading n lines from file (but not all) in Python
How to read n lines from a file instead of just one when iterating over it? I have a file which has well defined structure and I would like to do something like this: for line1, line2, line3 in file: do_something(line1) do_something_different(line2) do_something_else(line3) but it doesn't work: ValueError...
[ "Basically, your fileis an iterator which yields your file one line at a time. This turns your problem into how do you yield several items at a time from an iterator. A solution to that is given in this question. Note that the function isliceis in the itertools module so you will have to import it from there.\n"...
[ 4, 3, 2, 2, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0004342053_file_python.txt
Q: Decode values of a tuple in django template if(len(f1) > 0): for qs in profile_map: p = Profile.objects.get(pk=qs.emp.id) t_name = p.first_name + p.last_name t_arr.append((q.profile.id,emp_name)) response_dictionary.update({'tarr':t_arr}) render_to_response('project/profile_ta...
Decode values of a tuple in django template
if(len(f1) > 0): for qs in profile_map: p = Profile.objects.get(pk=qs.emp.id) t_name = p.first_name + p.last_name t_arr.append((q.profile.id,emp_name)) response_dictionary.update({'tarr':t_arr}) render_to_response('project/profile_table.html',context_instance=RequestContext(request...
[ "In your case, the generator will assign the tuple to ele, so you can access the first, last name with {{ ele.0 }} {{ ele.1 }}.\nBut this is also legal, to unpack the tuple into two vars:\n{% for first_name, last_name in response_dictionary.tarr %}\n\n", "if you are using django 0.96 you can't have multiple value...
[ 3, 3 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0003618856_django_django_templates_django_views_python.txt
Q: Python & Ctypes: Passing a struct to a function as a pointer to get back data I've looked through other answers but can't seem to get this to work. I'm trying to call a function within a DLL for communicating with SMBus devices. This function takes a pointer to a struct, which has an array as one of it's fields. s...
Python & Ctypes: Passing a struct to a function as a pointer to get back data
I've looked through other answers but can't seem to get this to work. I'm trying to call a function within a DLL for communicating with SMBus devices. This function takes a pointer to a struct, which has an array as one of it's fields. so... In C: typedef struct _SMB_REQUEST { unsigned char Address; unsigned ch...
[ "Here's a working example. It looks like you are passing the wrong type to the function.\nTest DLL Code (\"cl /W4 /LD x.c\" on Windows)\n#include <stdio.h>\n\n#define SMBUS_API __declspec(dllexport)\n#define SMB_MAX_DATA_SIZE 5\n\ntypedef void* SMBUS_HANDLE;\n\ntypedef struct _SMB_REQUEST\n{\n unsigned char Add...
[ 35, 7, 1 ]
[]
[]
[ "ctypes", "pointers", "python", "struct" ]
stackoverflow_0004351721_ctypes_pointers_python_struct.txt
Q: Supress Today link in Django admin date widget I would like to suppress the today link that is available by default in Django admin for a date field. A: Your best solution is to subclass the DateField widget used in the admin and tweak the render() method to not show the link. You can find an example of the gen...
Supress Today link in Django admin date widget
I would like to suppress the today link that is available by default in Django admin for a date field.
[ "Your best solution is to subclass the DateField widget used in the admin and tweak the render() method to not show the link. \nYou can find an example of the general approach to subclassing widgets here:\nAnd to get that widget to be used in the admin, you can set that in the admin.py for the relevant app. Here's ...
[ 0 ]
[]
[]
[ "datefield", "django", "python" ]
stackoverflow_0004352398_datefield_django_python.txt
Q: Is there a way to automatically detect links in Django templates? I am passing in some lists from a view into a django template. In this template, it will extract strings from these lists in a sequence of for loops, and then print out each of these strings. Some of these strings may have URLs in them, like This is...
Is there a way to automatically detect links in Django templates?
I am passing in some lists from a view into a django template. In this template, it will extract strings from these lists in a sequence of for loops, and then print out each of these strings. Some of these strings may have URLs in them, like This is some string. http://google.com Right now when these strings are printe...
[ "Try with urlize template tag.\n" ]
[ 9 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004353385_django_django_templates_python.txt