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: Nosetest including unwanted parent directories I'm trying to limit nosetests to a specific directory, however during the test run it's including the parent directories of the dir I'm targetting and in doing so throws errors. Here's the key elements of output from the test run: nose.importer: DEBUG: Add path /proje...
Nosetest including unwanted parent directories
I'm trying to limit nosetests to a specific directory, however during the test run it's including the parent directories of the dir I'm targetting and in doing so throws errors. Here's the key elements of output from the test run: nose.importer: DEBUG: Add path /projects/myproject/myproject/specs nose.importer: DEBUG: ...
[ "I suppose that you are expecting the following behavior.\nnose.importer: DEBUG: Add path /projects/myproject\nnose.importer: DEBUG: insert /projects/myproject into sys.path\n\nWhy not try a --match or an --exclude pattern to restrict the tests set ?\nTry:\n--exclude myproject/myproject\n\nI check the source code o...
[ 5 ]
[]
[]
[ "nose", "python" ]
stackoverflow_0006197940_nose_python.txt
Q: How to update a model but return unmodified model in Django? I'm using django-piston to write a RESTful Web Service and have a problem. in models.py: class Status(models.Model): user = models.ForeignKey(User) content = models.TextField(max_length=140) class StatusReply(models.Model): user = models.For...
How to update a model but return unmodified model in Django?
I'm using django-piston to write a RESTful Web Service and have a problem. in models.py: class Status(models.Model): user = models.ForeignKey(User) content = models.TextField(max_length=140) class StatusReply(models.Model): user = models.ForeignKey(User) reply_to = models.ForeignKey(Status, related_nam...
[ "Not sure if I understand what you need. As I understand your code, status.replies.all().update(has_read=True) doesn't change status but only changes the replies. If that's true, the code should do what you want. If it isn't, you could make a copy of status and return the copy:\n if status.user == current_us...
[ 2 ]
[]
[]
[ "django", "django_models", "django_piston", "python" ]
stackoverflow_0006264258_django_django_models_django_piston_python.txt
Q: Which is the best way to get a list of running processes in unix with python? I'm trying: import commands print commands.getoutput("ps -u 0") But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND nothing more A: This ...
Which is the best way to get a list of running processes in unix with python?
I'm trying: import commands print commands.getoutput("ps -u 0") But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND nothing more
[ "This works on Mac OS X 10.5.5. Note the capital -U option. Perhaps that's been your problem.\nimport subprocess\nps = subprocess.Popen(\"ps -U 0\", shell=True, stdout=subprocess.PIPE)\nprint ps.stdout.read()\nps.stdout.close()\nps.wait()\n\nHere's the Python version\nPython 2.5.2 (r252:60911, Feb 22 2008, 07:57:...
[ 8, 6, 5, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000160245_python.txt
Q: CPU Usage Per Process in Python Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. ...
CPU Usage Per Process in Python
Is it possible for me to see the amount of processor usage (% of maximum) that the current, python, app is using? Scenario: My host will allow me to run my app as long as it does not consume more then X% of the CPU power, so I would like it to 'keep an eye on itself' and slowdown. So how can I know how much CPU the a...
[ ">>> import os\n>>> os.times()\n(1.296875, 0.765625, 0.0, 0.0, 0.0)\n>>> print os.times.__doc__\ntimes() -> (utime, stime, cutime, cstime, elapsed_time)\n\nReturn a tuple of floating point numbers indicating process times.\n\nFrom the (2.5) manual:\n\ntimes( )\nReturn a 5-tuple of floating point numbers indicating ...
[ 29, 13, 8, 0 ]
[]
[]
[ "cpu_usage", "monitoring", "python" ]
stackoverflow_0000276281_cpu_usage_monitoring_python.txt
Q: Commands in Paramiko block due to script execution time hello guys i have three server and i mange it from SSH so i made this script to run my Register script "Register.py" so everyday i turn on Register mode so the problem how i can login to multiple SSH connection without close the other import paramiko import...
Commands in Paramiko block due to script execution time
hello guys i have three server and i mange it from SSH so i made this script to run my Register script "Register.py" so everyday i turn on Register mode so the problem how i can login to multiple SSH connection without close the other import paramiko import os ZI1={"ip":"192.168.1.2","pass":"Administrator"} ZI2={"ip"...
[ "I'd suggest looking at Fabric. It may help you with working with SSH connections.\n", "The way you are currently doing it blocks beacuse you are not logging out of the hosts for six hours.\nMultiprocessing:\nIf you need to see return codes from the script, you should open your connections to each host using pyth...
[ 1, 1, 0 ]
[]
[]
[ "paramiko", "python", "session", "ssh" ]
stackoverflow_0006265284_paramiko_python_session_ssh.txt
Q: python check pattern in string Possible Duplicate: Python - Check If Word Is In A String. i have a string which is a url e.g. my_url = "http://mysite.com/somefolder/somefile" I want check if "somefolder" is in the my_url file how do I do that? A: Are you looking for this? if "/somefolder/" in my_url: #wha...
python check pattern in string
Possible Duplicate: Python - Check If Word Is In A String. i have a string which is a url e.g. my_url = "http://mysite.com/somefolder/somefile" I want check if "somefolder" is in the my_url file how do I do that?
[ "Are you looking for this?\nif \"/somefolder/\" in my_url:\n #whatever\n\n", "Use:\nprint 'somefolder' in my_url\n\nOR \nprint my_url.index('somefolder')\n\n" ]
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006265552_python.txt
Q: SQLAlchemy: filter_by with like() on foreign attribute I have the following models: class CRRun(Base): ... crID = Column(u'CR_ID', INTEGER(), ForeignKey(CR.id), primary_key=True, nullable=False) cr = relationship(CR, backref=backref("CR_RUN", uselist=False)) ... class CR(Base): ...
SQLAlchemy: filter_by with like() on foreign attribute
I have the following models: class CRRun(Base): ... crID = Column(u'CR_ID', INTEGER(), ForeignKey(CR.id), primary_key=True, nullable=False) cr = relationship(CR, backref=backref("CR_RUN", uselist=False)) ... class CR(Base): ... id = Column(u'CR_ID', INTEGER(), primary_key=True...
[ "Try:\nstate = 'some value'\ncrsRuns = Session.query(CRRun)\ncrsRuns = crsRuns.options(eagerload('cr')) \\\n .filter(CRRun.cr.has(\n CR.state.like('%' + state + '%')\n ))\n\n", "I ended up doing the following:\ncrsRuns = Session.query(CRRun, CR, Run).join(CR).join(Run)\ncrsRuns = crsRuns.filter(CR.st...
[ 3, 1 ]
[]
[]
[ "foreign_key_relationship", "model", "python", "sqlalchemy" ]
stackoverflow_0006205400_foreign_key_relationship_model_python_sqlalchemy.txt
Q: Progress Meter and XPCOM I'm developing a Firefox extension that uses PyXPCOM to run a process. I would like to have a progress meter that is shown when the process is started and gives feedback to the user. In the javascript I have called the Thread Manager to run the process in Python: var threadManager = Comp...
Progress Meter and XPCOM
I'm developing a Firefox extension that uses PyXPCOM to run a process. I would like to have a progress meter that is shown when the process is started and gives feedback to the user. In the javascript I have called the Thread Manager to run the process in Python: var threadManager = Components.classes["@mozilla.org/t...
[ "You shouldn't be creating new threads from JavaScript directly - this has lots of thread safety issues and from all I know this functionality is no longer available in Firefox 4. The replacement are chrome workers: https://developer.mozilla.org/en/DOM/ChromeWorker. So you would create your worker like this:\nvar w...
[ 1 ]
[]
[]
[ "firefox_addon", "javascript", "python", "xpcom" ]
stackoverflow_0006047240_firefox_addon_javascript_python_xpcom.txt
Q: What should be the pythonic way to implement following logic? I would like to loop a list and remove element if it meets the requirement. At the same time, I would transform the removed element and add the transformation result to another list. Right now, I have implemented above logic by following code: delete_s...
What should be the pythonic way to implement following logic?
I would like to loop a list and remove element if it meets the requirement. At the same time, I would transform the removed element and add the transformation result to another list. Right now, I have implemented above logic by following code: delete_set = set([]) for item in my_list: if meet_requirement(item): ...
[ "You could do this with comprehensions only.\ndelete_set = set(I for I in my_list if meet_requirement(I))\nanother_list.extend(transform(I) for I in delete_set)\n# or extend(transform(I) for I in my_list if I in delete_set), if duplicates/order matter\nmy_list = [I for I in my_list if I not in delete_set]\n\n", "...
[ 6, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006265664_python.txt
Q: how to make python 3.x enter text into a web browser Say I wanted to load google, then automatically enter text into the search bar and press enter all without user input, how would i do that? Edit: while i do need to point it to a specific URL, i want python to be able to enter text regardless of the URL. That's ...
how to make python 3.x enter text into a web browser
Say I wanted to load google, then automatically enter text into the search bar and press enter all without user input, how would i do that? Edit: while i do need to point it to a specific URL, i want python to be able to enter text regardless of the URL. That's why i need it to be able to enter text into the search on ...
[ "If I understand properly, you actually want to \"control\" a specific browser, i.e., open a browser window to a specific URL, rather than having a program parse a web page. \nIn this case, you can take a look at the subprocess module, with wich you can actually run an external program (e.g., \"firefox\"), and then...
[ 3, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006258813_python_python_3.x.txt
Q: Python/MySQL: Query executes but nothing happens? I'm executing a simple query with Python but nothing seems to happen when it executes, just as if it skipped the execution. Here's the code: def somefunction(search_query): from django.db import connection, transaction search_query = search_query.strip() ...
Python/MySQL: Query executes but nothing happens?
I'm executing a simple query with Python but nothing seems to happen when it executes, just as if it skipped the execution. Here's the code: def somefunction(search_query): from django.db import connection, transaction search_query = search_query.strip() cursor = connection.cursor() rows = cursor.execu...
[ "Perhaps you have to commit your changes:\ncursor.execute('COMMIT')\n\n" ]
[ 7 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006266002_django_mysql_python.txt
Q: python bitarray to and from file I'm writing a large bitarray to a file using this code: import bitarray bits = bitarray.bitarray(bin='0000011111') #just an example with open('somefile.bin', 'wb') as fh: bits.tofile(fh) However, when i attempt to read this data back using: import bitarray a = bitarray.bitarr...
python bitarray to and from file
I'm writing a large bitarray to a file using this code: import bitarray bits = bitarray.bitarray(bin='0000011111') #just an example with open('somefile.bin', 'wb') as fh: bits.tofile(fh) However, when i attempt to read this data back using: import bitarray a = bitarray.bitarray() with open('somefile.bin', 'rb') a...
[ "I think \"a\" is what you want. a.fromfile(fh) is a method which fills a with the contents of fh: it doesn't return a bitarray.\n>>> import bitarray\n>>> bits = bitarray.bitarray('0000011111')\n>>> \n>>> print bits\nbitarray('0000011111')\n>>> \n>>> with open('somefile.bin', 'wb') as fh:\n... bits.tofile(fh)\...
[ 12, 1 ]
[]
[]
[ "bitarray", "fromfile", "python" ]
stackoverflow_0006266330_bitarray_fromfile_python.txt
Q: python mechanize.Browser returns I've done my first python script, and also my first mechanized Browser, very nice. But... it returns some fields as 'empty string' , which in this case is : "&\nbsp;" (back-slashe is mine, otherwise nothing appears.) Has anyone experienced this before with mechanize.Browser? Here i...
python mechanize.Browser returns
I've done my first python script, and also my first mechanized Browser, very nice. But... it returns some fields as 'empty string' , which in this case is : "&\nbsp;" (back-slashe is mine, otherwise nothing appears.) Has anyone experienced this before with mechanize.Browser? Here is my code: #!/usr/bin/env python impo...
[ "Could javascript be responsible for turning the &\\nbsp; into 0? Mechanize doesn't execute javascript.\n" ]
[ 0 ]
[]
[]
[ "mechanize", "python", "web_scraping" ]
stackoverflow_0006258975_mechanize_python_web_scraping.txt
Q: Improving Python Comparison and Existence Operations I'm fairly new to Python and was hoping I could get some advice before moving forward. I have a group of integers and I want to check whether or not a given element is contained within that group as fast as possible (speed does matter here). With Python, should...
Improving Python Comparison and Existence Operations
I'm fairly new to Python and was hoping I could get some advice before moving forward. I have a group of integers and I want to check whether or not a given element is contained within that group as fast as possible (speed does matter here). With Python, should I be looking at custom data structures tailored for these...
[ "The most Pythonic way would be to not store them in a sorted container, but to use a set (or the immutable variant frozenset). These are hash-based containers, so lookups are O(1). More importantly, the hashing algorithm is one of the core operations in Python (used for dictionaries, and attribute lookups), so i...
[ 6, 6 ]
[]
[]
[ "binary_search", "c", "comparison", "performance", "python" ]
stackoverflow_0006266641_binary_search_c_comparison_performance_python.txt
Q: How do you handle errors raised in Python Paramiko? self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect(self.hostname, username=self.username, password=self.password) except SSHException: #do something I was wondering how to handle errors ra...
How do you handle errors raised in Python Paramiko?
self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect(self.hostname, username=self.username, password=self.password) except SSHException: #do something I was wondering how to handle errors raised by Paramiko when trying to connect to an SSH server?...
[ "Depends on your application.\nHere are some possible actions:\n\nTerminate\nRetry\nLog the error and continue doing something else\n\n" ]
[ 1 ]
[]
[]
[ "error_handling", "paramiko", "python", "ssh" ]
stackoverflow_0006266944_error_handling_paramiko_python_ssh.txt
Q: How to execute long bash sequence with Python subprocess I wanna do this: Bash code: grub --batch << EOF root (hd0,1) find /boot/grub/menu.lst setup (hd0) quit EOF Python code: subprocess.call('grub --batch << EOF', shell=True) subprocess.call('root (hd0,1)', shell=True) subprocess.call('find /boot/grub/menu.lst'...
How to execute long bash sequence with Python subprocess
I wanna do this: Bash code: grub --batch << EOF root (hd0,1) find /boot/grub/menu.lst setup (hd0) quit EOF Python code: subprocess.call('grub --batch << EOF', shell=True) subprocess.call('root (hd0,1)', shell=True) subprocess.call('find /boot/grub/menu.lst', shell=True) subprocess.call('setup (hd0)', shell=True) subpr...
[ "The solution is to send the script as one string:\nscript = '''\nroot (hd0,1)\nfind /boot/grub/menu.lst\nsetup (hd0)\nquit\n'''\nprint subprocess.Popen('grub', stderr=subprocess.STDOUT).communicate(script)[0]\n\nshell=True should not be necessary.\n", "You could do something horrible like:\nsubprocess.call('echo...
[ 5, 1 ]
[]
[]
[ "bash", "python", "subprocess" ]
stackoverflow_0006266720_bash_python_subprocess.txt
Q: Wrong in Parsing Sparse ARFF with pyparsing all i've found a piece of code to parse simple ARFF file and i wanna change it to fit sparse ARFF whose data looks like: @data {0 12,4 37,8 First,20 'Some Thing'} {0 12,13 First,28 'Some Thing'} here is the code: def ParseFromSimpleARFF(data): arffFormat = Forward(...
Wrong in Parsing Sparse ARFF with pyparsing
all i've found a piece of code to parse simple ARFF file and i wanna change it to fit sparse ARFF whose data looks like: @data {0 12,4 37,8 First,20 'Some Thing'} {0 12,13 First,28 'Some Thing'} here is the code: def ParseFromSimpleARFF(data): arffFormat = Forward() E = CaselessLiteral("E") comment = '%' ...
[ "No, no, no! A big part of pyparsing is that \"whitespace happens\"! Unless you are doing something tricky with indentation-based parsing, or line-oriented data, leave the whitespace out of the parser definition.\nYour issue is that what you are defining as a dataList doesn't match the lists you are giving it. Eac...
[ 2 ]
[]
[]
[ "arff", "pyparsing", "python" ]
stackoverflow_0006266743_arff_pyparsing_python.txt
Q: How to write static_files exclude one subdirectory in yaml of Google App Engine With app.yml in GAE, we use regular expressions to match a certain type of url address. If I want to match a subdirectory of the path which is not a particula string(exclude one ), I do not know how to write regular expression? For exa...
How to write static_files exclude one subdirectory in yaml of Google App Engine
With app.yml in GAE, we use regular expressions to match a certain type of url address. If I want to match a subdirectory of the path which is not a particula string(exclude one ), I do not know how to write regular expression? For example: I want to upload foo/bar/.* as static files exclude any files in foo/bar/dir/.*...
[ "Most people keep all their static files in a subdirectory called \"public\" or \"static\" to avoid this issue, and I recommend you do the same.\nYou could add a line to catch your files by extension like:\n- url: /foo/bar/([^.]+\\.(js|css))\n static_files: foo/bar/\\1\n upload: foo/bar/[^.]+\\.(js|css)\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python", "yaml" ]
stackoverflow_0006265336_google_app_engine_python_yaml.txt
Q: Modifying axes on matplotlib colorbar plot of 2D array I have a 2D numpy array that I want to plot in a colorbar. I am having trouble changing the axis so that they display my dataset. The vertical axis goes 'down' from 0 to 100, whereas I want it to go 'up' from 0.0 to 0.1. So I need to do two things: Flip the a...
Modifying axes on matplotlib colorbar plot of 2D array
I have a 2D numpy array that I want to plot in a colorbar. I am having trouble changing the axis so that they display my dataset. The vertical axis goes 'down' from 0 to 100, whereas I want it to go 'up' from 0.0 to 0.1. So I need to do two things: Flip the array using np.flipud() and then 'flip' the axis as well Chan...
[ "You want to look at the imshow options \"origin\" and \"extent\", I think. \nimport matplotlib.pyplot as plt\nimport numpy as np\n\nx,y = np.mgrid[-2:2:0.1, -2:2:0.1]\ndata = np.sin(x)*(y+1.05**(x*np.floor(y))) + 1/(abs(x-y)+0.01)*0.03\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nticks_at = [-abs(data).max()...
[ 9, 0 ]
[]
[]
[ "colorbar", "matplotlib", "numpy", "python" ]
stackoverflow_0006267008_colorbar_matplotlib_numpy_python.txt
Q: pointer in python? When I was trying to figure out the use of imp.load_module in Python, I got the following code (origin page). It's my first time seeing the use of * in Python, is that some pointer like things? thanks in advance import imp import dbgp info = imp.find_module(modname, dbgp.__path__) _client = imp....
pointer in python?
When I was trying to figure out the use of imp.load_module in Python, I got the following code (origin page). It's my first time seeing the use of * in Python, is that some pointer like things? thanks in advance import imp import dbgp info = imp.find_module(modname, dbgp.__path__) _client = imp.load_module(modname, *in...
[ "The * on front if info causes the list / tuple to be unwrapped into individual arguments to the function. You can read more about unpacking here in the python documentation. this can also be done with dictionaries for named arguments, see here\nFor example,\ndef do_something(a,b,c,d):\n print(\"{0} {1} {2} {3...
[ 7, 4 ]
[]
[]
[ "pointers", "python" ]
stackoverflow_0006267505_pointers_python.txt
Q: MongoDB and Whoosh. Do I need both? I am working on the project that uses MongoDB and Whoosh. I wonder if the Whoosh is necessary if I can use MongoDB search. I am sure Whoosh was setup in the system for good, but I am not sure I understand right its purpose. Please give me some idea about what it gives that Mongo...
MongoDB and Whoosh. Do I need both?
I am working on the project that uses MongoDB and Whoosh. I wonder if the Whoosh is necessary if I can use MongoDB search. I am sure Whoosh was setup in the system for good, but I am not sure I understand right its purpose. Please give me some idea about what it gives that MongoDB alone doesn't.
[ "MongoDB search requires you to add keywords that you can later search on, so it's not really full text search (as Whoosh is). Whoosh can also do stemming (not available out of the box with MongoDB) and flexible scoring of results (including user-defined scoring).\n", "Whoosh is a fast full-text searching and ind...
[ 1, 0 ]
[]
[]
[ "mongodb", "python", "whoosh" ]
stackoverflow_0006267072_mongodb_python_whoosh.txt
Q: Managing many Python projects/virtualenvs In my workplace, I have to manage many (currently tens, but probably hundreds eventually) Python web applications, potentially running various frameworks, libraries, etc (all at various versions). Virtualenv has been a lifesaver in managing that so far, but I'd still like...
Managing many Python projects/virtualenvs
In my workplace, I have to manage many (currently tens, but probably hundreds eventually) Python web applications, potentially running various frameworks, libraries, etc (all at various versions). Virtualenv has been a lifesaver in managing that so far, but I'd still like to be able to manage things better, particular...
[ "You might consider using zc.buildout. It's more annoying to set up than plain pip/virtualenv, but it gives you more opportunities for automation. If the disk space usage isn't an issue, I'd suggest you just keep using individual environments for each project so you can upgrade them one at a time.\n", "We have ...
[ 2, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0006267613_python_virtualenv.txt
Q: Bundling python files inside jar for access via jython In the following code I simply execute test.py from java code using jython public static void main(String[] args) { org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter(); python.execfile("test.py"); ... My problem is test.py...
Bundling python files inside jar for access via jython
In the following code I simply execute test.py from java code using jython public static void main(String[] args) { org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter(); python.execfile("test.py"); ... My problem is test.py needs to be in same directory from where jar file is run. I...
[ "You can simply put test.py at the root of the jar, with the other scripts organized as they would be on the fs in normal python.\nThen you can do something like that:\npublic static void main(String[] args) {\n org.python.util.PythonInterpreter python = new org.python.util.PythonInterpreter();\n python.exec(\"im...
[ 6, 0 ]
[]
[]
[ "jar", "java", "jython", "python" ]
stackoverflow_0006260311_jar_java_jython_python.txt
Q: More efficient way to write this simple Python non-sequential number generator? Is there a more efficient way to write this so it's not looping from 1 to n (which hangs on n == 2**32): def ns_num(n, seed, modulo, incrementor): assert n < modulo current = seed # some start value for i in xrange(1, n): ...
More efficient way to write this simple Python non-sequential number generator?
Is there a more efficient way to write this so it's not looping from 1 to n (which hangs on n == 2**32): def ns_num(n, seed, modulo, incrementor): assert n < modulo current = seed # some start value for i in xrange(1, n): current = (current + incrementor) % modulo return current print ns_num(...
[ "That's the same as\nreturn (seed + (n - 1) * incrementor) % modulo\n\n(Are you sure you want n - 1? That's what you current code does.)\n" ]
[ 7 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006268045_algorithm_python.txt
Q: Rationalising package structure in python I am developing a python library with the following structure /application /lib __init__.py /models __init__.py model1.py model2.py model3.py In each model%.py file there is a corresponding class named Model%. I like to keep these classes in their ...
Rationalising package structure in python
I am developing a python library with the following structure /application /lib __init__.py /models __init__.py model1.py model2.py model3.py In each model%.py file there is a corresponding class named Model%. I like to keep these classes in their own files but it means that in my application I...
[ "Your final solution is correct. You should only worry about loading too many classes if it is causing serious performance issues, which I highly doubt.\n", "One way is to create a file in your models directory that imports your classes, then import from that file. For example, you could create a file called api...
[ 2, 1, 1 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0006267901_packaging_python.txt
Q: python-openid doesn't provide ax or sreg attributes I've been able to finally get python-openid to authenticate a user, but I'm not able to create a sreg.SRegResponse or ax.FetchResponse as they come back as None. This is coming from a Google Apps account and I'm trying to follow the example from https://github.c...
python-openid doesn't provide ax or sreg attributes
I've been able to finally get python-openid to authenticate a user, but I'm not able to create a sreg.SRegResponse or ax.FetchResponse as they come back as None. This is coming from a Google Apps account and I'm trying to follow the example from https://github.com/openid/python-openid/tree/master/examples/djopenid. I...
[ "I was having problems with Google returning not the schema.openid.net values for AttributeExchange. It was returning None just like you mentioned, and the worst part is that it used to work when I first wrote my OpenID handlers. \nOnce I switched over to the axschema values in my implementation, it worked like a c...
[ 4 ]
[]
[]
[ "django", "google_app_engine", "openid", "python" ]
stackoverflow_0005979260_django_google_app_engine_openid_python.txt
Q: Python telnetlib not reading everything I'm trying to automate the download of Argos data using Python's telnetlib, but I can't seem to figure out how to get it to download all of the output. Part of my problem may be that I don't really understand the seemingly asynchronous nature of the commands. Here's the cod...
Python telnetlib not reading everything
I'm trying to automate the download of Argos data using Python's telnetlib, but I can't seem to figure out how to get it to download all of the output. Part of my problem may be that I don't really understand the seemingly asynchronous nature of the commands. Here's the code: tn = telnetlib.Telnet(host = HOST, timeout...
[ "# At this point, it's presumably dumped it all\ntn.read_until(\"ARGOS READY\")\ntn.read_until(\"/\")\n\nAt a guess, this bit is sucking up the data and doing nothing with it. Think of it like a pair of pipes - you send stuff one way with write, and pull stuff back with read_*. If you've already sucked the stuff up...
[ 0 ]
[]
[]
[ "python", "telnetlib" ]
stackoverflow_0006268386_python_telnetlib.txt
Q: Automating capture of Extent from multiple mxds with multiple dataframes I want to create a single shape file from multiple mxd's that have multiple frame sets with different extents in them. I have found/started a python script to do this (code below) but can't figure out how to write the captured X&Y Max/Min int...
Automating capture of Extent from multiple mxds with multiple dataframes
I want to create a single shape file from multiple mxd's that have multiple frame sets with different extents in them. I have found/started a python script to do this (code below) but can't figure out how to write the captured X&Y Max/Min into the shape file that is created for this. See output below - an Attribute Err...
[ "First you define mxd2 as a list of .shp files, then you clobber it by using it as the value for the mxds_List loop, which turns mxd2 into a series of string values. By the time point_object is assigned, mxd2 is a string object which does not have an \"shp\" attribute. You probably want \"for mxd in mxds_List\" to ...
[ 0 ]
[]
[]
[ "arcgis", "attributes", "gis", "python", "shapefile" ]
stackoverflow_0005826444_arcgis_attributes_gis_python_shapefile.txt
Q: reverse() throws AttributeError on call I'm trying to reverse a named url called blog-home but no matter what I try it always throws an AttributeError with the description 'NoneType' object has no attribute 'rindex'. I've tried reverse("blog-home"), reverse("blogengine:blog-home") and even reverse("admin:index") a...
reverse() throws AttributeError on call
I'm trying to reverse a named url called blog-home but no matter what I try it always throws an AttributeError with the description 'NoneType' object has no attribute 'rindex'. I've tried reverse("blog-home"), reverse("blogengine:blog-home") and even reverse("admin:index") and reverse(resolve("/admin/")) just to test i...
[ "Don't do that:\nurl(r'^yadda/$', None)\n\nIf you specify an URL in the conf, it must be bound to something. If you don't want to bind it, don't specify it.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006268512_django_python.txt
Q: numpy: Replacing values in a recarray I'm pretty new to numpy, and I'm trying to replace a value in a recarray. So I have this array: import numpy as np d = [('1', ''),('4', '5'),('7', '8')] a = np.array(d, dtype=[('first', 'a5'), ('second', 'a5')]) I would like to do something like this: ind = a=='' #Replace all...
numpy: Replacing values in a recarray
I'm pretty new to numpy, and I'm trying to replace a value in a recarray. So I have this array: import numpy as np d = [('1', ''),('4', '5'),('7', '8')] a = np.array(d, dtype=[('first', 'a5'), ('second', 'a5')]) I would like to do something like this: ind = a=='' #Replace all blanks a[ind] = '12345' but that doesnt w...
[ "The \"element-by-element\" operations of numpy (with wich you can perform some function on all elements of the array at once without a loop) don't work with recarrays as far as I know. You can only do that with the individual columns.\nIf you want to use recarrays, I think the easiest solution is to loop the diffe...
[ 5 ]
[ "One possible solution:\na[np.where(a['second']=='')[0][0]]['second']='12345'\n\n" ]
[ -1 ]
[ "numpy", "python", "recarray" ]
stackoverflow_0006258415_numpy_python_recarray.txt
Q: Python scripts times out when I copy too many files I have a Python script which copies a bunch of files from an anonymous ftp site. When I try to copy several thousand, the script times out before all the files can be copied. However, if I run the script several times and only copy a few hundred files each time,...
Python scripts times out when I copy too many files
I have a Python script which copies a bunch of files from an anonymous ftp site. When I try to copy several thousand, the script times out before all the files can be copied. However, if I run the script several times and only copy a few hundred files each time, it has no problem. The files are text files and are arou...
[ "It's technically not grabbing all the files at once, but if calling the script multiple times on smaller sets of files works, then you might as well have the script itself copy only a few hundred files at a time, grabbing a new set each iteration.\n", "Does ftp.retbinary() block when you call it?\nIf not, it mea...
[ 0, 0 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0006268740_ftp_python.txt
Q: Python alternative of ruby watirrecorder? I'm looking for a tool to record scripts for web application testing in python, similar to ruby watirrecorder. The latter is basically a tool that generates the script for watir (web application testing in ruby) which uses IE to test web applications. A: Try Selenium, h...
Python alternative of ruby watirrecorder?
I'm looking for a tool to record scripts for web application testing in python, similar to ruby watirrecorder. The latter is basically a tool that generates the script for watir (web application testing in ruby) which uses IE to test web applications.
[ "Try Selenium, http://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.html\n", "Another alternative may be Pamie, but not sure it is as mature as Selenium.\nhttp://sourceforge.net/projects/pamie/\n" ]
[ 5, 1 ]
[]
[]
[ "python", "ruby", "watir" ]
stackoverflow_0001660643_python_ruby_watir.txt
Q: test for node membership in pydot graph pydot has a huge number of bound methods for getting and setting every little thing in a dot graph, reading and writing, you-name-it, but I can't seem to find a simple membership test. >>> d = pydot.Dot() >>> n = pydot.Node('foobar') >>> d.add_node(n) >>> n in d.get_nodes()...
test for node membership in pydot graph
pydot has a huge number of bound methods for getting and setting every little thing in a dot graph, reading and writing, you-name-it, but I can't seem to find a simple membership test. >>> d = pydot.Dot() >>> n = pydot.Node('foobar') >>> d.add_node(n) >>> n in d.get_nodes() False is just one of many things that didn'...
[ "Looking through the source code, http://code.google.com/p/pydot/source/browse/trunk/pydot.py, it seems that node names are unique values, used as the keys to locate the nodes within a graph's node dictionary (though, interestingly, rather than return an error for an existing node, it simply adds the attributes of ...
[ 2 ]
[]
[]
[ "dot", "graphviz", "pydot", "python" ]
stackoverflow_0006268782_dot_graphviz_pydot_python.txt
Q: How to find out what function the Python interpreter is calling from callable PyObject? I'm trying to trace through the Python source code where a certain function is actually called and how to get its name. In abstract.c: PyObject * PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { ternaryfunc call...
How to find out what function the Python interpreter is calling from callable PyObject?
I'm trying to trace through the Python source code where a certain function is actually called and how to get its name. In abstract.c: PyObject * PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { ternaryfunc call; if((call = func->ob_type->tp_name) != NULL){ PyObject *result; ... ...
[ "The __name__ attribute of the function object should contain the name. The arguments are in arg as a tuple and kw as a dict.\n" ]
[ 1 ]
[]
[]
[ "cpython", "python", "python_2.6" ]
stackoverflow_0006269174_cpython_python_python_2.6.txt
Q: Why does pickle not see the class 'painter' when loading? I am working with a o.o.p and trying to use pickle to load a list of lines I save in a .txt file. I can save the data with pickle, but I am not sure why it can't see 'painter' after I have initialized it. class LoadButton(MTButton): def __init__(self, *...
Why does pickle not see the class 'painter' when loading?
I am working with a o.o.p and trying to use pickle to load a list of lines I save in a .txt file. I can save the data with pickle, but I am not sure why it can't see 'painter' after I have initialized it. class LoadButton(MTButton): def __init__(self, **kwargs): super(LoadButton, self).__init__(**kwargs) ...
[ "It is because painter = newpainter creates a local variable painter, even if after the part when you call the global painter.\nDo something like this:\npainter_ = newpainter\nscatter.add_widget(painter_)\n\nEDIT: But why don't you use only painter?\n scatter.remove_widget(painter)\n oldlines = pickle...
[ 1 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0006268879_pickle_python.txt
Q: Python/Mysql: Refuses to escape string! I have a pretty long query i need to execute, and i'm using prepared statements to insert the values to the query. As far as i know, it's suppose to work, but it's not working! Here's the code: cursor = connection.cursor() rows = cursor.execute(r"""SELECT... %s.. %s....
Python/Mysql: Refuses to escape string!
I have a pretty long query i need to execute, and i'm using prepared statements to insert the values to the query. As far as i know, it's suppose to work, but it's not working! Here's the code: cursor = connection.cursor() rows = cursor.execute(r"""SELECT... %s.. %s.. %s...""",(val1,val2,val3,)) rows = curs...
[ "This is a general technique for debugging SQL (especially when generated from another language, like Python):\nStop the mysql server (assuming you run mysqld without logging):\nsudo invoke-rc.d mysql stop\n\nRun mysqld with logging turned on:\nsudo mysqld --log=/tmp/myquery.log\n\nRun your script.\nLook in /tmp/my...
[ 0 ]
[]
[]
[ "escaping", "mysql", "python" ]
stackoverflow_0006269234_escaping_mysql_python.txt
Q: writing to model field in django / python i'm trying to populate custom user profile fields with data from social networks. i created profile fields like: currentjobtitle1 currentjobtitle2 currentjobtitle3 pastjobtitle1 pastjobtitle2 pastjobtitle3 I'm a newb in every way, so i tried to code this more efficiently...
writing to model field in django / python
i'm trying to populate custom user profile fields with data from social networks. i created profile fields like: currentjobtitle1 currentjobtitle2 currentjobtitle3 pastjobtitle1 pastjobtitle2 pastjobtitle3 I'm a newb in every way, so i tried to code this more efficiently than normal and have become very confused. I'...
[ "setattr(SarProfile, '%sjobtitle%d' % (var, count), x['position']['name'])\n\nBut you probably want to create an instance of SarProfile first, and use that instead.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006269409_django_python.txt
Q: Why can't paramiko run this command? (Python) echo Something=Something > file I can use paramiko's exec_command to do cat, grep and ls, but whenever I try to modify a file it does nothing. I already ran su before this. The file remains exactly the same as it was before running the command. A: This is because yo...
Why can't paramiko run this command? (Python)
echo Something=Something > file I can use paramiko's exec_command to do cat, grep and ls, but whenever I try to modify a file it does nothing. I already ran su before this. The file remains exactly the same as it was before running the command.
[ "This is because you have to open a new channel for each exec_command call. This loses the authentication of the su command since it is associated to a specific channel. \nYou have a couple of options.\n\nrun the command with sudo, which may not be possible over paramiko\nLog in as root, which is not necessarily a ...
[ 2 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0006269000_paramiko_python_ssh.txt
Q: How to insert a string of characters into a text file using python? This is the text file I have . # This is an auto-generated Django model module created by ogrinspect. from django.contrib.gis.db import models class Parking(models.Model): name = models.CharField(max_length=80) descriptio = models.Char...
How to insert a string of characters into a text file using python?
This is the text file I have . # This is an auto-generated Django model module created by ogrinspect. from django.contrib.gis.db import models class Parking(models.Model): name = models.CharField(max_length=80) descriptio = models.CharField(max_length=80) geom = models.PointField(srid=4326) objects ...
[ "You can first read all into a list, insert your text into the required(here you can use regular expressions or 'find'/'index' and etc) position and then simply rewrite file.\n", "#!/usr/bin/python\nfilename='thefile.txt'\nsearch=\"class Parking(models.Model):\"\nadd=\"\\n layer_id= models.ForeignKey('sdr_laye...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006269383_python.txt
Q: How do I get admin.StackedInline or admin.TabularInline like feel in my own views? Consider the simple Poll example in the Django Tutorial example in Djnagoproject web site. Once you use admin.StackedInline or TabularInline, you get a nice interface which allows you create a neat Poll application. If I need to pro...
How do I get admin.StackedInline or admin.TabularInline like feel in my own views?
Consider the simple Poll example in the Django Tutorial example in Djnagoproject web site. Once you use admin.StackedInline or TabularInline, you get a nice interface which allows you create a neat Poll application. If I need to provide same look, feel and functionality in my own custom views, what should I do. For eg:...
[ "Inline formsets.\n" ]
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006269670_django_django_forms_python.txt
Q: Program used to calculate the sum of all numbers from zero to 999 producing in consistent results Below is python code that attempts to find the sum of all values divided by a particular number using arithmetic progression equations found here The program will produce incorrect output only a handful of the time, ...
Program used to calculate the sum of all numbers from zero to 999 producing in consistent results
Below is python code that attempts to find the sum of all values divided by a particular number using arithmetic progression equations found here The program will produce incorrect output only a handful of the time, with the same numbers being off by the exact same amount everytime. Sample Output Format: First its th...
[ "You're running into an issue with integer division and order of operations. Remove the parentheses to change your function from this:\ndef SumDivisibleby(first,last,nTerms): return nTerms * ((first + last)/2);\n\nto this:\ndef SumDivisibleby(first,last,nTerms): return nTerms * (first + last)/2;\n\nEDIT: As an exam...
[ 3 ]
[]
[]
[ "math", "python" ]
stackoverflow_0006269539_math_python.txt
Q: Efficient reduction of a list in python So I have a list of 85 items. I would like to continually reduce this list in half (essentially a binary search on the items) -- my question is then, what is the most efficient way to reduce the list? A list comprehension would continually create copies of the list which is ...
Efficient reduction of a list in python
So I have a list of 85 items. I would like to continually reduce this list in half (essentially a binary search on the items) -- my question is then, what is the most efficient way to reduce the list? A list comprehension would continually create copies of the list which is not ideal. I would like in-place removal of r...
[ "For a mere 85 items, truthfully, almost any method you want to use would be more than fast enough. Don't optimize prematurely.\nThat said, depending on what you're actually doing, a list may be faster than a deque. A deque is faster for adding and removing items at either end, but it doesn't support slicing. \nWit...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "algorithm", "list", "memory_efficient", "python" ]
stackoverflow_0006269262_algorithm_list_memory_efficient_python.txt
Q: Connecting to a subprocess stdin to pipe I have a method that creates a subprocess and connects it STDIN to an anonymous pipe; which is not working. Its not raising any exceptions, the subprocess just never seems to never read the data. (the subprocess is the 'zenity' executable for displaying a progress bar in ...
Connecting to a subprocess stdin to pipe
I have a method that creates a subprocess and connects it STDIN to an anonymous pipe; which is not working. Its not raising any exceptions, the subprocess just never seems to never read the data. (the subprocess is the 'zenity' executable for displaying a progress bar in the GUI) class Screen(object): def __init_...
[ "You probably need to flush the file buffers. Try doing self.progress.flush() after each write.\n", "os.fdopen() should have a buffer size of 0. Use rfd = os.fdopen(readp, 'r', 0).\n" ]
[ 1, 1 ]
[]
[]
[ "pipe", "python", "stdin", "subprocess" ]
stackoverflow_0006269886_pipe_python_stdin_subprocess.txt
Q: Parsing Multipart emails in python and saving attachments I am pretty new to python and I am trying to parse email from gmail via python's imaplib and email. It is working pretty well but I am having issues with email attachments. I would like to parse out all of the plaintext from the email while ignoring any HT...
Parsing Multipart emails in python and saving attachments
I am pretty new to python and I am trying to parse email from gmail via python's imaplib and email. It is working pretty well but I am having issues with email attachments. I would like to parse out all of the plaintext from the email while ignoring any HTML that may be inserted as a secondary content type while also ...
[ "If you just need to keep text attachments out of the body variable with what you have there, it should be as simple as this:\nmail = email.message_from_string(email_body)\n for part in mail.walk():\n c_type = part.get_content_type()\n c_disp = part.get('Content-Disposition')\n\n if c_type =...
[ 11 ]
[]
[]
[ "attachment", "email", "gmail", "imaplib", "python" ]
stackoverflow_0006255202_attachment_email_gmail_imaplib_python.txt
Q: Extracting each line from a file and passing it as a variable to "foreach" loop Could somebody help me figure out a simple way of doing this using any script ? I will be running the script on Linux 1 ) I have a file1 which has the following lines : (Bank8GntR[3] | Bank8GntR[2] | Bank8GntR[1] | Bank8GntR[0] ), (...
Extracting each line from a file and passing it as a variable to "foreach" loop
Could somebody help me figure out a simple way of doing this using any script ? I will be running the script on Linux 1 ) I have a file1 which has the following lines : (Bank8GntR[3] | Bank8GntR[2] | Bank8GntR[1] | Bank8GntR[0] ), (Bank7GntR[3] | Bank7GntR[2] | Bank7GntR[1] | Bank7GntR[0] ), (Bank6GntR[3] | Bank6G...
[ "How about something like this in Python:\n# a function that adds 7 to a matched group.\n# groups 1 and 2, we grabbed (Bank) to avoid catching the digits in brackets.\ndef plus7(matchobj):\n return '%s%d' % (matchobj.group(1), int(matchobj.group(2)) + 7)\n\n# iterate over the input file, have access to the output ...
[ 3, 0 ]
[]
[]
[ "linux", "python", "regex", "sed" ]
stackoverflow_0006270155_linux_python_regex_sed.txt
Q: Slicing of python os.listdir() Can I make a slicing in os.listdir()? To take only a number of elements. A: I don't see why not: >>> os.listdir(os.getcwd()) ['CVS', 'library.bin', 'man', 'PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text'] >>> os.listdir(os.getcwd())[3:] ['PyLpr-0.2a.zip', 'pylpr.exe', 'python2...
Slicing of python os.listdir()
Can I make a slicing in os.listdir()? To take only a number of elements.
[ "I don't see why not:\n>>> os.listdir(os.getcwd())\n['CVS', 'library.bin', 'man', 'PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']\n>>> os.listdir(os.getcwd())[3:]\n['PyLpr-0.2a.zip', 'pylpr.exe', 'python26.dll', 'text']\n\n", "Since os.listdir(path) returns a list, you can use slice notation on the result....
[ 3, 3 ]
[]
[]
[ "python", "slice" ]
stackoverflow_0006270684_python_slice.txt
Q: Django on Dreamhost with Passenger: no response to browsers, no error I'm trying to get some trivial Django to run on my dreamhost account. I did do my homework before choosing Dreamhost, but only recently decided to try Django. Anyhow, I have a trivial app that I want to run under something.mydomain.com. Passenge...
Django on Dreamhost with Passenger: no response to browsers, no error
I'm trying to get some trivial Django to run on my dreamhost account. I did do my homework before choosing Dreamhost, but only recently decided to try Django. Anyhow, I have a trivial app that I want to run under something.mydomain.com. Passenger is enabled. When I visit a static page, it loads fine, out of ~/something...
[ "I gave up on using Django on Dreamhost because their server forcibly kills any wsgi process on a timed basis. After that a new request has to start a new instance, which in my case meant that queries sometimes took 10-15s. It was more than enough time for most people to assume the site was down and give up.\nThi...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "dreamhost", "passenger", "python", "wsgi" ]
stackoverflow_0004251647_django_dreamhost_passenger_python_wsgi.txt
Q: Placing Python objects in shared memory Is there a Python module that would enable me to place instances of non-trivial user classes into shared memory? By that I mean allocating directly in shared memory as opposed to pickling into and out of it. multiprocessing.Value and multiprocessing.Array wouldn't work for m...
Placing Python objects in shared memory
Is there a Python module that would enable me to place instances of non-trivial user classes into shared memory? By that I mean allocating directly in shared memory as opposed to pickling into and out of it. multiprocessing.Value and multiprocessing.Array wouldn't work for my use case as they only seem to support primi...
[ "That's kind of a tough one. The best solution I can think of is pickling your objects and using a c_char_p with multiprocessing.sharedctypes. You'd still have to make sure no null bytes got into the c_char_p, either by escaping them or converting to hex.\nOn second thought, maybe you should go with POSH.\n" ]
[ 1 ]
[]
[]
[ "allocation", "python", "shared_memory" ]
stackoverflow_0006270849_allocation_python_shared_memory.txt
Q: How to "comma" format the output of a django variable? I have this variable: {{ object.article.rating.get_percent|floatformat }} that outputs this: 540787 Is there a way to format it so it shows as: 540,787 A: this should help you out: http://twigstechtips.blogspot.com/2010/02/django-formatting-numbers-with-c...
How to "comma" format the output of a django variable?
I have this variable: {{ object.article.rating.get_percent|floatformat }} that outputs this: 540787 Is there a way to format it so it shows as: 540,787
[ "this should help you out:\nhttp://twigstechtips.blogspot.com/2010/02/django-formatting-numbers-with-commas.html\ndetails:\nadd \"django.contrib.humanize\" to your INSTALLED_APPS setting.\nthen in the template:\n{% load humanize %}\n{{ price|intcomma }}\n\n" ]
[ 12 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006270904_django_python.txt
Q: Could not scrape data in English, help! I have a website that I'm trying to scrape using Python & BeautifulSoup. The site itself can be viewed in 2 languages(Thai or English); all you have to do is to click on either the Thai or UK flag on the upper right corner of the screen and the data is displayed in the selec...
Could not scrape data in English, help!
I have a website that I'm trying to scrape using Python & BeautifulSoup. The site itself can be viewed in 2 languages(Thai or English); all you have to do is to click on either the Thai or UK flag on the upper right corner of the screen and the data is displayed in the selected language. When in comes to the script tho...
[ "You haven't said what the site is so impossible to answer for sure. But a couple of suggestions. If the url does not change when you click the flag, then either:\na) The english is already in the html document, and the relevant content is being switched with javascript\nb) The english content is being fetched via ...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0006268580_beautifulsoup_python.txt
Q: How to check if permutations have equal parity? I am looking for a way to check if 2 permutations (represented by lists) are of the same parity. Note that I am not interested if they are even or odd parity, just the equality. I am new to Python and my naive solution is given below as a reply. I am looking forward ...
How to check if permutations have equal parity?
I am looking for a way to check if 2 permutations (represented by lists) are of the same parity. Note that I am not interested if they are even or odd parity, just the equality. I am new to Python and my naive solution is given below as a reply. I am looking forward to Python gurus showing me some cool tricks to achiev...
[ "If we combine both permutations, the result will have even parity when each permutation has the same parity, and odd parity if they have different parity. So if we solve the parity problem it's trivial to compare two different permutations.\nParity can be determined as follows: pick an arbitrary element, find the ...
[ 7, 6, 5, 4, 3, 2, 0, 0 ]
[]
[]
[ "list", "parity", "permutation", "python" ]
stackoverflow_0001503072_list_parity_permutation_python.txt
Q: Design help for static content with fixed keywords search framework I am trying to work out a solution for detecting traceability between source code and documentation. The most important use case is that the user needs to see the a collection of source code tokens (sorted by relevance to the documentation) that c...
Design help for static content with fixed keywords search framework
I am trying to work out a solution for detecting traceability between source code and documentation. The most important use case is that the user needs to see the a collection of source code tokens (sorted by relevance to the documentation) that can be traced back to the documentation. She is wont be bothered about the...
[ "I'm not sure, if I understand your use case. The user sees the source code and has some ways of jumping from a token to the appropriate part or a listing of the possible parts of the documentation, right?\nThen a search tool seems to be the right tool for the job, although you could precompile every possible searc...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006266899_python.txt
Q: On-demand function sharing I need to convert from strings to the code named references. The only currently known option is a script that makes a script, and I was thinking it could be inline like exec. class finder: def __init__(self, parent): self.parent = parent def isin(self, what): return what in s...
On-demand function sharing
I need to convert from strings to the code named references. The only currently known option is a script that makes a script, and I was thinking it could be inline like exec. class finder: def __init__(self, parent): self.parent = parent def isin(self, what): return what in self.parent def find(self, what...
[ "I may be wrong, but I think what you're looking for is the ability to find the symbol for a method or attribute based on a string that is determined at runtime. If that's the case, I would pursue a different approach than a strategy based around exec or eval which have problems, like potential python injection att...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006271321_python.txt
Q: Processing multiple forms on same page I have an account page where I have three forms. A user can change his name, his email address, and his password. There are two difficulties I am having from trying to do this: 1) the request.user information is not updating accordingly (e.g., it will lag behind by one change...
Processing multiple forms on same page
I have an account page where I have three forms. A user can change his name, his email address, and his password. There are two difficulties I am having from trying to do this: 1) the request.user information is not updating accordingly (e.g., it will lag behind by one change or it will update if the form is not valida...
[ "I think martin means:\n@login_required\ndef account(request):\n name_message = password_message = email_message = ''\n if request.method == \"POST\":\n change_name_form = ChangeNameForm(data=request.POST or None, instance=request.user)\n change_password_form = PasswordChangeForm(data=request.POST...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0006270262_django_django_forms_django_views_python.txt
Q: google apps db.model ignores StringPropertys which i defined I'm making a BBS by using google apps. It works, but it's under 5000 words by each thread. I unioned 10 db.StringProperty() of db.model. I planned to union 1000 StringProperty(), but it doesn't work for more than 10. Google apps engine ignores additional...
google apps db.model ignores StringPropertys which i defined
I'm making a BBS by using google apps. It works, but it's under 5000 words by each thread. I unioned 10 db.StringProperty() of db.model. I planned to union 1000 StringProperty(), but it doesn't work for more than 10. Google apps engine ignores additional StringProperty()'s. The error said: 'TypeError: coercing to Uni...
[ "Your error is because you are trying to do:\nu'a' + u'b' + None\n\nSomewhere... probably one of your entity fields is None\n" ]
[ 1 ]
[]
[]
[ "database", "google_app_engine", "model", "python" ]
stackoverflow_0006271587_database_google_app_engine_model_python.txt
Q: Financial Charts / Graphs in Ruby or Python What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart. http://en.wikipedia.org/wiki/Op...
Financial Charts / Graphs in Ruby or Python
What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart. http://en.wikipedia.org/wiki/Open-high-low-close_chart (but I don't need the mov...
[ "You can use matplotlib and the the optional bottom parameter of matplotlib.pyplot.bar. You can then use line plot to indicate the opening and closing prices:\nFor example:\n#!/usr/bin/env python\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import lines\n\nimport random\n\n\ndeltas = [4, 6,...
[ 18, 8, 4, 4, 1, 0, 0, 0 ]
[]
[]
[ "charts", "financial", "graph", "python", "ruby" ]
stackoverflow_0001089307_charts_financial_graph_python_ruby.txt
Q: Sort list elements belonging to enumerable object I have a list of possible types of products : PRODUCT_TYPE_CHOICES = [ (PRODUCT_UNISEX, _(u"Unisex")), (PRODUCT_MENS, _(u"Mens")), (PRODUCT_WOMANS, _(u"Womans")), ] And a second list containing some Product objects. all_products = [Product1, Product2, ...
Sort list elements belonging to enumerable object
I have a list of possible types of products : PRODUCT_TYPE_CHOICES = [ (PRODUCT_UNISEX, _(u"Unisex")), (PRODUCT_MENS, _(u"Mens")), (PRODUCT_WOMANS, _(u"Womans")), ] And a second list containing some Product objects. all_products = [Product1, Product2, Product3, ..., ProductN] Each product has a field/prop...
[ "1 liner:\nzip([sum(t) for t in zip( \\\n *[(1,0,0) if p.type==PRODUCT_UNISEX \\\n else (0,1,0) if p.type==PRODUCT_MENS \\\n else (0,0,1) for p in products] \\\n ) \\\n ], \\\n ['Unisex','Mens','Womans'])\n\nOr in a classic way:\ndict = {}\n...
[ 0 ]
[]
[]
[ "django", "enumerable", "python" ]
stackoverflow_0006272131_django_enumerable_python.txt
Q: How can I create a non-http proxy with Twisted How can I create a non-http proxy with Twisted. Instead I would like to do it for the Terraria protocol which is made entirely of binary data. I see that they have a built-in proxy for HTTP connections, but this application needs to act more like an entry point which ...
How can I create a non-http proxy with Twisted
How can I create a non-http proxy with Twisted. Instead I would like to do it for the Terraria protocol which is made entirely of binary data. I see that they have a built-in proxy for HTTP connections, but this application needs to act more like an entry point which is forwarded to a set server (almost like a BNC on I...
[ "There are several different ways to create proxies in Twisted. The basic technique is built on peering, by taking two different protocols, on two different ports, and somehow gluing them together so that they can exchange data with each other.\nThe simplest proxy is a port-forwarder. Twisted ships with a port-forw...
[ 6 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0006271493_python_twisted.txt
Q: How to hide the cursor in windows when dragging and dropping (possibly in python, or another language) After hours of searching google, with little luck, I'm wondering if anybody knows how to either hide the cursor, or set a custom cursor (which could be made blank) in Windows when dragging and dropping. I'm writi...
How to hide the cursor in windows when dragging and dropping (possibly in python, or another language)
After hours of searching google, with little luck, I'm wondering if anybody knows how to either hide the cursor, or set a custom cursor (which could be made blank) in Windows when dragging and dropping. I'm writing a program which draws its own mouse using openGL, and normally the mouse hides just fine, but when I drag...
[ "Windows SDK:\n\nShowCursor: This function sets an\n internal display counter that\n determines whether the cursor should\n be displayed. The cursor is displayed\n only if the display count is greater\n than or equal to 0.\n\nSo you should try the equivalent of:\nwhile ShowCursor(False) >= 0 do ;\n\n" ]
[ 0 ]
[]
[]
[ "com", "python", "winapi", "windows" ]
stackoverflow_0006272428_com_python_winapi_windows.txt
Q: pywin32 excel find how many sheets are in a workbook and index by number? How do I find the number of sheets in a workbook in pywin32? Also, is there ANY documentation on how to use pywin32 with excel? I can't seem to even find code examples or anything. A: from win32com.client import Dispatch xl= Dispatch("Ex...
pywin32 excel find how many sheets are in a workbook and index by number?
How do I find the number of sheets in a workbook in pywin32? Also, is there ANY documentation on how to use pywin32 with excel? I can't seem to even find code examples or anything.
[ "from win32com.client import Dispatch\n\nxl= Dispatch(\"Excel.Application\")\nxl.Visible = True # otherwise excel is hidden\n\n# newest excel does not accept forward slash in path\nwb = xl.Workbooks.Open(r'U:\\Example.xls')\nprint \"count of sheets:\", wb.Sheets.Count\nfor sh in wb.Sheets:\n print sh.Name\nwb.Cl...
[ 6 ]
[]
[]
[ "excel", "python", "pywin32" ]
stackoverflow_0006272225_excel_python_pywin32.txt
Q: Compoud charts with python I want to generate compound charts (e.g: Bar+line) from my database using python. How can i do this ? Thanks in Advance A: You might want to look up Matplotlib. A: This is extremely simple to do using matplotlib using the plot and bar methods: http://matplotlib.sourceforge.net/api/py...
Compoud charts with python
I want to generate compound charts (e.g: Bar+line) from my database using python. How can i do this ? Thanks in Advance
[ "You might want to look up Matplotlib.\n", "This is extremely simple to do using matplotlib using the plot and bar methods:\nhttp://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.plot\nhttp://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar\nThe matplotlib gallery is usually ...
[ 3, 3, 1, 0 ]
[]
[]
[ "charts", "python" ]
stackoverflow_0005693151_charts_python.txt
Q: How to represent one-to-one relationship in App Engine Say you have a concept of "user" records that you'd like to store in the data store. class User (db.Model): first_name = db.StringProperty() last_name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) twitter_oauth_token = db.Strin...
How to represent one-to-one relationship in App Engine
Say you have a concept of "user" records that you'd like to store in the data store. class User (db.Model): first_name = db.StringProperty() last_name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) twitter_oauth_token = db.StringProperty() twitter_oauth_secret = db.StringProperty() Th...
[ "In this specific case, your best option is probably to make the UserTwitterOauth entity a child of the User entity with a well-known key name, like so:\nmy_user = User(first_name=\"John\", last_name=\"Smith\")\nmy_user.put()\nextra_info = UserTwitterOauth(parent=my_user, key_name=\"UserTwitterOauth\")\nextra_info....
[ 6, 0 ]
[]
[]
[ "bigtable", "google_app_engine", "python", "schema_design" ]
stackoverflow_0006268434_bigtable_google_app_engine_python_schema_design.txt
Q: Finding the number of characters in the ith sentence of a given text file using Python When run, the cursor simple blinks on the command line to the left and nothing happens. Could anyone tell me why it does not do what is expected? Thanks in anticipation. The code is as follows: import sys i=3 try: text =...
Finding the number of characters in the ith sentence of a given text file using Python
When run, the cursor simple blinks on the command line to the left and nothing happens. Could anyone tell me why it does not do what is expected? Thanks in anticipation. The code is as follows: import sys i=3 try: text = open(sys.argv[1], 'r') except IOError: print 'Cannot open file %s for reading' % filena...
[ "I see one problem: \nwhile char != '.' or '!' or '?':\nShould be:\nwhile char != '.' and char != '!' and char != '?':\n... or at least something logically equivalent, but cleaner and more delicious-looking. In the former case, Python would be trying to evaluate char != '.', and then evaluate '!', and evaluate '?',...
[ 4, 0 ]
[]
[]
[ "python", "text_processing" ]
stackoverflow_0006272804_python_text_processing.txt
Q: Implementing recursion with a deep copy How can I implement recursion in a deep copy function object? This is the relevant code (if you want more then please ask): PS: I would like the recursion to iterate through a filtered list of references. The goal is to download and insert any missing objects. copy.py from p...
Implementing recursion with a deep copy
How can I implement recursion in a deep copy function object? This is the relevant code (if you want more then please ask): PS: I would like the recursion to iterate through a filtered list of references. The goal is to download and insert any missing objects. copy.py from put import putter class copier: def __init_...
[ "Check out the documentation for copy.deepcopy, if you can implement what you want with __getinitargs__(), __getstate__() and __setstate__(), then that will save you a lot of grief. Otherwise, you will need to reimplement it yourself, it should look something like:\ndef deepcopyif(obj, shouldcopyprop):\n copied ...
[ 2 ]
[]
[]
[ "deep_copy", "distributed_computing", "pickle", "python" ]
stackoverflow_0006273026_deep_copy_distributed_computing_pickle_python.txt
Q: Is there a Python editor with python built in? I need an editor with python built into it. Currently I use blender so I do not have install python. Blender comes with the python32.dll to use python. is there another editor out there that I can execute python commands without it being installed? A: I don't unders...
Is there a Python editor with python built in?
I need an editor with python built into it. Currently I use blender so I do not have install python. Blender comes with the python32.dll to use python. is there another editor out there that I can execute python commands without it being installed?
[ "I don't understand the question fully either. Why NOT install python? But if the question is how to be able to edit and run python on machines without installing it, there's Movable Python (http://www.voidspace.org.uk/python/movpy/) with a small fee to purchase and Portable Python (http://www.portablepython.com/wi...
[ 0, 0 ]
[]
[]
[ "editor", "python" ]
stackoverflow_0006074030_editor_python.txt
Q: Python class function being called from another class function returning None OK I have two classes: PMBMessage and PPConsume PPConsume instanciated PMBMessage and then calls a function from PMBMessage to get a string returned. Here is the code from PPConsume: def handle(self, ch, delivery_tag, body): print "G...
Python class function being called from another class function returning None
OK I have two classes: PMBMessage and PPConsume PPConsume instanciated PMBMessage and then calls a function from PMBMessage to get a string returned. Here is the code from PPConsume: def handle(self, ch, delivery_tag, body): print "Got: " + body pmbmessage = PMBMessage(body) msg_format_id = pmbmessage.get_h...
[ "The recursive call needs to return its return value again, i.e.\n...\nprint \"HEY WE WENT THIS WAY\"\nreturn self.get_header_attribute(attr)\n\nOtherwise the return value is simply dropped, and after the recursive call has returned, control reaches the end of the function and None is implicitly returned.\n" ]
[ 3 ]
[]
[]
[ "class", "null", "python" ]
stackoverflow_0006273265_class_null_python.txt
Q: Is there an expression which dictates which form of delete is used (implicite versus complete)? Let's say I have class A(<class ...>): pass. Should I be explicitly calling del for a deep delete? Let me be more specific: What happens just before a fork merge with a current thread? When a thread is being interwoven ...
Is there an expression which dictates which form of delete is used (implicite versus complete)?
Let's say I have class A(<class ...>): pass. Should I be explicitly calling del for a deep delete? Let me be more specific: What happens just before a fork merge with a current thread? When a thread is being interwoven with another, does it thrash or use a pointer? EDIT Aha! http://docs.python.org/library/gc.html
[ "The del keyword doesn't actually explicitly remove an object. It decrements the reference count, and then the garbage collector cleans up the memory if nothing else is using it. It's useful when you have a block of code that will be running for a long time, and a variable that's eating up a lot of memory that you ...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006273622_python.txt
Q: Find phase difference between two (inharmonic) waves I have two datasets listing the average voltage outputs of two assemblies of neural networks at times t, that look something like this: A = [-80.0, -80.0, -80.0, -80.0, -80.0, -80.0, -79.58, -79.55, -79.08, -78.95, -78.77, -78.45,-77.75, -77.18, -77.08, -77.18, ...
Find phase difference between two (inharmonic) waves
I have two datasets listing the average voltage outputs of two assemblies of neural networks at times t, that look something like this: A = [-80.0, -80.0, -80.0, -80.0, -80.0, -80.0, -79.58, -79.55, -79.08, -78.95, -78.77, -78.45,-77.75, -77.18, -77.08, -77.18, -77.16, -76.6, -76.34, -76.35] B = [-80.0, -80.0, -80.0, ...
[ "Perhaps you are looking for the cross-correlation:\nscipy.​signal.​signaltools.correlate(A, B)\n\nThe position of the peak in the cross-correlation will be an estimate of the phase difference. \nEDIT 3: Update now that I have looked at the real data files. There are two reasons that you find a phase shift of zero....
[ 38, 3 ]
[]
[]
[ "neural_network", "numpy", "physics", "python", "scipy" ]
stackoverflow_0006157791_neural_network_numpy_physics_python_scipy.txt
Q: shotgun for django? I like shotgun server. but is there any similar package available for Django development ? shotgun reloads the server every time the code is changed , thus making the development process easier .. I am looking for a similar kind of program for Django development . Thanks ! A: You could use ...
shotgun for django?
I like shotgun server. but is there any similar package available for Django development ? shotgun reloads the server every time the code is changed , thus making the development process easier .. I am looking for a similar kind of program for Django development . Thanks !
[ "You could use the Django Dev server that is supplied. OR you could use something similar to this:\nhttp://jeffbaier.com/articles/installing-django-on-an-ubuntu-linux-server/\nThis will reload the server at each request, but make sure to turn it off before production!\nEdit:\nThe part you really need is just this:...
[ 1 ]
[]
[]
[ "django", "python", "shotgun", "sinatra" ]
stackoverflow_0006273695_django_python_shotgun_sinatra.txt
Q: Improving Python/django view code I am very new to Python/Django and programming in general. With the limited tools in my programming bag, I have written three views functions for after a user registers: it allows the user to add information and upload a thumbnail before activating his account. I have posted the c...
Improving Python/django view code
I am very new to Python/Django and programming in general. With the limited tools in my programming bag, I have written three views functions for after a user registers: it allows the user to add information and upload a thumbnail before activating his account. I have posted the code that I have written so far so that ...
[ "A few things I'd do differently:\n\nIn your models.py you use the choices argument for your graduation field, but don't define the choices on the model, and don't use all caps which is usually used to denote a constant in Python. This would be better:\nclass UserProfile(models.Model):\n ...\n CHOICES = [('ch...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006245755_django_python.txt
Q: numpy.savetxt Problems with 1D array writing I'm trying to use numpy's savetxt function to generate a bunch of files as inputs for another piece of software. I'm trying to write an array of the form: a=np.array([1,2,3,4,...]) a.shape=>(1,n) to a text file with the formatting 1,2,3,4,... when I enter the command n...
numpy.savetxt Problems with 1D array writing
I'm trying to use numpy's savetxt function to generate a bunch of files as inputs for another piece of software. I'm trying to write an array of the form: a=np.array([1,2,3,4,...]) a.shape=>(1,n) to a text file with the formatting 1,2,3,4,... when I enter the command np.savetxt('test.csv',a,fmt='%d',delimiter=',') I ...
[ "There are different ways to fix this. The one closest to your current approach is:\nnp.savetxt('test.csv', a[None], fmt='%d', delimiter=',')\n\ni.e. add the slicing [None] to your array to make it two-dimensional with only a single line.\n", "If you only want to save a 1D array, it's actually a lot faster to us...
[ 12, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006268657_numpy_python.txt
Q: How to upload data with key_name by Google App Engine bulkloader I can upload data, but key_name is empty. How can I use the 'id' in the CSV as the key_name on datastore? I'like to use 'id' as the key_name, because other data uses the 'id' as the foreign key. I'm new to Google App Engine. This is the CSV data. "id...
How to upload data with key_name by Google App Engine bulkloader
I can upload data, but key_name is empty. How can I use the 'id' in the CSV as the key_name on datastore? I'like to use 'id' as the key_name, because other data uses the 'id' as the foreign key. I'm new to Google App Engine. This is the CSV data. "id","name" "1","USA" "2","France" "3","Italy" This is the YAML - model:...
[ "Try this:\n- import: google.appengine.ext.bulkload.transform\n- model: model.testcountry.TestCountry\n connector: csv\n connector_options:\n encoding: utf-8\n columns: from_header\n property_map:\n - property: __key__\n external_name: id\n import_transform: transform.create_foreign_key('Tes...
[ 1 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0006273688_bulkloader_google_app_engine_python.txt
Q: Python Inheritance question I have a class of boxes that need to move around in a grid, but need to access that grid's coordinates in its methods. I don't want my classes to inherit the grid unless they need to. Do I need to pass the grid to the classes as a parameter, or make the box classes inherit from the grid...
Python Inheritance question
I have a class of boxes that need to move around in a grid, but need to access that grid's coordinates in its methods. I don't want my classes to inherit the grid unless they need to. Do I need to pass the grid to the classes as a parameter, or make the box classes inherit from the grid class? Thanks. This is the edit....
[ "General rule would be parameter.\nThe question is is-a vs. has-a:\n Is the box a grid? \n yes: # if so, then is it really a box???\n The box should inherit grid\n no:\n The box should get a reference to the grid \n #(generally through a setter or constructor parameter).\n\nEdit\n...
[ 3, 0, 0, 0 ]
[]
[]
[ "class", "inheritance", "python" ]
stackoverflow_0006273946_class_inheritance_python.txt
Q: A faster way of comparing two lists of point-tuples? I have two lists (which may or may not be the same length). In each list, are a series of tuples of two points (basically X, Y values). I am comparing the two lists against each other to find two points with similar point values. I have tried list comprehension ...
A faster way of comparing two lists of point-tuples?
I have two lists (which may or may not be the same length). In each list, are a series of tuples of two points (basically X, Y values). I am comparing the two lists against each other to find two points with similar point values. I have tried list comprehension techniques, but it got really confusing with the nested tu...
[ "If these lists are large, I would suggest finding a faster algorithm...\nI would start by sorting both lists of pairs by the sum of the (x,y) in the pair. (Because two points can be close only if their sums are close.)\nFor any point in the first list, that will severely limit the range you need to search in the ...
[ 2, 2, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0006273226_list_comprehension_python.txt
Q: Translate several lines of C to Python I need just a little bit of help translating C to python. I have not used c++ in about 4 years now, and when I used it, I only new the basics. the context of this snippet is reading a file and creating a checksum int ff7_checksum( void* qw ) { int i = 0, t, d; long r = ...
Translate several lines of C to Python
I need just a little bit of help translating C to python. I have not used c++ in about 4 years now, and when I used it, I only new the basics. the context of this snippet is reading a file and creating a checksum int ff7_checksum( void* qw ) { int i = 0, t, d; long r = 0xFFFF, len = 4336; long pbit = 0x8000; ...
[ "I assume that qw points at a buffer with a known size (4336) and that does not really represent a string (i.e. it might contain \\0 characters that should still be processed).\nHowever, in Python (2.x), we still generally model this as a string, since the string may contain embedded \\0 bytes, and knows its own le...
[ 0 ]
[]
[]
[ "c", "python", "translation" ]
stackoverflow_0006273279_c_python_translation.txt
Q: How to get font of a HTML node with python? Now I use lxml to parse HTML in python. But I haven't found any API to get font information of a text node. Is there any librafy to do that? Thanks very much! A: You can't get this information from the text nodes in the HTML, because it isn't there.
How to get font of a HTML node with python?
Now I use lxml to parse HTML in python. But I haven't found any API to get font information of a text node. Is there any librafy to do that? Thanks very much!
[ "You can't get this information from the text nodes in the HTML, because it isn't there.\n" ]
[ 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0006273635_html_python.txt
Q: Explaining this primes generator function, i cannot understand [python] def primes(n): if n==2: return [2] elif n<2: return [] s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)/2 s[j]=0 while j<...
Explaining this primes generator function, i cannot understand [python]
def primes(n): if n==2: return [2] elif n<2: return [] s=range(3,n+1,2) mroot = n ** 0.5 half=(n+1)/2-1 i=0 m=3 while m <= mroot: if s[i]: j=(m*m-3)/2 s[j]=0 while j<half: s[j]=0 j+=m i=i+1 m=2*i...
[ "A line-by-line breakdown:\ndef primes(n): \n if n==2: return [2]\n\nThis function returns a list of primes <= n. So if n == 2, that list contains only 2. Easy enough.\n elif n<2: return []\n\nHere again, there are no prime numbers below 2, so return an empty list.\n s=range(3,n+1,2)\n\nSo s is a list of o...
[ 5, 2, 2 ]
[]
[]
[ "math", "primes", "python" ]
stackoverflow_0006274215_math_primes_python.txt
Q: Python: How to set breakpoints on mac with IDLE debugger? I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. ...
Python: How to set breakpoints on mac with IDLE debugger?
I have access to both a PC and a mac for a python class. I find I am unable to set breakpoints in the IDLE debugger in the mac (works fine on the PC). I've tried "ctrl-click" and configuring the touchpad to recognize two taps at once as a secondary click. I don't have a mouse for the mac, just the touchpad. MAC OS 10....
[ "If you put the following two lines:\nimport pdb\npdb.set_trace()\n\nPython will import the Python De Bugger and you will be in the interactive interpreter at this point in the code. It will evaluate all your Python expressions normally.\nThe most important commands are:\n\ns - step (forward one command)\nc - conti...
[ 3, 1, 1, 0 ]
[]
[]
[ "macos", "python", "python_idle" ]
stackoverflow_0001081536_macos_python_python_idle.txt
Q: Python Graphing Utility for GUI with Animations I am trying to create a GUI interface in VB to track... oh, nevermind. Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom i...
Python Graphing Utility for GUI with Animations
I am trying to create a GUI interface in VB to track... oh, nevermind. Basically, I want to create a GUI in python to display data, but I am finding that mathplotlib is not suiting my needs. I would like to be able to highlight certain datapoints, have more freedom in the text drawn to the screen, have animations on da...
[ "I haven't used it myself but Chaco seems to fit some of your needs. It is more interactive than matplotlib and can be used to make quite interactive applications. \n\nChaco is a Python plotting application toolkit that facilitates writing plotting applications at all levels of complexity, from simple scripts with...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001172776_python.txt
Q: Calling Python function from MATLAB Possible Duplicate: Call Python function from MATLAB I need to call a Python function from a MATLAB environment. Is it possible? Let's assume, I have the following Python code: def squared(x): y = x * x return y How do I call squared(3) from MATLAB workspace/code and ...
Calling Python function from MATLAB
Possible Duplicate: Call Python function from MATLAB I need to call a Python function from a MATLAB environment. Is it possible? Let's assume, I have the following Python code: def squared(x): y = x * x return y How do I call squared(3) from MATLAB workspace/code and get 9?
[ "I have never done this before, so someone else will have to provide a 'real' answer, but\nI can offer this.\nI often call the shell from MATLAB on my Linux machine, with an exclamation point, >>!{comm}\nSo I suppose you could have a shell script that calls python and call the script from MATLAB.\nwbg\n" ]
[ 1 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0006274731_matlab_python.txt
Q: django-tables2 linkColumn accessor I have been using django-tables2 which I like, but i run into some problems I am trying to make a table in which cells link out to a different table, or an outside link the example in the documentation is : models.py class Person(models.Model): name = models.CharField(max_l...
django-tables2 linkColumn accessor
I have been using django-tables2 which I like, but i run into some problems I am trying to make a table in which cells link out to a different table, or an outside link the example in the documentation is : models.py class Person(models.Model): name = models.CharField(max_length=200) urls.py urlpatterns = patte...
[ "args=[A('pk')] is the primary key of the model from which you're displaying the table. Your example would create a column 'Name' with the cell content <a href=\"/people/pk\"></a> pk would be the primary key (number).\nThe view would be views.people_detail and the template would be whatever you've defined in this v...
[ 3 ]
[]
[]
[ "accessor", "django", "django_tables2", "python" ]
stackoverflow_0006157101_accessor_django_django_tables2_python.txt
Q: Why doesn't this work (sqlite, python) I tried to do this in the interpreter and I can get it to work but inside my function it doesn't What I'm trying to do: cursor = dbconnect.cursor() cursor.execute("""SELECT * FROM credits WHERE phone = ?""",(phone,)) data = cursor.fetchone() firstname = data[1] #the db is set...
Why doesn't this work (sqlite, python)
I tried to do this in the interpreter and I can get it to work but inside my function it doesn't What I'm trying to do: cursor = dbconnect.cursor() cursor.execute("""SELECT * FROM credits WHERE phone = ?""",(phone,)) data = cursor.fetchone() firstname = data[1] #the db is set as firstname in position 1 after the id(pri...
[ "I think the problem is that your function doesn't check if there was a matching row in the database. you will get this error if no row is being returned:\n#!/usr/bin/python\ntry:\n import sqlite3\nexcept:\n from pysqlite2 import dbapi2 as sqlite3\n\n#prepare testcase \ndb=\"/tmp/soverflow.sqlite\"\ndbconn...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006274735_python_sqlite.txt
Q: Match a string that does not end with a list of known strings I want to match street names, which could come in forms of " St/Ave/Road". The postfix may not be exist at all, so it may just be "1st". I also want to know what the postfix is. What is a suitable regex for it? I tried: (.+)(\s+(St|Ave|Road))? But it s...
Match a string that does not end with a list of known strings
I want to match street names, which could come in forms of " St/Ave/Road". The postfix may not be exist at all, so it may just be "1st". I also want to know what the postfix is. What is a suitable regex for it? I tried: (.+)(\s+(St|Ave|Road))? But it seems like the first group greedily matches the entire string. I tri...
[ "Just make your first group non-greedy by adding a question mark:\n(.+?)(\\s+(St|Ave|Road))?\n\n", "As an alternative to regex-based solutions, how about:\nsuffix = s.split(' ')[-1]\nif suffix in ('St', 'Ave', 'Road'):\n print 'suffix is', suffix\nelse:\n print 'no suffix'\n\nIf you do have to use regular expre...
[ 4, 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006275009_python_regex.txt
Q: using itertools to reduce the complexity of four "for" stmt? I have list 4 lists: list1, list2, list3, list4 = range(0,4), range(4,9), range(8,15), range(2,16) # just using range() generate sample data I can list all the items combination by sequence list1_item, list2_item, list3_item, list4_item via below code...
using itertools to reduce the complexity of four "for" stmt?
I have list 4 lists: list1, list2, list3, list4 = range(0,4), range(4,9), range(8,15), range(2,16) # just using range() generate sample data I can list all the items combination by sequence list1_item, list2_item, list3_item, list4_item via below code: for item1 in list1: for item2 in list2: for item3 in...
[ "Yes, you can:\nfor n in itertools.product(list1, list2, list3, list4):\n print n\n\n(n will be a tuple instead of a list).\n", "I think what you want is itertools.product\nimport itertools\nret = list ( itertools.product( list1, list2, list3, list4 ) )\n\nAnd ret is the result.\n" ]
[ 5, 1 ]
[]
[]
[ "combinations", "python", "python_itertools" ]
stackoverflow_0006275003_combinations_python_python_itertools.txt
Q: Installing python library to a custom location? I want to use a couple of third party django packages for my application. So, I want to install each package locally for that application (or my whole project). The python custom installation instructions look a bit scary - how do I do this as simply as possible? A:...
Installing python library to a custom location?
I want to use a couple of third party django packages for my application. So, I want to install each package locally for that application (or my whole project). The python custom installation instructions look a bit scary - how do I do this as simply as possible?
[ "You can just put the library module into your project folder because your project folder will be in the PYTHONPATH automatically when running via manage.py runserver or your wsgi script will point to it when running on production.\nUsually all python packages are packaged like this:\npackage directory\n module ...
[ 3, 2, 0 ]
[]
[]
[ "django", "installation", "python" ]
stackoverflow_0006274787_django_installation_python.txt
Q: pyramid - threadlocal doesn't work inside Response's app_iter With the following sample code: from webob import Response from paste.httpserver import serve def test_iter(): from pyramid import threadlocal yield 'current request: %s' % threadlocal.get_current_request() def hello_world(request): return...
pyramid - threadlocal doesn't work inside Response's app_iter
With the following sample code: from webob import Response from paste.httpserver import serve def test_iter(): from pyramid import threadlocal yield 'current request: %s' % threadlocal.get_current_request() def hello_world(request): return Response(app_iter=test_iter()) if __name__ == '__main__': ...
[ "Maybe mistake?\nreturn Response(app_iter=test_iter())\n\nor\nreturn Response(app_iter=test_iter)\n\n", "According to the Pyramid docs the thread-local stack shouldn't be popped until after app_iter is used (see steps 16 and 18), although I see the same behavior as you when I try to run your example. Since the d...
[ 0, 0 ]
[]
[]
[ "pyramid", "python", "thread_local", "webob" ]
stackoverflow_0006275831_pyramid_python_thread_local_webob.txt
Q: Superclass of bytes and bytearray? I'm making a function which will accept either an Unicode string or a bytes (or bytearray) object. I want to make sure only those types get passed. I know I can check whether something is a string by doing isinstance(x, str), and I know I can write isinstance(x, bytes) or isinsta...
Superclass of bytes and bytearray?
I'm making a function which will accept either an Unicode string or a bytes (or bytearray) object. I want to make sure only those types get passed. I know I can check whether something is a string by doing isinstance(x, str), and I know I can write isinstance(x, bytes) or isinstance(x, bytearray). Is there a more conci...
[ "There is no common base class except for object:\n>>> bytearray.__base__\n<class 'object'>\n>>> bytes.__base__\n<class 'object'>\n\nDon't check for the type. Let the user pass parameters of whatever type she desires. If the type does not have the required interface, your code will fail anyway.\n", "You can use...
[ 8, 4, 2 ]
[]
[]
[ "byte", "python", "python_3.x" ]
stackoverflow_0006272091_byte_python_python_3.x.txt
Q: How to save tkinter table as an image I am drawing a table using tKinter. I was wondering if there was a way to export the table as an image. for r in range(numberOfRows): for c in range(numberOfColumns): l = tk.Label(root, text=someText, relief="solid", height=5, width=10, bg="white") l.gr...
How to save tkinter table as an image
I am drawing a table using tKinter. I was wondering if there was a way to export the table as an image. for r in range(numberOfRows): for c in range(numberOfColumns): l = tk.Label(root, text=someText, relief="solid", height=5, width=10, bg="white") l.grid(row=r, column=c) Thanks.
[ "You can always go the draw-it-yourself way. There are several modules out there that allow you draw an image. Take the coordinates of your table, column width and so on and draw it into the image.\n", "You can take a screen shot of it. \nimport PIL.ImageGrab as ImageGrab\n\nscreenshot = ImageGrab.grab().load()\n...
[ 1, 0 ]
[]
[]
[ "draw", "python", "save", "tkinter" ]
stackoverflow_0006267822_draw_python_save_tkinter.txt
Q: IPv6 regexp python Hello i need to match a IPv6 address using a python script like : but it seems not working even the pattern is correct ? data="Client IPv6: 2001:470:9b36:1::2" pattern="Client IPv6: (\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\Z)|(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\Z)|(\A([0-9a-f]{1,...
IPv6 regexp python
Hello i need to match a IPv6 address using a python script like : but it seems not working even the pattern is correct ? data="Client IPv6: 2001:470:9b36:1::2" pattern="Client IPv6: (\A([0-9a-f]{1,4}:){1,1}(:[0-9a-f]{1,4}){1,6}\Z)|(\A([0-9a-f]{1,4}:){1,2}(:[0-9a-f]{1,4}){1,5}\Z)|(\A([0-9a-f]{1,4}:){1,3}(:[0-9a-f]{1,4}...
[ "I like this answer (assuming it is working) 4017219#4017219\nTo extract only the IP address part from your example to use it with the linked answer you can use this:\npattern=\"Client IPv6: (.*)$\"\n\nlooks much simpler to me.\n", "The problem is in the extra data you are adding to it, perhaps this is better:\nd...
[ 1, 0 ]
[]
[]
[ "ipv6", "python", "regex" ]
stackoverflow_0006276115_ipv6_python_regex.txt
Q: automate navigation of a JavaScript powered website I need to automate navigation around a JavaScript powered website in Python so I can scrape some content. I came across Chickenfoot, which is a FireFox extension that gives me a programming interface to the browser. Do you know of other solutions? A: WWW::Mecha...
automate navigation of a JavaScript powered website
I need to automate navigation around a JavaScript powered website in Python so I can scrape some content. I came across Chickenfoot, which is a FireFox extension that gives me a programming interface to the browser. Do you know of other solutions?
[ "WWW::Mechanize has several extensions/compatible replacements to handle JavaScript: WWW::Mechanize::FireFox, WWW::Mechanize::Plugin::JavaScript/WWW::Scripter::Plugin::JavaScript, Mozilla::Mechanize, Gtk2::WebKit::Mechanize, Win32::IE::Mechanize.\n", "Check out Selenium. \n", "You can automate Internet Explore...
[ 3, 2, 2, 0 ]
[]
[]
[ "javascript", "python", "web" ]
stackoverflow_0001698285_javascript_python_web.txt
Q: Can anyone help me check this python code? I met a problem when I want to write a simple permutation code, def permutation(Ori, Curr, used): if len(Ori) == len(Curr): #print Curr return for i in xrange(len(Ori)): if used[i]: continue used[i] = True Curr.append(Ori[i]) ...
Can anyone help me check this python code?
I met a problem when I want to write a simple permutation code, def permutation(Ori, Curr, used): if len(Ori) == len(Curr): #print Curr return for i in xrange(len(Ori)): if used[i]: continue used[i] = True Curr.append(Ori[i]) print Curr,i," after append" permuta...
[ "At the line\npermutation(Ori, Curr, used) # further level\n\nyou're passing pointers to the lists, not a copy of the lists. Doing this, when permutation modifies Curr, you see the modifications in the calling context. One possible solution is to call\npermutation(Ori, Curr[:], used) # further level\n\nwhich ...
[ 4, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0006275276_algorithm_python.txt
Q: having problem with the submit form button with selenium rc and python So i am trying to automate a simple test using selenium rc and python. A Sign Up: sel = self.selenium sel.open("/") sel.click("link=Get Started for free") sel.wait_for_page_to_load("60000") sel.type("full_name", "blah blah") s...
having problem with the submit form button with selenium rc and python
So i am trying to automate a simple test using selenium rc and python. A Sign Up: sel = self.selenium sel.open("/") sel.click("link=Get Started for free") sel.wait_for_page_to_load("60000") sel.type("full_name", "blah blah") sel.type("identity", "blah blah") sel.select("gender","label=Male") sel...
[ "One reason might be that the page is doing an Ajax call and not a full page refresh.\n", "After the sel.click() what happens on the page?\n", "The second wait_for_page_to_load seems suspicious. Usually when you fill out a form, the page doesn't get reloaded - can it be you're running into a timeout and your co...
[ 0, 0, 0 ]
[]
[]
[ "ajax", "python", "selenium_rc" ]
stackoverflow_0006233563_ajax_python_selenium_rc.txt
Q: Regex extract numer into group I have simple html code: <span class="someclass" title="4.5 stars"></span> or it could be: <span class="someclass" title="5 stars"></span> I used ((\d+\.\d+)|(\d+)) star but it extracted me 3 groups, I need one with numeric value. How can I extract 4.5 and 5 in both strings using R...
Regex extract numer into group
I have simple html code: <span class="someclass" title="4.5 stars"></span> or it could be: <span class="someclass" title="5 stars"></span> I used ((\d+\.\d+)|(\d+)) star but it extracted me 3 groups, I need one with numeric value. How can I extract 4.5 and 5 in both strings using Regex in one group? Thanks!
[ "Try removing the inner parentheses:\n(\\d+\\.\\d+|\\d+) star\n\nAlso, you may wish to consider using an HTML parser to extract the attributes first rather than applying the regular expression directly to the raw HTML.\n", "You can make groups non capturing by adding a ?: after the opening bracket like this\n((?:...
[ 4, 1, 0 ]
[]
[]
[ "asp.net", "c#", "javascript", "python", "regex" ]
stackoverflow_0006276844_asp.net_c#_javascript_python_regex.txt
Q: What is the best way to fetch frequently changing data from the web? I have to download a text file every 20 seconds and process it as a string s=urlopen(url).read() This works but I've read that it's not very efficient. How would you do it? A: One way to save bandwidth would be to specify If-Modified-Since as ...
What is the best way to fetch frequently changing data from the web?
I have to download a text file every 20 seconds and process it as a string s=urlopen(url).read() This works but I've read that it's not very efficient. How would you do it?
[ "One way to save bandwidth would be to specify If-Modified-Since as part of your request, with the timestamp of the data that you already have. This way, if the data hasn't changed, you'd get a 304 Not Modified response back.\n\"Dive into Python\" seems to have an example of doing just that.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006274352_python.txt
Q: Django extends existing apps I installed app https://github.com/zerok/django-flatblocks, next I want to extend this app model https://github.com/zerok/django-flatblocks/blob/master/flatblocks/models.py. New models.py looks class MyFlatBlock(FlatBlock): my_field = models.CharField() How can I do this, whitout...
Django extends existing apps
I installed app https://github.com/zerok/django-flatblocks, next I want to extend this app model https://github.com/zerok/django-flatblocks/blob/master/flatblocks/models.py. New models.py looks class MyFlatBlock(FlatBlock): my_field = models.CharField() How can I do this, whitout coping all app (django-flatblocks...
[ "Create another model\nclass MyFlatBlock(models.Model):\n flat_block = models.OneToOneField(FlatBlock, related_name='extra')\n my_field = models.CharField()\n\nThen you will be able to use flatblock.extra.my_field (catching AttributeError if necessary).\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006276900_django_python.txt
Q: Which set of python libraries i should learn for AI and Data mining stuff I am learning python and django. I need to do extensive stuff for data parsing , stats , AI and data mining. There are many libraries available. so I want to know which SET I should learn. Currently I have the following SET in My Mind. Pars...
Which set of python libraries i should learn for AI and Data mining stuff
I am learning python and django. I need to do extensive stuff for data parsing , stats , AI and data mining. There are many libraries available. so I want to know which SET I should learn. Currently I have the following SET in My Mind. Parsing: Beautiful Soup Search Engine: Whoosh (Will it crawl and index the website...
[ "I find your requirements a little vague, but you might want to take a look at scikits.learn.\n", "In addition to the scikit cited by @aix, you might want to take a look at the following libraries:\n\nmlpy, an ML library for preprocessing, clustering, predictive classification, regression and feature selection.\n...
[ 2, 1 ]
[]
[]
[ "data_mining", "django", "python", "statistics" ]
stackoverflow_0006276744_data_mining_django_python_statistics.txt
Q: Operating on each generated entity of a list comprehension I am trying to generate a list using list comprehension and I want to do an operation on each generated entity. Something like: a=['1','2','3'] b=['a','b','c'] temp = [[x,y] for x in a for y in b] c=[] for t in temp: c.append("".join(t)) I tri...
Operating on each generated entity of a list comprehension
I am trying to generate a list using list comprehension and I want to do an operation on each generated entity. Something like: a=['1','2','3'] b=['a','b','c'] temp = [[x,y] for x in a for y in b] c=[] for t in temp: c.append("".join(t)) I tried something like: a=['1','2','3'] b=['a','b','c'] c = ",".join(...
[ ">>> [x + y for x in a for y in b]\n['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']\n\n", "The same using itertools:\nfrom itertools import product\n\nprint map(''.join, product(['1','2','3'],['a','b','c']))\n\nOR without:\nprint map(lambda y: map(lambda x: x+y, a), b)\n\nOR if you have a list of integers:...
[ 6, 4, 1 ]
[]
[]
[ "list_comprehension", "python", "split", "string" ]
stackoverflow_0006277158_list_comprehension_python_split_string.txt
Q: python regexp for a few thousand words I'm trying to find certain keywords in a string with python. The string is something like this: A was changed from B to C all I'm trying to find is the "to C" part, where C is one of many thousand words. This code builds the regexp string: pre_pad = 'to ' regex_string = Non...
python regexp for a few thousand words
I'm trying to find certain keywords in a string with python. The string is something like this: A was changed from B to C all I'm trying to find is the "to C" part, where C is one of many thousand words. This code builds the regexp string: pre_pad = 'to ' regex_string = None for i in words: if regex_string == Non...
[ "This is not supposed to be a task you can solve with a huge regexp and expect better performances than this:\npre_pad = 'to '\nmatches = []\n\nfor i in words:\n regex_string = '\\\\b%s%s(?!-)(?!_)\\\\b' % (pre_pad, i)\n for match in re.finditer(r\"%s\" % regex_string, text):\n matches.append([match, M...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "pattern_matching", "python", "regex" ]
stackoverflow_0006276796_pattern_matching_python_regex.txt
Q: How do I convert string version of an array into an actual array? s = "[[A, B],[E,R], [E,G]]" Is there a built-in way to convert this string into an array? (s[][]) A: There is, but in your case it will assume A B E R G to be variables, is this the case? If this is not the case you will need to do some extra for...
How do I convert string version of an array into an actual array?
s = "[[A, B],[E,R], [E,G]]" Is there a built-in way to convert this string into an array? (s[][])
[ "There is, but in your case it will assume A B E R G to be variables, is this the case?\nIf this is not the case you will need to do some extra formatting with the string.\nThis will work if the variables A B E R G are set:\ns = eval(s)\nIf the letters need to be strings you will have to do some kind of regexp to r...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006277372_python.txt
Q: One access token for OAuth using Twitter API I would like to use a one access token with OAuth to make calls to the Twitter API. I am NOT trying to build a web application but rather trying to harvest data from Twitter to perform some analysis. I would like to collect three types of data : followers, friends and u...
One access token for OAuth using Twitter API
I would like to use a one access token with OAuth to make calls to the Twitter API. I am NOT trying to build a web application but rather trying to harvest data from Twitter to perform some analysis. I would like to collect three types of data : followers, friends and user information including status updates. I am abl...
[ "I used the Python-Oauth2 library to achieve a one access token.\n", "You will get 350 requests per hour and access token. An access token basically represents the relationship between your application and a user. \nSo, as far as I know, for every user you are able to get to authorize your application - you will ...
[ 1, 0 ]
[]
[]
[ "oauth", "python", "twitter", "twitter_oauth" ]
stackoverflow_0006239042_oauth_python_twitter_twitter_oauth.txt