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: Init method; len() of self object def __init__(self,emps=str(""),l=[">"]): self.str=emps self.bl=l def fromFile(self,seqfile): opf=open(seqfile,'r') s=opf.read() opf.close() ...
Init method; len() of self object
def __init__(self,emps=str(""),l=[">"]): self.str=emps self.bl=l def fromFile(self,seqfile): opf=open(seqfile,'r') s=opf.read() opf.close() lisst=s.split(">"...
[ "Looks like a typo. You define self.bl in your __init__() routine, then try to access self.lb. \n(Also, emps=str(\"\") is redundant - emps=\"\" works just as well.)\nBut even if you correct that typo, the loop won't work:\nfor x in range(len(self.bl)): # This iterates over a list like [0, 1, 2, 3, ...]\n if x=...
[ 4 ]
[]
[]
[ "initialization", "python" ]
stackoverflow_0008480825_initialization_python.txt
Q: User input a function I'm writing a program that involves calculating the maximum of a user defined function, however if the user enters a function in terms of a variable such as x, i.e. input = x**2 + 2*x + 1 I (fairly expectedly) get an error as x is not defined. Does anyone know of an effective way to allow a ...
User input a function
I'm writing a program that involves calculating the maximum of a user defined function, however if the user enters a function in terms of a variable such as x, i.e. input = x**2 + 2*x + 1 I (fairly expectedly) get an error as x is not defined. Does anyone know of an effective way to allow a user to input a function in...
[ "If you are not worried about security much, simplest solution is to eval the expression e.g.\ndef calculate(value, function):\n x = value\n return eval(function)\n\nprint calculate(2, \"x**2 + 2*x + 1\")\nprint calculate(2, \"x**3 - x**2 + 1\")\n\noutput:\n9\n5\n\nYou can make it more secure by passing an em...
[ 2 ]
[]
[]
[ "function", "input", "python" ]
stackoverflow_0008481327_function_input_python.txt
Q: List a files in python and save it I can't save this output, maybe someone have the solution. I'm listing a directory and some singles files. But when I save the output just catch the directory files, and Not the singles files. My code: import os tosave = open('/tmp/list','ab') thesource = ["/etc/ssh","/var/log/s...
List a files in python and save it
I can't save this output, maybe someone have the solution. I'm listing a directory and some singles files. But when I save the output just catch the directory files, and Not the singles files. My code: import os tosave = open('/tmp/list','ab') thesource = ["/etc/ssh","/var/log/syslog","/etc/hosts"] for f in thesource:...
[ "You could try adding tosave.flush() at the end. It does cause problems sometimes. Sometimes, a flush call is required to empty the contents of the buffer into the file.\n", "Check if this works for you\nimport os\ntosave = open('/tmp/list','ab')\nthesource = [\"/etc/ssh\",\"/var/log/syslog\",\"/etc/hosts\"]\nfor...
[ 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "directory", "filesystems", "python" ]
stackoverflow_0008461802_directory_filesystems_python.txt
Q: How do I use optparse to just split the command-line arguments into options and positional args? For example, if I give test.py -a SOMETHING 1 2 3 after option parsing, I want two lists: >> print opt >> ['-a', 'SOMETHING'] >> print args >> ['1', '2', '3'] Is it possible to do this using optparse? A: Loo...
How do I use optparse to just split the command-line arguments into options and positional args?
For example, if I give test.py -a SOMETHING 1 2 3 after option parsing, I want two lists: >> print opt >> ['-a', 'SOMETHING'] >> print args >> ['1', '2', '3'] Is it possible to do this using optparse?
[ "Looking at the optparse documentation it seems like you can do this:\nimport optparse\n\nparser = optparse.OptionParser()\nparser.add_option(\"-a\", action=\"store\", type=\"string\", dest=\"a\")\n\n(opt, arg) = parser.parse_args()\nprint \"Opt:\", opt\nprint \"Arg:\", arg\n\nIf I run this using your command line ...
[ 3 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0008481509_optparse_python.txt
Q: M2Crypto: Is PKey a reference to a Public or a Private key? In the PKey class documentation of the M2Crypto python package (an OpenSSL wrapper for Python) it is said that PKey is a reference to a Public key. My opinion is instead that it's a reference to a Private Key because the init method of the PKey class call...
M2Crypto: Is PKey a reference to a Public or a Private key?
In the PKey class documentation of the M2Crypto python package (an OpenSSL wrapper for Python) it is said that PKey is a reference to a Public key. My opinion is instead that it's a reference to a Private Key because the init method of the PKey class calls the evp_pkey_new openssl function that, from this link: http://...
[ "The documentation for EVP_PKEY_new directly states its used to store private keys. And I'm lost as the original poster is since x509foo.get_pubkey() just returns a EVP.PKey instance and that storeing the instance as pem shows PRIVATE KEY. I can't pretend to know the intention of the M2Crypto team since many funct...
[ 2, 1 ]
[]
[]
[ "m2crypto", "openssl", "python" ]
stackoverflow_0002750008_m2crypto_openssl_python.txt
Q: What is the difference between numpy.fft and scipy.fftpack? Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better? A: SciPy does more: http://docs.scipy.org/doc/numpy/reference/routines.fft.html http://docs.scipy.org/doc/scipy/reference/fftpack.html# I...
What is the difference between numpy.fft and scipy.fftpack?
Is the later just a synonym of the former, or are they two different implementations of FFT? Which one is better?
[ "SciPy does more:\n\nhttp://docs.scipy.org/doc/numpy/reference/routines.fft.html\nhttp://docs.scipy.org/doc/scipy/reference/fftpack.html#\n\nIn addition, SciPy exports some of the NumPy features through its own interface, for example if you execute scipy.fftpack.helper.fftfreq and numpy.fft.helper.fftfreq you're ac...
[ 43, 20, 4 ]
[]
[]
[ "fft", "numpy", "python", "scipy" ]
stackoverflow_0006363154_fft_numpy_python_scipy.txt
Q: Is there a more Pythonic way of changing `None` to `[]` than Is there a more Pythonic way of doing this?: if self.name2info[name]['prereqs'] is None: self.name2info[name]['prereqs'] = [] if self.name2info[name]['optionals'] is None: self.name2info[name]['opti...
Is there a more Pythonic way of changing `None` to `[]` than
Is there a more Pythonic way of doing this?: if self.name2info[name]['prereqs'] is None: self.name2info[name]['prereqs'] = [] if self.name2info[name]['optionals'] is None: self.name2info[name]['optionals'] = [] The reason I do this is because I need to iterate ov...
[ "If you prefer this:\nself.name2info[name]['prereqs'] = self.name2info[name]['prereqs'] or []\n", "If you can't fix the input you could do this (becomes 'better' if you need to add more):\nfor prop in ['prereqs', 'optionals']:\n if self.name2info[name][prop] is None:\n self.name2info[name][prop] = []\n\...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "coding_style", "python", "syntax" ]
stackoverflow_0003198592_coding_style_python_syntax.txt
Q: Regular expression not working in django I am trying to set up a regular expression to redirect users to the url fieldguide/0e should they put anything other than 0e or 0E as the first two characters after the URL. The following is in my urls.py file: url(r'^fieldguide/(?P<IDmatch>0[eE]([0-9A-Fa-f]{0,14}))/$', 'tr...
Regular expression not working in django
I am trying to set up a regular expression to redirect users to the url fieldguide/0e should they put anything other than 0e or 0E as the first two characters after the URL. The following is in my urls.py file: url(r'^fieldguide/(?P<IDmatch>0[eE]([0-9A-Fa-f]{0,14}))/$', 'treeView', name='index'), url(r'^fieldguide/./$'...
[ "Django doesn't support verbose regexes - i.e. '(?x)' - because they make it really difficult to determine the url for a view (as opposed to a view from a url).\nThe good news is that Django urls are designed to cascade, so you can just do something like the following:\nurl(r'^fieldguide/(?P<IDmatch>0[eE]([0-9A-Fa-...
[ 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0008481734_django_django_urls_python.txt
Q: Ordering Django queryset by a @property I'm trying to order a query set by a property I defined in the model, but not sure the best way to do this. Here's the property: @property def name(self): if self.custom_name: return self.custom_name else: return self.module_object.name Essentially, ...
Ordering Django queryset by a @property
I'm trying to order a query set by a property I defined in the model, but not sure the best way to do this. Here's the property: @property def name(self): if self.custom_name: return self.custom_name else: return self.module_object.name Essentially, I'd like to do a: things = Thing.objects.all(...
[ "You can't do that because that property is not in MySQL, but in your python code. If you really want to do this, you can on the client-side(though it will be very slow):\nsorted(Thing.objects.all(), key=lambda t: t.name)\n\n", "order_by happens on the sql level, so it can't make use of properties, only field dat...
[ 41, 4, 4, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008478494_django_python.txt
Q: How do I get the body of a http response from a string containing the entire response, in Python? I got the entire HTTP response as a string but I want to extract just the body. I would prefer not to use an external library or reimplement the header parsing. Content-Type: text/xml Content-Length: 129 <?xml versi...
How do I get the body of a http response from a string containing the entire response, in Python?
I got the entire HTTP response as a string but I want to extract just the body. I would prefer not to use an external library or reimplement the header parsing. Content-Type: text/xml Content-Length: 129 <?xml version='1.0'?> <methodResponse> <params> <param> <value><boolean>0</boolean></value> </param> </params> </m...
[ "Based on Michal solution but this one includes and essential fix:\ndef strip_http_headers(http_reply):\n p = http_reply.find('\\r\\n\\r\\n')\n if p >= 0:\n return http_reply[p+4:]\n return http_reply\n\n", "In HTTP response headers are separated from body by two CRLF characters. So you can use st...
[ 5, 3, 2, 2, 1, 1 ]
[]
[]
[ "http", "python" ]
stackoverflow_0008474745_http_python.txt
Q: SimpleCV NameError: name 'images' is not defined I try Library SimpleCV. I have Ubuntu 11.10, Python 2.7 with PIL (python-imaging ver. 1.1.7-3ubuntu1) According to Install instructions I downloaded SimpleCV_1.1_linux_all.deb package. Then I install: sudo apt-get install python-numpy python-scipy. Since Ubuntu 11...
SimpleCV NameError: name 'images' is not defined
I try Library SimpleCV. I have Ubuntu 11.10, Python 2.7 with PIL (python-imaging ver. 1.1.7-3ubuntu1) According to Install instructions I downloaded SimpleCV_1.1_linux_all.deb package. Then I install: sudo apt-get install python-numpy python-scipy. Since Ubuntu 11.10 has python-opencv library I don't install any othe...
[ "Pass images/redeye.jpg as a string: Image(\"images/redeye.jpg\").\nmy_image = Image(\"images/redeye.jpg\")\n\nYou are currently passing that literally to the Image() class, hence why python is intepreting it as a variable, and as such, raising a NameError exception because the images local or global name is not fo...
[ 2 ]
[]
[]
[ "opencv", "python", "simplecv" ]
stackoverflow_0008482897_opencv_python_simplecv.txt
Q: UnicodeDecodeError on join I have a list with some strings (most of which I fetched from a sqlite3 database): stats_list = ['Statistik \xc3\xb6ver s\xc3\xa5nger\n', 'Antal\tS\xc3\xa5ng', '1\tCarola - Betlehems Stj\xc3\xa4rna', '\n\nStatistik \xc3\xb6ver datak\xc3\xa4llor\n', 'K\xc3\xa4lla\tAntal', 'MANUAL\t1', '\n...
UnicodeDecodeError on join
I have a list with some strings (most of which I fetched from a sqlite3 database): stats_list = ['Statistik \xc3\xb6ver s\xc3\xa5nger\n', 'Antal\tS\xc3\xa5ng', '1\tCarola - Betlehems Stj\xc3\xa4rna', '\n\nStatistik \xc3\xb6ver datak\xc3\xa4llor\n', 'K\xc3\xa4lla\tAntal', 'MANUAL\t1', '\n\nStatistik \xc3\xb6ver \xc3\xb6...
[ "Your problem is probably that you are mixing unicode strings with byte strings.\nThe code in \"Edit 2\" has several unicode strings being added to stats_list:\nstats_list = [u'Statistik över sånger\\n', u'Antal\\tSång']\n\nIf you try to decode these unicode strings, you will get a UnicodeEncodeError. This because ...
[ 11, 7, 1 ]
[]
[]
[ "character_encoding", "python", "unicode" ]
stackoverflow_0008481006_character_encoding_python_unicode.txt
Q: Python's trigonmetric function return unexpected values import math print "python calculator" print "calc or eval" while 0 == 0: check = raw_input() #(experimental evaluation or traditional calculator) if check == "eval": a = raw_input("operator\n") #operator if a == "+": b = in...
Python's trigonmetric function return unexpected values
import math print "python calculator" print "calc or eval" while 0 == 0: check = raw_input() #(experimental evaluation or traditional calculator) if check == "eval": a = raw_input("operator\n") #operator if a == "+": b = input("arg1\n") #inarg1 c = input("arg2\n") #inarg2...
[ "You don't want o convert the return value of sin() to degrees -- the return value isn't an angle. You instead want to convert the argument to radians, since math.sin() expects radians:\n>>> math.sin(math.radians(90))\n1.0\n\n", "Python's sin and cos take radians not degrees. You can convert using the math.radia...
[ 10, 3, 3, 2, 2, 2 ]
[]
[]
[ "math", "python", "trigonometry" ]
stackoverflow_0008483080_math_python_trigonometry.txt
Q: Calculate starting time and duration of a digital signal in python I am having a hard "time" trying to use time and datetime in Python to achive a fairly simple goal. I have already worked with those modules, and have read documentation, but I think I am not getting it the right way. I have a digital signal (a lon...
Calculate starting time and duration of a digital signal in python
I am having a hard "time" trying to use time and datetime in Python to achive a fairly simple goal. I have already worked with those modules, and have read documentation, but I think I am not getting it the right way. I have a digital signal (a long array) which represents a time series recorded with a given sampling r...
[ "from datetime import timedelta\n\nil = [(150, 150),\n (450, 90),\n (750, 150),\n (1050, 90),\n (1350, 150),\n (1650, 90),\n (1950, 150)]\n\nsr = 12.5\ntl = list(tuple((str(timedelta(seconds=j/sr)) for j in i)) for i in il)\n\nfor t in tl:\n print(t)\n\nprints:\n('0:00:12', '0:00:12...
[ 1 ]
[]
[]
[ "datetime", "python", "string_formatting", "time", "timestamp" ]
stackoverflow_0008480346_datetime_python_string_formatting_time_timestamp.txt
Q: Python xml absolute path How do I use python to print/dump the "absolute path" and value for an XML document? for example: <A> <B>foo</B> <C> <D>On</D> </C> <E>Auto</E> <F> <G> <H>shoo</H> <I>Off</I> </G> </F> </A> to /A/B, foo /A/C/D, On /A/E, Auto /A/F/G/H, shoo /A/F/G/I, Off...
Python xml absolute path
How do I use python to print/dump the "absolute path" and value for an XML document? for example: <A> <B>foo</B> <C> <D>On</D> </C> <E>Auto</E> <F> <G> <H>shoo</H> <I>Off</I> </G> </F> </A> to /A/B, foo /A/C/D, On /A/E, Auto /A/F/G/H, shoo /A/F/G/I, Off
[ "from lxml import etree\nroot = etree.XML(your_xml_string)\n\ndef print_path_of_elems(elem, elem_path=\"\"):\n for child in elem:\n if not child.getchildren() and child.text:\n # leaf node with text => print\n print \"%s/%s, %s\" % (elem_path, child.tag, child.text)\n else:\n ...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008475377_python_xml.txt
Q: Proper way to extend Python Queue? I'm writing a custom sub-class of Queue.Queue and run into a situation where I need to acquire a queue-level lock when my custom put() is being called. I'd like to reuse the existing lock Queue has (Queue.mutex), but can't because its not an RLock. In the source (python 2.6), it...
Proper way to extend Python Queue?
I'm writing a custom sub-class of Queue.Queue and run into a situation where I need to acquire a queue-level lock when my custom put() is being called. I'd like to reuse the existing lock Queue has (Queue.mutex), but can't because its not an RLock. In the source (python 2.6), it says: # Override these methods [_put, _...
[ "As far as I'm concerned, it would be completely kosher. In Python, the source is the documentation, or at least should be considered as a supplement to the published API documentation. This is largely a consequence of the enforced use of whitespace and coding conventions that emphasize clear, readable code: when y...
[ 2 ]
[]
[]
[ "python", "queue" ]
stackoverflow_0008482619_python_queue.txt
Q: In pyqt how do I use for loops to insert data at tablewidgets? I have some tablewidgets,in which I want to insert some data.To do this,i use the following: for index,i in enumerate(list1): item = QtGui.QTableWidgetItem() item.setText(QtGui.QApplication.translate("Dialog", str(i), None, QtGui.QApplication.Uni...
In pyqt how do I use for loops to insert data at tablewidgets?
I have some tablewidgets,in which I want to insert some data.To do this,i use the following: for index,i in enumerate(list1): item = QtGui.QTableWidgetItem() item.setText(QtGui.QApplication.translate("Dialog", str(i), None, QtGui.QApplication.UnicodeUTF8)) item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt...
[ "Just send the QTableWidget object to your function and use as such:\ndef function_1(item_list,tablewidget):\n for index, i in enumerate(item_list):\n #...\n tablewidget.setItem(0, index, item)\n\n", "You can use getattr() to evaluate attribute names dynamically:\ndef function_1(list1,number_of_tab...
[ 1, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0008483385_pyqt_python.txt
Q: webapp2 routing fails I hoped that webapp2 routing would be easy but apparently it is not (for me). This is issue is similar to webapp2 route fails as the code is pretty much the same but when I use webapp2.Route I only get 404 errors and when I use laze routing (as is the solution in the other question mentioned ...
webapp2 routing fails
I hoped that webapp2 routing would be easy but apparently it is not (for me). This is issue is similar to webapp2 route fails as the code is pretty much the same but when I use webapp2.Route I only get 404 errors and when I use laze routing (as is the solution in the other question mentioned above) I get this colorful ...
[ "here's the correct regex to catch your urls\nSITE_URLS = [\n webapp2.Route(r'/', handler.TestHome),\n webapp2.Route(r'/test/<:\\w+>', handler.TestPage)\n]\n\nyou can also get named route, simply by adding\n webapp2.Route(r'/test/<your_route_name_here:\\w+>', handler.TestPage)\n\nand named routes are usually ...
[ 6 ]
[]
[]
[ "google_app_engine", "python", "webapp2" ]
stackoverflow_0008481653_google_app_engine_python_webapp2.txt
Q: django: return image data from a view I want a view to return image data. so something along the lines of return HttpResponse(image_data, mimetype=”image/png”) I know I can do a file.read() to get the image data, but because the image is small (like 1x1 px) I want to just store it as a string object (or whatever ...
django: return image data from a view
I want a view to return image data. so something along the lines of return HttpResponse(image_data, mimetype=”image/png”) I know I can do a file.read() to get the image data, but because the image is small (like 1x1 px) I want to just store it as a string object (or whatever object I can copy and paste in my code). Th...
[ "Here is a simple example from the django-openid project\ndef logo(request):\n return HttpResponse(\n OPENID_LOGO_BASE_64.decode('base64'), content_type='image/gif'\n )\n # Logo from http://openid.net/login-bg.gif\n # Embedded here for convenience; you should serve this as a static file\n OPEN...
[ 13, 1 ]
[]
[]
[ "binary", "django", "httpresponse", "python" ]
stackoverflow_0008483348_binary_django_httpresponse_python.txt
Q: Using map function in python If you have the following code, how exactly is it following the documentation: map(function, iterable,...)? x = sorted(map(int, dat[0].split())) Is int a function and if so, why isn't it expressed as such? A: int is a constructor so it's callable so you can use it with map A: In ...
Using map function in python
If you have the following code, how exactly is it following the documentation: map(function, iterable,...)? x = sorted(map(int, dat[0].split())) Is int a function and if so, why isn't it expressed as such?
[ "int is a constructor so it's callable so you can use it with map\n", "In your case dat[0] is as string, and split() generates a list of strings, by splitting the input string at whitespaces.\nEg\n\"1 11\".split()\n\nreturns\n[\"1\", \"11\"]\n\nThe map function has two input arguments: \n\nThe first argument is s...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007593895_python.txt
Q: python subprocess non-blocking and returning output I know this has been asked a lot of times but I've yet to find a proper way of doing this. If I want to run a local command the docs say I have to use subprocess as it's replacing all other methods such as os.system/peopen etc. If I call subprocess.Popen(command,...
python subprocess non-blocking and returning output
I know this has been asked a lot of times but I've yet to find a proper way of doing this. If I want to run a local command the docs say I have to use subprocess as it's replacing all other methods such as os.system/peopen etc. If I call subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) in my program and th...
[ "If you specify stdout=PIPE, then your subprocess will write to the pipe and hang when the pipe buffer is full. The python program shoudn't hang - Popen is asynchronous which is why Popen.wait() can be called later to wait for the subprocess to exit. Read from Popen.stdout in order to keep the subprocess happy, a...
[ 0 ]
[ "Consider running your process within a terminal. For example,\nsubprocess.Popen(\"xterm -e /bin/bash -c '/path/to/openvpn'\", shell=True)\n\nor even, you could try,\nimport shlex\nsubprocess.Poen(shlex.split(\"xterm -e /bin/bash -c '/path/to/openvpn'\"), shell=False)\n\n" ]
[ -1 ]
[ "python", "subprocess" ]
stackoverflow_0008483654_python_subprocess.txt
Q: defaultdict and tuples I wanted to do the following: d = defaultdict((int,float)) for z in range( lots_and_lots): d['operation one'] += (1,5.67) ... ... d['operation two'] += (1,4.56) And then output the number of times each operation was called and the total of float value. for k,v in d.items(): print ...
defaultdict and tuples
I wanted to do the following: d = defaultdict((int,float)) for z in range( lots_and_lots): d['operation one'] += (1,5.67) ... ... d['operation two'] += (1,4.56) And then output the number of times each operation was called and the total of float value. for k,v in d.items(): print k, 'Called', v[0], 'times, t...
[ "You could do it with collections.Counter to accumulate the results:\n>>> from collections import Counter, defaultdict\n>>> d = defaultdict(Counter)\n>>> d['operation_one'].update(ival=1, fval=5.67)\n>>> d['operation_two'].update(ival=1, fval=4.56)\n\n", "the argument to defaultdict must be a \"callable\" that re...
[ 28, 19, 5, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008483881_python.txt
Q: how to rid "" from a string to non string I have this a = "'Something': False" I want it to be this a = 'Something': False How do I do it? I can strip things within the double quotation marks, but not the quotation marks itself. Have researched, cant find. I have mind block at moment. Sorry Im trying to do this:...
how to rid "" from a string to non string
I have this a = "'Something': False" I want it to be this a = 'Something': False How do I do it? I can strip things within the double quotation marks, but not the quotation marks itself. Have researched, cant find. I have mind block at moment. Sorry Im trying to do this: query_results = UserProfile.objects.filter(Loc...
[ "You can't. This is not valid python syntax: 'Something': False ... unless it's inside a dictionary: {'Something': False}. And no, you can not assign 'Something': False to a variable.\n", "stufftofilter = {}\nif shouldFilterLocation:\n stufftofilter['Location'] = 'thelocation'\n# etc\nquery_set = UserProfile.o...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008483824_python.txt
Q: Separating view_config routing and rendering in Pyramid I am attempting to implement a pattern where I use an intermediate function to determine which function to call and have the final function do the rendering, but the flow does not end up rendering. What am I missing? Is there a way to tweak this to make it wo...
Separating view_config routing and rendering in Pyramid
I am attempting to implement a pattern where I use an intermediate function to determine which function to call and have the final function do the rendering, but the flow does not end up rendering. What am I missing? Is there a way to tweak this to make it work? Here's what I'm attempting. @view_config(route='fork_rout...
[ "Pyramid's renderers are pretty simple, and in the end it's \"just python\". Meaning you're calling functions from functions, nothing special.\nThe way Pyramid's automated rendering works is:\n\nRequest comes in, gets dispatched to a view.\nIf that specific view view does NOT return a Response object, then Pyramid ...
[ 4 ]
[]
[]
[ "pyramid", "python", "render" ]
stackoverflow_0008483096_pyramid_python_render.txt
Q: SQLAlchemy is Throwing an IntegrityError due to a DBSession.add() On the second time line 121 is called in this script http://paste.pocoo.org/show/520040/, I receive this error message: *** IntegrityError: (IntegrityError) duplicate key value violates unique constraint "heroes_pkey" DETAIL: Key (id)=(14) already ...
SQLAlchemy is Throwing an IntegrityError due to a DBSession.add()
On the second time line 121 is called in this script http://paste.pocoo.org/show/520040/, I receive this error message: *** IntegrityError: (IntegrityError) duplicate key value violates unique constraint "heroes_pkey" DETAIL: Key (id)=(14) already exists. 'INSERT INTO heroes (id, name, description, image_name, defaul...
[ "The problem ended up being with Postgres. I had created the database by importing a sql file, and the sequence that kept track of the heroes primary key ended up not being accurate. This explained why the id was being incremented by one on each subsequent run, b/c Postgres was attempting to find an unused primar...
[ 13 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0008483895_postgresql_python_sqlalchemy.txt
Q: Retrieving the number of integers from a variable I have a variable x and is used four times throughout my code. I want to find the amount of numbers in the variable and then count up to the highest number starting from 1. Each time, the variable x has different numbers and different amounts of numbers. Guanine = ...
Retrieving the number of integers from a variable
I have a variable x and is used four times throughout my code. I want to find the amount of numbers in the variable and then count up to the highest number starting from 1. Each time, the variable x has different numbers and different amounts of numbers. Guanine = {"C": [(6.958, -5.037, 2.040), (7.355, -4.850, 3.500), ...
[ "If I'm reading your question correctly, this should accomplish what you want:\nx = [x for x, y, z in Guanine['C']]\n\nThis returns the list of all x values in your data set.\n", "Try\nlength = 0\nfor i in Guanine[\"C\"]:\n length += len(i)\n\nfor i in range(1, length):\n print i # <-python 2.7 for 3.0 or ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008484243_python.txt
Q: OO Patterns and/or Structured Approach for "Self Healing"? Many web application projects I've been involved with reach a point where The application expects persisted data to be in a particular format The application will barf if the persisted data strays from that format Old "mystery code" is persisting data in...
OO Patterns and/or Structured Approach for "Self Healing"?
Many web application projects I've been involved with reach a point where The application expects persisted data to be in a particular format The application will barf if the persisted data strays from that format Old "mystery code" is persisting data in the bad format This usually results in the application develop...
[ "We use configuration-file provided list of steps that should be performed on every processed item. That enables validation, slight changes of data, lookups, retrieval and merging of certain attributes from external sources etc.\nAlthough right now it is based on a set of Ruby classes that implement abstract Step, ...
[ 2, 2 ]
[]
[]
[ "oop", "php", "python", "ruby", "self_healing" ]
stackoverflow_0008481586_oop_php_python_ruby_self_healing.txt
Q: Python in a webapp (client side) This is part of some preliminary research and I am having a difficult time figuring out what options might be available or if this is even a situation where a solution even exists. Essentially we have an existing python based simulation that we would like to make available to peopl...
Python in a webapp (client side)
This is part of some preliminary research and I am having a difficult time figuring out what options might be available or if this is even a situation where a solution even exists. Essentially we have an existing python based simulation that we would like to make available to people via the web. It can be pretty proce...
[ "Pyjamas: Python->Javascript, set of widgets for use in a browser or a desktop\nSkulpt: Python written in Javascript\nEmscripten: C/C++ -> LLVM -> Javascript\nEmpythoned: Based on emscripten and cpython, working on a stdlib? There are bugs to file\n" ]
[ 1 ]
[]
[]
[ "apache_flex", "html", "python" ]
stackoverflow_0008484253_apache_flex_html_python.txt
Q: plotting bounded CDF of discrete count data in matplotlib python I have a numpy array "data" that just contains a set of integer counts. Given another array "bins", I just want to make a frequency plot/CDF of the fraction of total entries in "data" that have at least bins[0]-many counts, at least bins[1]-many coun...
plotting bounded CDF of discrete count data in matplotlib python
I have a numpy array "data" that just contains a set of integer counts. Given another array "bins", I just want to make a frequency plot/CDF of the fraction of total entries in "data" that have at least bins[0]-many counts, at least bins[1]-many counts, etc. and make it into a bar plot, in matplotlib. For example, if: ...
[ "If you're using matplotlib I assume you are also using numpy, so you can just go through bins and work out the fraction of data such that data>bin, for all data in datas and for all bin in bins.\nTo that effect this could work:\nimport numpy as np\n# turn data into numpy array for easier manipulation\ndata2 = np.a...
[ 1 ]
[]
[]
[ "graph", "matplotlib", "plot", "python" ]
stackoverflow_0008484639_graph_matplotlib_plot_python.txt
Q: Regular expression for matching latex I am trying to learn regular expressions by writing something akin to latex2html in Python. But I am having a hard time figuring out how to match latex equations -- things of the form $ ... $ where ... can be any expression in LaTeX, while allowing for escape sequences at the ...
Regular expression for matching latex
I am trying to learn regular expressions by writing something akin to latex2html in Python. But I am having a hard time figuring out how to match latex equations -- things of the form $ ... $ where ... can be any expression in LaTeX, while allowing for escape sequences at the same time. In other words, the problem cas...
[ "You can use negative lookbehind to make sure you don't match \\$. something like:\n\\\\$.*?(?<!\\\\\\\\)\\\\$\n\nE.g.\nprint re.findall(\"\\\\$.*?(?<!\\\\\\\\)\\\\$\", \"$x= \\$12$ and $x=12$\")\n\nwill find two matches: $x= \\$12$ and $x=12$\n", "The answer from Petar should get you started.\nIt might also be h...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008484945_python_regex.txt
Q: Matplotlib - 3D plotting - Points are being defaulted to circles I am trying to get do a 3D scatter plot, but the only markers that seems to work are so large that they start overlapping. I would like to just use '.' or ',', but I always get bumped to using 'o'. I could live with those if markersize would work in ...
Matplotlib - 3D plotting - Points are being defaulted to circles
I am trying to get do a 3D scatter plot, but the only markers that seems to work are so large that they start overlapping. I would like to just use '.' or ',', but I always get bumped to using 'o'. I could live with those if markersize would work in 3D plots. Is there a way around this?
[ "Types of markers\nFor scatter, '.' is for point markers and ',' is for pixel markers. When I attempt to use them, however, I get a ValueError claiming they do not exist, but that is likely due to using matplotlib v1.0.1; the changelog for v1.1.x includes a comment on markers:\n\nThere is now a common set of marker...
[ 4 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008485250_matplotlib_python.txt
Q: Why does python append 0000 to every UTF-32 encoded character? Try: codecs.getencoder('hex_codecs')(codecs.getencoder('utf-32')('a')[0]) Python will output: ('fffe000061000000', 8) Why python append 0000 to the UTF-32 encoded string? Thanks. A: It doesn't. 61000000 is the (little-endian) UTF-32 encoding of U+0...
Why does python append 0000 to every UTF-32 encoded character?
Try: codecs.getencoder('hex_codecs')(codecs.getencoder('utf-32')('a')[0]) Python will output: ('fffe000061000000', 8) Why python append 0000 to the UTF-32 encoded string? Thanks.
[ "It doesn't. 61000000 is the (little-endian) UTF-32 encoding of U+0061, LATIN SMALL LETTER A. 6100 would be the (little-endian) UTF-16 encoding, and 61 would be the UTF-8 encoding.\n", "It's just ordering the bytes in opposite (little-endian) order than you may expect. The same in PHP:\n> bin2hex(iconv('ASCII', '...
[ 2, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0008485466_python_unicode.txt
Q: google-app-engine: How can I have a list of objects as property in another class? how can I achieve this in google appengine db model from google.appengine.ext import db Class Car(db.Model): name=db.StringProperty() model=db.StringProperty() mileage=db.IntegerProperty() Class Person(db.Model): nam...
google-app-engine: How can I have a list of objects as property in another class?
how can I achieve this in google appengine db model from google.appengine.ext import db Class Car(db.Model): name=db.StringProperty() model=db.StringProperty() mileage=db.IntegerProperty() Class Person(db.Model): name=db.StringProperty() age=db.IntegerProperty() cars=db.ListProperty(Car) # How ...
[ "Have a look at the reference documentation http://code.google.com/appengine/docs/python/datastore/datamodeling.html#References\nIt works the other way round, class Car would have\nperson = db.ReferenceProperty(Person, collection_name=\"cars\")\n\nwhich would make a property cars available in Person.\nHope this hel...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008485502_google_app_engine_python.txt
Q: Overloaded constructor in Python from C++ perspective There is this code: #include <iostream> class SomeClass { int someInteger; float someFloat; public: SomeClass(int someInteger_) { // do something for int std::cout << "Int constructor\n"; } SomeClass(float someFloat_) { // do something...
Overloaded constructor in Python from C++ perspective
There is this code: #include <iostream> class SomeClass { int someInteger; float someFloat; public: SomeClass(int someInteger_) { // do something for int std::cout << "Int constructor\n"; } SomeClass(float someFloat_) { // do something for float std::cout << "Float constructor\n"; } }; ...
[ "Use isinstance:\n>>> isinstance(1, int)\nTrue\n>>> isinstance(1, float)\nFalse\n>>> isinstance(1.1, float)\nTrue\n>>> isinstance(1.1, int)\nFalse\n\nOr for you constructor:\ndef __init__(self, value):\n if isinstance(value, int):\n # int constructor\n elif isinstance(value, float):\n # float co...
[ 5 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0008485847_c++_python.txt
Q: PyQt4 - Smooth window resize transition? When a User opens a particular tab inside the QMainWindow of my PyQt4 driven GUI, the window needs to be automatically resized so that the contents of this particular tab will fit. As you know, when using Qwidget.resize(), the Window (by default on PC) is instantly resized....
PyQt4 - Smooth window resize transition?
When a User opens a particular tab inside the QMainWindow of my PyQt4 driven GUI, the window needs to be automatically resized so that the contents of this particular tab will fit. As you know, when using Qwidget.resize(), the Window (by default on PC) is instantly resized. This isn't easy on the eyes and would probabl...
[ "There is QPropertyAnimation which can be used to animate QObject properties, including the size of your window.\nI'm not sure if it will work well performance wise, since it will call resize() perpetually, as you say, but it seems like that is what you want.\nWhat you could maybe do is to resize the window, but so...
[ 2 ]
[]
[]
[ "python", "qt", "resize", "transition", "windows_7" ]
stackoverflow_0008485746_python_qt_resize_transition_windows_7.txt
Q: Parsing Html data using LXML <div id="descriptionmodule" class="module toggle-wrap"> <div class="mod-header"> <h3 class="toggle-title">Description</h3> </div> <div id="issue-description" class="mod-content"> <p>qqqqqqqqqqqqq,<br/> qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq...
Parsing Html data using LXML
<div id="descriptionmodule" class="module toggle-wrap"> <div class="mod-header"> <h3 class="toggle-title">Description</h3> </div> <div id="issue-description" class="mod-content"> <p>qqqqqqqqqqqqq,<br/> qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq<br/> qqqqqqqqqqqqqqqqqqqqqqqqqqq...
[ "First off: if you are parsing HTML there is a high chance humans will have messed up with it and it won't validate correctly. For example this is the case for the example you posted (there are a couple of </div> missing...). Consider passing to beautifulsoup instead, which is specifically designed to accommodate f...
[ 1 ]
[]
[]
[ "css_selectors", "lxml", "python" ]
stackoverflow_0008485706_css_selectors_lxml_python.txt
Q: Handle browser's Back and Next buttons after logout Python After log out from my app, I have redirected the user to the log in page. At the log in page, when someone click back or next buttons of the browser, I want to redirect him to the login page as same as gmail or facebook. So I tried to clear cache as foll...
Handle browser's Back and Next buttons after logout Python
After log out from my app, I have redirected the user to the log in page. At the log in page, when someone click back or next buttons of the browser, I want to redirect him to the login page as same as gmail or facebook. So I tried to clear cache as follow, class LogoutHandler(SecurePageHandler): def get(self): s...
[ "Maybe you can try to use javascript's window.location.replace after logout so that the page you don't want to go back to is replace with the new login page.\n" ]
[ 0 ]
[]
[]
[ "browser_cache", "http_headers", "javascript", "python", "tipfy" ]
stackoverflow_0008485678_browser_cache_http_headers_javascript_python_tipfy.txt
Q: python positional args and keyword args I am reading the source codes of mercurial, and found such a func def in commands.py: def import_(ui, repo, patch1=None, *patches, **opts): ... in python, postional args must be put ahead of keyword args. But here, patch1 is a keyword argument, followed by a positional ...
python positional args and keyword args
I am reading the source codes of mercurial, and found such a func def in commands.py: def import_(ui, repo, patch1=None, *patches, **opts): ... in python, postional args must be put ahead of keyword args. But here, patch1 is a keyword argument, followed by a positional argument *patches. why is this OK?
[ "Just have a look into the PEP 3102 also it seems its somehow related to this.\nTo summarize, patches and opts are there to accept variable arguments but the later is to accept keyword arguments. The keyword arguments are passed as a dictionary where as the variable positional arguments would be wrapped as tuples ....
[ 9, 3, 2, 2 ]
[]
[]
[ "func", "function", "python" ]
stackoverflow_0008486067_func_function_python.txt
Q: Python/Django auto typecasting datetime field to datetime.datetime I am using query = mysql_query mysql = connection.cursor() mysql.execute(mysql) to get my result by providing raw sql query. It is working fine but while fetching datetime time field it is giving datetime.datetime(2011,8,3,0,0) but if execute same...
Python/Django auto typecasting datetime field to datetime.datetime
I am using query = mysql_query mysql = connection.cursor() mysql.execute(mysql) to get my result by providing raw sql query. It is working fine but while fetching datetime time field it is giving datetime.datetime(2011,8,3,0,0) but if execute same query in mysql it is not typecasting. Please where anything is missing
[ "The database stores date/time values as a string internally. When you retrieve it through Django, then Django casts this into a datetime.datetime object for your convenience. If you retrieve the value directly from the database yourself, you will get the raw string and will therefore need to do any casting yoursel...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008486180_django_python.txt
Q: Unable to compile PIL/pysqlite after OS X 10.7 Lion upgrade After Lion upgrade, I had to reinstall my python packages, and ran into problem installing PIL and pysqlite. ... unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1 A: Turned out all I had to do was li...
Unable to compile PIL/pysqlite after OS X 10.7 Lion upgrade
After Lion upgrade, I had to reinstall my python packages, and ran into problem installing PIL and pysqlite. ... unable to execute gcc-4.2: No such file or directory error: command 'gcc-4.2' failed with exit status 1
[ "Turned out all I had to do was link up gcc-4.2, which was in /Developer/usr/bin\nI added export PATH=$PATH:/Developer/usr/bin to ~/.bash_profile\n", "ln -s /Developer/usr/bin/gcc /Developer/usr/bin/gcc-4.2\n" ]
[ 2, 2 ]
[]
[]
[ "pysqlite", "python", "python_imaging_library", "xcode4" ]
stackoverflow_0006771250_pysqlite_python_python_imaging_library_xcode4.txt
Q: Can AppEngine python threads last longer than the original request? We're trying to use the new python 2.7 threading ability in Google App Engine and it seems like the created thread is getting killed before it finishes running. Our scenario: User sends a message to the server We update the user's data We spawn ...
Can AppEngine python threads last longer than the original request?
We're trying to use the new python 2.7 threading ability in Google App Engine and it seems like the created thread is getting killed before it finishes running. Our scenario: User sends a message to the server We update the user's data We spawn a thread to do some more heavy duty processing We return a response to th...
[ "The 'Sandboxing' section of this page:\n http://code.google.com/appengine/docs/python/python27/using27.html#Sandboxing\nindicates that threads cannot run past the end of the request.\n", "Deferred tasks are the way to do this. You don't need a URL or serialization to use them:\nfrom google.appengine.ext import d...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008481877_google_app_engine_python.txt
Q: Python - How do i multiply 2 lists I am trying to multiply and append 2 lists. I can't understand how it works. xs = [1,2,3,4] m = 3 t.append(xs[m]) return t How does ([1,2,3,4] * [3]) = 4? A: Performing i[j] indexes the sequence i with the value j. If you want matrix multiplication then you should look at NumP...
Python - How do i multiply 2 lists
I am trying to multiply and append 2 lists. I can't understand how it works. xs = [1,2,3,4] m = 3 t.append(xs[m]) return t How does ([1,2,3,4] * [3]) = 4?
[ "Performing i[j] indexes the sequence i with the value j. If you want matrix multiplication then you should look at NumPy.\n>>> [1, 2, 3, 4][3]\n4\n\n", "An addition to the list multiplication, we cannot multiply two lists. We can multiply list by a number(Integer; -ve will do as well). Doing this you can repeat ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008162445_python.txt
Q: Checking type of big integer values without sign There is this code: print isinstance(2147483647, int) # True - max signed 32-bit integer print isinstance(4294967295, int) # False - max unsigned 32-bit integer print isinstance(18446744073709551615, int) # False - max unsigned 64-bit integer How to check if value ...
Checking type of big integer values without sign
There is this code: print isinstance(2147483647, int) # True - max signed 32-bit integer print isinstance(4294967295, int) # False - max unsigned 32-bit integer print isinstance(18446744073709551615, int) # False - max unsigned 64-bit integer How to check if value is unsigned 32-bit integer and unsigned 64-bit integer...
[ "If you just intended to check whether the number fits in a 32 bit integer or 64 bit integer, there is a method called bit-length which you can check and determine if the result is less than 32 or not.\nFor ex.\n>>> def Is32or64(x):\n return 32 if x.bit_length() < 32 else 64\n\n>>> Is32or64(2**30)\n32\n>>> Is32...
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008486654_python.txt
Q: Notify browser/page after long task has ended I am using a Python WebServer (CherryPy), but I guess the question is more open and is fairly general. At the moment, I have some Ajax call trough JQuery load on a button click, that triggers some computation, ending in files generation. At the moment, as soon as the p...
Notify browser/page after long task has ended
I am using a Python WebServer (CherryPy), but I guess the question is more open and is fairly general. At the moment, I have some Ajax call trough JQuery load on a button click, that triggers some computation, ending in files generation. At the moment, as soon as the processing starts in a background thread, my load re...
[ "Poll the server to get the latest generated files (or the complete list of generated files) every n seconds, and stop the polling once the list is complete, or once the first ajax query (the one which starts the generation process) has completed.\nThe thread which generates the file should make the list of generat...
[ 1 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0008486691_browser_python.txt
Q: Funny issue; localStorage and MongoDB I'm having a peculiar issue. I'm reading the HTML from a div contenteditable, and then sending an AJAX request to my backend that saves that HTML to a mongodb document, and I also save that exact same HTML to localStorage. And, guess what happens? When the text is loaded back...
Funny issue; localStorage and MongoDB
I'm having a peculiar issue. I'm reading the HTML from a div contenteditable, and then sending an AJAX request to my backend that saves that HTML to a mongodb document, and I also save that exact same HTML to localStorage. And, guess what happens? When the text is loaded back later, the localStorage renders fine, but,...
[ "Sounds like the text returned from the server is HTML encoded. Whether the value in MongoDB is encoded or the result is encoded just before sending the response is something you can tell by looking at actual records in MongoDB.\nOne easy way to work with the encoded data is:\nvar decodedData = $(\"<div />\").html(...
[ 2 ]
[ "It's nothing about MongoDB, it's the AJAX call.\nThe string in response of an AJAX call will be converted to character entities, or they will break ur DOM with characters like '<'. All u need to do is converted them back.\n" ]
[ -1 ]
[ "html", "javascript", "mongodb", "python" ]
stackoverflow_0007990060_html_javascript_mongodb_python.txt
Q: How to check if a given tweet can be retweeted or not? Currently am working on a retweet function using twitter API's. While the feature works fine, but who those tweets that are not retweetable i get this error, "sharing is not permissable for this status (Share validations failed)". So i need a way to determine ...
How to check if a given tweet can be retweeted or not?
Currently am working on a retweet function using twitter API's. While the feature works fine, but who those tweets that are not retweetable i get this error, "sharing is not permissable for this status (Share validations failed)". So i need a way to determine if a particular tweet is retweetable or not using the JSON r...
[ "If someone have protected his tweets, it means his tweets can only be seen by his followers. If you retweet these tweets it may break this protection. So twitter do not let you retweet these tweets\nIf you want to check whether a user have protected his tweets or not, you can try this API:\nhttp://api.twitter.com/...
[ 1 ]
[]
[]
[ "api", "oauth", "python", "twitter" ]
stackoverflow_0008486036_api_oauth_python_twitter.txt
Q: Sharing util modules between actively developed apps We have a growing library of apps depending on a set of common util modules. We'd like to: share the same utils codebase between all projects allow utils to be extended (and fixed!) by developers working on any project have this be reasonably simple to use for...
Sharing util modules between actively developed apps
We have a growing library of apps depending on a set of common util modules. We'd like to: share the same utils codebase between all projects allow utils to be extended (and fixed!) by developers working on any project have this be reasonably simple to use for devs (i.e. not a big disruption to workflow) cross-platfo...
[ "You can take advantage of Python paths (the paths searched when looking for module to import).\nThus you can create different directory for utils and include it within different repository than the project that use these utils. Then include path to this repository in PYTHONPATH.\nThis way if you write import mymod...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008486942_python.txt
Q: The ability to apply multiple formats to cell with xlwt / openpyxl I plan to use one of 2 libraries below to output excel file in python: xlwt ( http://www.python-excel.org/ ) openpyxl ( http://packages.python.org/openpyxl/ ) I tried the first one, most of things seem to be fine but one issue, unfortunately it m...
The ability to apply multiple formats to cell with xlwt / openpyxl
I plan to use one of 2 libraries below to output excel file in python: xlwt ( http://www.python-excel.org/ ) openpyxl ( http://packages.python.org/openpyxl/ ) I tried the first one, most of things seem to be fine but one issue, unfortunately it may not support the ability to apply multiple formats to cell. (see http:...
[ "The svn versions of both xlrd and xlwt have support for \"rich text\", which is MS jargon for what you want.\n", "I have another answer which explains how to apply many formatting styles using openpyxl...\nSetting styles in Openpyxl\n" ]
[ 6, 0 ]
[]
[]
[ "excel", "openpyxl", "python", "xlwt" ]
stackoverflow_0008429014_excel_openpyxl_python_xlwt.txt
Q: Generate all the points on the circumference of a circle Could someone help me with a code that could generate all the points on the circumference of a circle, Given the radius and center of the circle. I need the code in Python. Also could someone explain what would happen if K-Means is applied to two sets of poi...
Generate all the points on the circumference of a circle
Could someone help me with a code that could generate all the points on the circumference of a circle, Given the radius and center of the circle. I need the code in Python. Also could someone explain what would happen if K-Means is applied to two sets of points (i mean the points on the circumference) for 2 circle with...
[ "The following would generate the desired number of points on a circumference of a circle centered at (0,0),default is 100 points.\nimport math\npi = math.pi\n\ndef PointsInCircum(r,n=100):\n return [(math.cos(2*pi/n*x)*r,math.sin(2*pi/n*x)*r) for x in range(0,n+1)]\n\n", "Here's how to generate All points on ...
[ 21, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008487893_python.txt
Q: share data using Manager() in python multiprocessing module I tried to share data when using the multiprocessing module (python 2.7, Linux), I got different results when using slightly different code: import os import time from multiprocessing import Process, Manager def editDict(d): d[1] = 10 d[2] = 20 ...
share data using Manager() in python multiprocessing module
I tried to share data when using the multiprocessing module (python 2.7, Linux), I got different results when using slightly different code: import os import time from multiprocessing import Process, Manager def editDict(d): d[1] = 10 d[2] = 20 d[3] = 30 pnum = 3 m = Manager() 1st version: mlist = m.lis...
[ "It is because you access the variable by the list index the second time, while the first time you pass the actual variable. As stated in the multiprocessing docs:\n\nModifications to mutable values or items in dict and list proxies will not be propagated through the manager, because the proxy has no way of knowing...
[ 11 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0008476392_multiprocessing_python.txt
Q: Python script and cgi throws an error Thanks to nightcracker for his suggestion on my first question, it works! I have another issue now, I am trying to make this work via a cgi Form to pilot the cameras from a Browser. The script goes like this: link to the script the error I get is: link to the python error So i...
Python script and cgi throws an error
Thanks to nightcracker for his suggestion on my first question, it works! I have another issue now, I am trying to make this work via a cgi Form to pilot the cameras from a Browser. The script goes like this: link to the script the error I get is: link to the python error So if any of you know what the problem is I am ...
[ "The error message says that integers do not have a method of move.\nThis is happening because servo is an integer (see line 13). When you do servo.move(...) you are calling a member method of the integer class... which does not exist. Perhaps you have another variable called servo somewhere else and you overwrote ...
[ 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0008488446_cgi_python.txt
Q: Expanding a list of tuples I have a list like [(1, 2), (4, 7), (6, 0)], where tuples are always of equal length. What's the most pythonic way to generate [1, 2, 4, 7, 6, 0]? A: You can use the list comprehension : my_list = [(1, 2), (4, 7), (6, 0)] result = [x for t in my_list for x in t] or result = list(itert...
Expanding a list of tuples
I have a list like [(1, 2), (4, 7), (6, 0)], where tuples are always of equal length. What's the most pythonic way to generate [1, 2, 4, 7, 6, 0]?
[ "You can use the list comprehension :\nmy_list = [(1, 2), (4, 7), (6, 0)]\nresult = [x for t in my_list for x in t]\n\nor\nresult = list(itertools.chain.from_iterable(my_list))\n\n", "If you're not using Python 3,\nreduce(lambda x,y: x+y, sequence)\n\nalso works. Mileage may vary on how pythonic it is since reduc...
[ 10, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008481567_python.txt
Q: AttributeError: 'NoneType' object has no attribute 'route' and webapp2 I am still running into errors with webapp2 and am at a lost what could be the problem here. ERROR 2011-12-13 11:17:19,059 webapp2.py:1528] 'NoneType' object has no attribute 'route' Traceback (most recent call last): File "/home/user/sdk/...
AttributeError: 'NoneType' object has no attribute 'route' and webapp2
I am still running into errors with webapp2 and am at a lost what could be the problem here. ERROR 2011-12-13 11:17:19,059 webapp2.py:1528] 'NoneType' object has no attribute 'route' Traceback (most recent call last): File "/home/user/sdk/google_appengine/lib/webapp2/webapp2.py", line 1511, in __call__ rv = se...
[ "I think it is because you didn't call the webapp2.RequestHandler.__init__(). Here is a code snippet from webapp2.py:\nclass RequestHandler(object):\n # ...\n def __init__(self, request=None, response=None):\n self.initialize(request, response)\n\nAs you can see the RequestHandler is initialized with r...
[ 10 ]
[]
[]
[ "google_app_engine", "python", "webapp2" ]
stackoverflow_0008488482_google_app_engine_python_webapp2.txt
Q: Is it possible to concatenate QuerySets? After a search of a database I end up with an array of querysets. I wanted to concatenate these queryset somewhat like we can do with list elements. Is this possible or maybe there an altogether better way to do this? The end goal here is to get queryset for rows of table t...
Is it possible to concatenate QuerySets?
After a search of a database I end up with an array of querysets. I wanted to concatenate these queryset somewhat like we can do with list elements. Is this possible or maybe there an altogether better way to do this? The end goal here is to get queryset for rows of table that contain one of a set of strings in a field...
[ "I think the proper way to do that is to use the | operator (that is, if the QuerySets are of the same type):\nqset = MyModel.objects.none()\nfor filterString in list_of_filterStrings:\n qset_temp = MyModel.objects.filter(asn=filterString)\n qset = qset | qset_temp\n\n", "Your code looks weird! I have no id...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008488689_django_python.txt
Q: Put JNDI parameter in WebSphere I would like to ask a question. Any help will be highly appreciated. I have a pair, let's say [key1][value1] and I would like to put them in a JNDI of WebSphere server using administrative script. What command in Python would do that? Thank you in advance. A: Well, I found a solut...
Put JNDI parameter in WebSphere
I would like to ask a question. Any help will be highly appreciated. I have a pair, let's say [key1][value1] and I would like to put them in a JNDI of WebSphere server using administrative script. What command in Python would do that? Thank you in advance.
[ "Well, I found a solution. I added spring context to store my values and to enhance architecture.\n" ]
[ 0 ]
[]
[]
[ "jndi", "python", "websphere" ]
stackoverflow_0008256113_jndi_python_websphere.txt
Q: Change the version of python 2.6 to python 2.5 or 2.4 Python-igraph is giving error when I install it on python 2.6 .SO, i wish to change it to python 2.5 or 2.4. I need to remove python2.6 and install python 2.5. Please show me a way to accomplish this!! A: You don't need to uninstall new version of Python to u...
Change the version of python 2.6 to python 2.5 or 2.4
Python-igraph is giving error when I install it on python 2.6 .SO, i wish to change it to python 2.5 or 2.4. I need to remove python2.6 and install python 2.5. Please show me a way to accomplish this!!
[ "You don't need to uninstall new version of Python to use its older version. Just install both or even more versions. This works for me on Linux and Windows. If you use some kind of unix then in your python source you can use shebang http://en.wikipedia.org/wiki/Shebang_(Unix). Simply start your python program with...
[ 2 ]
[]
[]
[ "python", "uninstallation", "version" ]
stackoverflow_0008488436_python_uninstallation_version.txt
Q: Python path issue with pickled class I have a class call Monkey, defined in root/ook/monkey.py. Another script, let's call it do_things.py pickles instances of Monkey objects. The script do_things.py looks like: import monkey [...] inst = monkey.Monkey() [...] data = cPickle.dumps(inst) Now, I have another scr...
Python path issue with pickled class
I have a class call Monkey, defined in root/ook/monkey.py. Another script, let's call it do_things.py pickles instances of Monkey objects. The script do_things.py looks like: import monkey [...] inst = monkey.Monkey() [...] data = cPickle.dumps(inst) Now, I have another script called root/eek/fubar.py that looks li...
[ "Change your import in the second file from import ook.monkey to from ook import monkey.\n", "The name \"Monkey\" in the global variables of the running module has to reference the same \"Monkey\" class -\nso, in your pickling module, do\nimport monkey\nMonkey = monkey.Monkey\n\nor just:\nfrom monkey import Monk...
[ 1, 1 ]
[]
[]
[ "path", "pickle", "python" ]
stackoverflow_0008489699_path_pickle_python.txt
Q: Python subprocess.check_call issue I know I'm doing something wrong. In the shell i would type: cuebreakpoints cuefile.cue | shnsplit -o flac flacfile.flac This would then split the flac file according to the cuefile. Since I'm in the process of writing a small help tool (in Python) to convert flac files I obviou...
Python subprocess.check_call issue
I know I'm doing something wrong. In the shell i would type: cuebreakpoints cuefile.cue | shnsplit -o flac flacfile.flac This would then split the flac file according to the cuefile. Since I'm in the process of writing a small help tool (in Python) to convert flac files I obviously wanted to incorporate this bit in my...
[ "If you want to use shell features such as pipes, you need to give check_call a shell=True kwarg and give the command as a single string:\ncheck_call(\"cuebreakpoints '%s' | shnsplit -o flac '%s'\" % (cue, flacs[0]),\n shell=True)\n\nBut note that shell=True is a potential security hazard when used with u...
[ 2, 2, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0008489712_python_subprocess.txt
Q: Open and Select Item in Windows Explorer (Unicode) - Python I know how to open and select file in windows explorer by using explorer.exe commandline options '/n,@/select ' but I can only make it work with regular characters. Anyone have idea how to make it support unicode characters such as this 五輪代? I've tried to...
Open and Select Item in Windows Explorer (Unicode) - Python
I know how to open and select file in windows explorer by using explorer.exe commandline options '/n,@/select ' but I can only make it work with regular characters. Anyone have idea how to make it support unicode characters such as this 五輪代? I've tried to encode it with 'utf-8' but it didn't work, I'm sure there's a pr...
[ "You can use ctypes to access the API in a more direct way: (file_path should be a Python unicode object, not utf-8)\nimport ctypes\nctypes.windll.shell32.ShellExecuteW(None, u'open', u'explorer.exe', \n u'/n,/select, ' + file_path, None, 1)\n\n", "this may be of some use. It's ...
[ 4, 0 ]
[]
[]
[ "python", "unicode", "windows_explorer" ]
stackoverflow_0008486815_python_unicode_windows_explorer.txt
Q: Incrementing a variable or assigning an iterator-element to it I want to increment a variable and - if a particular condition is fulfilled - I want to assign the next element of an iterator to it. In both cases the result should be appended to a list. Problem is, that the function only recognizes the values alread...
Incrementing a variable or assigning an iterator-element to it
I want to increment a variable and - if a particular condition is fulfilled - I want to assign the next element of an iterator to it. In both cases the result should be appended to a list. Problem is, that the function only recognizes the values already in the iterator. The input-data is a nested list. import datetime ...
[ "I am suspecting dates_prices is a nested list.\nYou possibly want to add a copy of item to filter and not the same object. To do this, change the line filled.append(item) to filled.append(item[:]). This will prevent item[0] += dt.timedelta(1) from changing already appended values in filled.\n\nTo answer your edit:...
[ 2, 1, 1, 1 ]
[]
[]
[ "iterator", "python", "variable_assignment" ]
stackoverflow_0008483344_iterator_python_variable_assignment.txt
Q: How to create an array of 10 digits for counting repetitions? I wondered how to create an array of 10 digits, such that each time a digit of a number shows, it increments its matching place in the 10 digits array, like this: digits=[0,0,0,0,0,0,0,0,0,0] num_digits=[1,2,3,9,1] and digits becomes: digits=[0,2,1,1,...
How to create an array of 10 digits for counting repetitions?
I wondered how to create an array of 10 digits, such that each time a digit of a number shows, it increments its matching place in the 10 digits array, like this: digits=[0,0,0,0,0,0,0,0,0,0] num_digits=[1,2,3,9,1] and digits becomes: digits=[0,2,1,1,0,0,0,0,0,1] I tried: digits[num_digits[j]]=digits[num_digits[j]]...
[ ">>> digits=[0,0,0,0,0,0,0,0,0,0]\n>>> num_digits=[1,2,3,9,1]\n>>> for d in num_digits:\n... digits[d] += 1\n... \n>>> digits\n[0, 2, 1, 1, 0, 0, 0, 0, 0, 1]\n\nWe wouldn't need a variable j for a simple iteration of a list.\n", "It might be worth using a dict rather than a list to store your totals. You cou...
[ 6, 3, 1 ]
[ "Here you can find how you could implement counting sort in python: http://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Counting_sort#Python\n" ]
[ -1 ]
[ "arrays", "digits", "flags", "list", "python" ]
stackoverflow_0008489940_arrays_digits_flags_list_python.txt
Q: Using Python's smtplib with Tor I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done? A:...
Using Python's smtplib with Tor
I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending. Ideas how this can be done?
[ "Because of abuse by spammers, many Tor egress nodes decline to emit port 25 (SMTP) traffic, so you may have problems.\n", "http://bent.latency.net/smtpprox/ I found this earlier, but haven't tried it\n" ]
[ 1, 1 ]
[]
[]
[ "python", "smtp", "tor" ]
stackoverflow_0000266849_python_smtp_tor.txt
Q: fabric task error when prompting for password I'm having an error I can't seem to get past. I have a simple fabric task that must be run as a different user on the remote system, e.g: def update(): env.user = 'otheruser' #~ env.password = 'otherpass' # this works, but I don't want it here. with cd(en...
fabric task error when prompting for password
I'm having an error I can't seem to get past. I have a simple fabric task that must be run as a different user on the remote system, e.g: def update(): env.user = 'otheruser' #~ env.password = 'otherpass' # this works, but I don't want it here. with cd(env.sitefolder): run('hg pull -u') If I run ...
[ "Prompt for the password yourself!\ndef update():\n env.user = 'otheruser'\n env.password = getpass.getpass('Enter password: ')\n with cd(env.sitefolder):\n run('hg pull -u')\n\ngetpass is part of the standard library, it's just a raw_input that doesn't echo what you type\n", "This can also happen...
[ 4, 1 ]
[]
[]
[ "fabric", "paramiko", "python" ]
stackoverflow_0007732856_fabric_paramiko_python.txt
Q: Parsing the result using python I am a beginner in Python (I am a biologist) and I have a file with the results from a particular software and i would like to parse the result using python. From the following output I would like to get just the score and would like to split the sequence into individual amino acids...
Parsing the result using python
I am a beginner in Python (I am a biologist) and I have a file with the results from a particular software and i would like to parse the result using python. From the following output I would like to get just the score and would like to split the sequence into individual amino acids. no. score ...
[ "Assuming you've opened the file containing this data as f, then your example can be reproduced with:\nfor ln in f: # loop over all lines\n seqno, score, seq = ln.split()\n print(\"%s %s %s\" % (seqno, score, seq[0]))\n\nTo split out the sequence, you need to additionally loop over the letters in seq...
[ 5, 0, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0008473786_parsing_python.txt
Q: Does python identify critical section automatically? I am new to Python multithreading coding. I consult the manual for Lock Object usage and find the normal case is g_mutex = Lock() g_mutex.acquire() #some code g_mutex.release() But the lock does not specify what variable or function it is going to lock? So doe...
Does python identify critical section automatically?
I am new to Python multithreading coding. I consult the manual for Lock Object usage and find the normal case is g_mutex = Lock() g_mutex.acquire() #some code g_mutex.release() But the lock does not specify what variable or function it is going to lock? So does python automatically find all critical variables to be l...
[ "The purpose of a Lock is that at most one thread can hold it at any given time. If you acquire the lock, you can be sure no other process holds it. It's up to you to define the semantics of the lock -- if you want to use it to guard the access to some variable, just do so: acquire the lock before messing around ...
[ 6, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008490327_multithreading_python.txt
Q: How to extract Ethernet level data from pcap file? I have some pcap files, previously I used tshark combined python to extract source IP address, timestamp, ect. However, now I open these pcap files in Wireshark. It also contains the VLAN info, VID is the thing I want to extract right now. I use tshark -r xx.pcap...
How to extract Ethernet level data from pcap file?
I have some pcap files, previously I used tshark combined python to extract source IP address, timestamp, ect. However, now I open these pcap files in Wireshark. It also contains the VLAN info, VID is the thing I want to extract right now. I use tshark -r xx.pcap in the terminal, it can only show the tcp level info, I...
[ "the perfect solution is Scapy\nIn this example i create a packet with vlan and then print the vlan ID\nfrom scapy.all import *\npkt=Ether()/Dot1Q(vlan=0x32)/IP(dst=\"192.168.1.66\")/ICMP()\nprint pkt[Dot1Q].vlan\n\nand this example shows how to read a pcap file and print the VLAN ID\nfrom scapy.all import *\nfrom ...
[ 2, 1 ]
[]
[]
[ "networking", "python", "scapy" ]
stackoverflow_0008489960_networking_python_scapy.txt
Q: Pywin32 Excel Formatting I want to write to an Excel sheet via pywin32. I can do it actually without problem. But I couldnt format a range of cells in sheet. I want to align the values centerly inside cells. And also i need to fill the cells with color. How can I do it? Thanks in advance. A: I've not specifical...
Pywin32 Excel Formatting
I want to write to an Excel sheet via pywin32. I can do it actually without problem. But I couldnt format a range of cells in sheet. I want to align the values centerly inside cells. And also i need to fill the cells with color. How can I do it? Thanks in advance.
[ "I've not specifically done this using python before, but I'm assuming you're using the COM automation interface to excel.\nThis page has an example that seems to cover both alignment and filling cells with colour in C#, so it should be fairly easy to adapt to python. Assuming you have a Worksheet object called sh...
[ 6 ]
[]
[]
[ "excel", "python", "pywin32" ]
stackoverflow_0008490265_excel_python_pywin32.txt
Q: how do I make a customised object as a node for networkx and how do I look it up? I want every node to have a ipaddress string, latitude and longitude values. Also how do I get a pointer to such object on looking up the graph created by networkx? A: NetworkX is based on the idea that graphs can act like dictiona...
how do I make a customised object as a node for networkx and how do I look it up?
I want every node to have a ipaddress string, latitude and longitude values. Also how do I get a pointer to such object on looking up the graph created by networkx?
[ "NetworkX is based on the idea that graphs can act like dictionaries. You don't need a custom object to act as nodes, as the nodes can have arbitrary properties added to their \"dictionaries\". \nConsider the following interactive session:\n>>> import networkx as nx\n>>> G = nx.Graph()\n>>> G.add_node(1)\n>>> G.nod...
[ 5 ]
[]
[]
[ "graph", "networkx", "python" ]
stackoverflow_0008490794_graph_networkx_python.txt
Q: Insert performance with Cassandra sorry for my English in advance. I am a beginner with Cassandra and his data model. I am trying to insert one million rows in a cassandra database in local on one node. Each row has 10 columns and I insert those only in one column family. With one thread, that operation took arou...
Insert performance with Cassandra
sorry for my English in advance. I am a beginner with Cassandra and his data model. I am trying to insert one million rows in a cassandra database in local on one node. Each row has 10 columns and I insert those only in one column family. With one thread, that operation took around 3 min. But I would like do the same ...
[ "It's possible you're hitting the python GIL but more likely you're doing something wrong.\nFor instance, putting 2M rows in a single batch would be Doing It Wrong.\n", "Try running multiple clients in multiple processes, NOT threads.\nThen experiment with different insert sizes. \n1M inserts in 3 mins is about 5...
[ 0, 0, 0, 0 ]
[]
[]
[ "cassandra", "insert", "multithreading", "python" ]
stackoverflow_0005950427_cassandra_insert_multithreading_python.txt
Q: how to handle socket errors as exceptions in python + paramiko? I want to return an error code when the following error gets raised: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "UserManagementRemote.py", line 202, in create_group ssh.connect(hostname, username=user, password=rem...
how to handle socket errors as exceptions in python + paramiko?
I want to return an error code when the following error gets raised: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "UserManagementRemote.py", line 202, in create_group ssh.connect(hostname, username=user, password=remotepass) File "/usr/lib/python2.6/site-packages/paramiko/client.py",...
[ "Do\nimport socket\n\nin the module where you do the exception handling.\nTo prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.\n" ]
[ 6 ]
[]
[]
[ "error_handling", "exception", "paramiko", "python" ]
stackoverflow_0008491194_error_handling_exception_paramiko_python.txt
Q: Matching two patterns in one python regex, capturing only non-empty values After a lot of searching and reading, I am not really sure what I am trying to do is possible in one step. I want it to either match this: (\d{1,4})/(\d{1,2})/(\d{1,2}) 2011/12/13 or this (\d{1,2})/(\d{1,4})/(\d{1,2}) 12/2011/13 or this...
Matching two patterns in one python regex, capturing only non-empty values
After a lot of searching and reading, I am not really sure what I am trying to do is possible in one step. I want it to either match this: (\d{1,4})/(\d{1,2})/(\d{1,2}) 2011/12/13 or this (\d{1,2})/(\d{1,4})/(\d{1,2}) 12/2011/13 or this (\d{1,2})/(\d{1,4})/(\d{1,2}) 12/13/2011 in one regex and capture the values ...
[ "How about:\n^(?:(?=\\d{1,4}/\\d{1,2}/\\d{1,2})|(?=\\d{1,2}/\\d{1,4}/\\d{1,2})|(?=\\d{1,2}/\\d{1,2}/\\d{1,4}))(\\d+)/(\\d+)/(\\d+)$\n\nThe 3 look ahead make sure you have a date in any of the 3 formats, then capture the 3 elements of the date.\nexplanation:\n^ : begining of the string\n...
[ 5, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008490954_python_regex.txt
Q: Matching strings for multiple data set in Python I am working on python and I need to match the strings of several data files. First I used pickle to unpack my files and then I place them into a list. I only want to match strings that have the same conditions. This conditions are indicated at the end of the string...
Matching strings for multiple data set in Python
I am working on python and I need to match the strings of several data files. First I used pickle to unpack my files and then I place them into a list. I only want to match strings that have the same conditions. This conditions are indicated at the end of the string. My working script looks approximately like this: im...
[ "out of my head:\nfiles = [\"file_a\", \"file_b\", \"file_c\"]\nsets = []\n\nfor f in files:\n f = open(\"data_a.dat\")\n sets.append(set(pickle.load(f)))\n f.close()\n\nintersection = sets[0].intersection(*sets[1:])\n\nEDIT: Well I overlooked your mapping to x.GetName()[12:], but you should be able to red...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008473620_python.txt
Q: Python: Writing to a specific position in a text file I am writing co-ordinates to a text file, a sample data set looks as follows: -11.700 8.827 9.247 -11.956 8.450 7.858 -12.511 9.655 7.129 -13.527 10.173 7.584 The co-ordinates are arranged x,y,z respectively. I need the X co-ordinates to be written to t...
Python: Writing to a specific position in a text file
I am writing co-ordinates to a text file, a sample data set looks as follows: -11.700 8.827 9.247 -11.956 8.450 7.858 -12.511 9.655 7.129 -13.527 10.173 7.584 The co-ordinates are arranged x,y,z respectively. I need the X co-ordinates to be written to the text file where the last digit in the number fall at cha...
[ "You could use the formatting operator % for this:\nIn [11]: x, y, z = -11.700, 8.827, 9.247\n\nIn [12]: '%14.3f %12.3f %12.3f' % (x, y, z)\nOut[12]: ' -11.700 8.827 9.247'\n\n", "string.rjust() is what you want.\nline = ''.join([str(x).rjust(14), str(y).rjust(13), str(z).rjust(13)])\n", "Th...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008477968_python.txt
Q: How can I split this string in two parts using a regex? Imagine this: a = "('a','b','c'),('d','e','f')" I am trying to split it using re so that I will get an array of 2 elements, containing "('a','b','c')" and ('d','e','f'). I tried : matches = re.split("(?:\)),(?:\()",a) but this gives me the result: '(2,3,4' ...
How can I split this string in two parts using a regex?
Imagine this: a = "('a','b','c'),('d','e','f')" I am trying to split it using re so that I will get an array of 2 elements, containing "('a','b','c')" and ('d','e','f'). I tried : matches = re.split("(?:\)),(?:\()",a) but this gives me the result: '(2,3,4' '1,6,7)' I could parse it, character by character, but if a ...
[ "You need to split on the comma which is preceded by a ) and followed by a (. But the parenthesis themselves should not be part of the split point. For that you need to use positive lookahead and positive look behind assertions as:\nmatches = re.split(\"(?<=\\)),(?=\\()\",a)\n\nSee it\n", "Try this:\nfrom ast imp...
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008491235_python_regex.txt
Q: Automatically update setup.py version on every SVN commit We are deploying Plone add-ons as development eggs with buildout. The eggs are pushed to the production as source code checkouts using Mr. Developer buildout recipe and .egg packaging is not done in any point. What would be best way to automatically update ...
Automatically update setup.py version on every SVN commit
We are deploying Plone add-ons as development eggs with buildout. The eggs are pushed to the production as source code checkouts using Mr. Developer buildout recipe and .egg packaging is not done in any point. What would be best way to automatically update setup.py version stamp on every SVN commit to SVN release numbe...
[ "Add something like this in setup.cfg:\n[egg_info]\ntag_build = .dev\ntag_svn_revision = 1\n\nThis only works for subversion of course; not sure if there are alternatives for other vcs. This file may still be added by default by some of the ZopeSkel templates. Some plone packages have it too; Wichert Akkerman is/...
[ 6, 1, 0 ]
[]
[]
[ "buildout", "plone", "python", "setuptools", "svn" ]
stackoverflow_0008486812_buildout_plone_python_setuptools_svn.txt
Q: Bold/Unbold rows in PyGTK TreeView I want to make some rows in my TreeView bold, and some not as I append them to TreeView, later on, I want to unbold rows on click. What is the easiest way to do this? A: I assume that you have a model that contains a column with some text and that a gtk.CellRendererText widget ...
Bold/Unbold rows in PyGTK TreeView
I want to make some rows in my TreeView bold, and some not as I append them to TreeView, later on, I want to unbold rows on click. What is the easiest way to do this?
[ "I assume that you have a model that contains a column with some text and that a gtk.CellRendererText widget has a text property set to the column index in that model.\nIf you add a new column to that model you can use it to set the font weight used in every cell renderer. To do that just set the gtk.CellRendererTe...
[ 7 ]
[]
[]
[ "click", "glade", "gtktreeview", "pygtk", "python" ]
stackoverflow_0008491310_click_glade_gtktreeview_pygtk_python.txt
Q: In Python, how can I refer to a return-value from a function called within a generator expression? Simplified, I want to do something like this: ({'publication': obj.pub_name, 'views': obj.views, } for obj = analyze_publication(p) for p in Publication.objects.all()) Of course, that doesn't work. Right now, I'm us...
In Python, how can I refer to a return-value from a function called within a generator expression?
Simplified, I want to do something like this: ({'publication': obj.pub_name, 'views': obj.views, } for obj = analyze_publication(p) for p in Publication.objects.all()) Of course, that doesn't work. Right now, I'm using: ({'publication': obj.pub_name, 'views': obj.views, } for obj in (analyze_publication(p) for p in Pu...
[ "Just another version:\n( dict(publication= obj.pub_name, views= obj.views) \n for obj in map(analyze_publication, Publication.objects.all()) )\n\n", "You have unbalanced parens, but other than that, you should have no (functional) problem nesting generator expressions. As with list comprehensions, they quick...
[ 2, 1, 0 ]
[]
[]
[ "generator_expression", "python", "syntax" ]
stackoverflow_0008485003_generator_expression_python_syntax.txt
Q: lift list of values to a list of lists of values Here's a tricky one. I want to take a list of integers, and turn it into a list of lists containing that integer. This is so that I can later append to that list. Unfortunately list() does not take a single integer, so I can't map it to the list. Here's a more co...
lift list of values to a list of lists of values
Here's a tricky one. I want to take a list of integers, and turn it into a list of lists containing that integer. This is so that I can later append to that list. Unfortunately list() does not take a single integer, so I can't map it to the list. Here's a more concrete explanation: Given, >>> a = range(5) >>> a [0, ...
[ "I'd use a list comprehension for this:\nIn [1]: a = range(5)\n\nIn [2]: [[v] for v in a]\nOut[2]: [[0], [1], [2], [3], [4]]\n\n", "If you want a general way to turn scalars into either lists or tuple, you can first turn them into a generic iterable returning one value (the scalar), and then construct either a li...
[ 9, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008491618_python.txt
Q: undefined symbol: Py_Initialize in Ubuntu 10.10 I created my own apache module in C API with Python. #include "httpd.h" #include "http_config.h" #include "http_protocol.h" #include "ap_config.h" #include "python2.7/Python.h" static char* a(){ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" ...
undefined symbol: Py_Initialize in Ubuntu 10.10
I created my own apache module in C API with Python. #include "httpd.h" #include "http_config.h" #include "http_protocol.h" #include "ap_config.h" #include "python2.7/Python.h" static char* a(){ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n...
[ "You can add a reference to libpython:\n$ apxs2 -cia mod_mor.c -lpython2.7\n\nThen you should be able to load your module.If you can not refer to the dynamic .so of python, then you could try using the .a version of the library:\n$ apxs2 -cia mod_mor.c -Wl,-static -lpython2.7 \n\nHowever,you can get some complains ...
[ 1 ]
[]
[]
[ "apache2", "c", "python" ]
stackoverflow_0008491666_apache2_c_python.txt
Q: Which gives better performance-passing parsed URL as args alongwith request or parsing URL in view-Django I have an Django application where the URL's to be handled shall have a specific pattern like /servername/alpha/beta/2/delta/10/pie/1 Now i will be be needing these parameters contained in the URL and will per...
Which gives better performance-passing parsed URL as args alongwith request or parsing URL in view-Django
I have an Django application where the URL's to be handled shall have a specific pattern like /servername/alpha/beta/2/delta/10/pie/1 Now i will be be needing these parameters contained in the URL and will persist them to the database when a URL beginning from /servername/ is being called.So i have 2 ways of doing it ...
[ "Option two is inherently slower as your view would need to do this parsing each time, whereas Django's standard URL parser works off of compiled regular expressions. (The urlpatterns in urls.py is compiled once on first run.)\nHowever, the speed difference in either approach is pretty negligible. This will never b...
[ 1 ]
[]
[]
[ "args", "django", "parsing", "python", "url" ]
stackoverflow_0008490117_args_django_parsing_python_url.txt
Q: What tools are best to investigate USB devices on Windows I have been developing some code in python/pyUSB on LINUX for a USB device primarily used on Windows. I have tried SNOOPY which does not work on Win7 to examine the messages. I have used BUSDOG which works but I want more detail. I have also used lsusb on L...
What tools are best to investigate USB devices on Windows
I have been developing some code in python/pyUSB on LINUX for a USB device primarily used on Windows. I have tried SNOOPY which does not work on Win7 to examine the messages. I have used BUSDOG which works but I want more detail. I have also used lsusb on LINUX to examine the device but I still can't see everything. Wh...
[ "A long time ago I've been using BusHound (http://www.perisoft.net). It has to advantage of being software-only, and not as expensive as a hardware solutions. This is a Windows-only solution. There is a free version, but I don't know what the limitations are.\nAnother option is to use hardware capture tools, but th...
[ 1 ]
[]
[]
[ "python", "usb" ]
stackoverflow_0008491962_python_usb.txt
Q: Loading Matlab sparse matrix using Python Pytables I originally asked a related question here, but didn't really seem to get anywhere. Perhaps if I rephrase part of it more specifically it might help.... I have files stored using Matlab's sparse format (HDF5, csc I believe), and I'm trying to use Pytables to opera...
Loading Matlab sparse matrix using Python Pytables
I originally asked a related question here, but didn't really seem to get anywhere. Perhaps if I rephrase part of it more specifically it might help.... I have files stored using Matlab's sparse format (HDF5, csc I believe), and I'm trying to use Pytables to operate on them directly, but haven't succeeded yet. Using h5...
[ "I missed seeing this in your original post but I think your issue is in the design of PyTables, which provides an extra level of abstraction on top of the underlying data.\nConsider the following:\n>>> import tables\n>>> import numpy as np\n\n>>> h5_file = tables.openFile(fname)\n>>> data = f2.root.M.data\n\nAt th...
[ 3 ]
[]
[]
[ "matlab", "numpy", "python", "scipy", "sparse_matrix" ]
stackoverflow_0008447926_matlab_numpy_python_scipy_sparse_matrix.txt
Q: Python Can't Access Windows 7 User Folder I have a wxPython app that writes user data to the Users folder at close. In most cases it works fine. However, I get some error reports from users that the app cannot write to the Users/username folder. IOError: [Errno 13] Permission denied: u\'C:\\Users\\usersname\\AppD...
Python Can't Access Windows 7 User Folder
I have a wxPython app that writes user data to the Users folder at close. In most cases it works fine. However, I get some error reports from users that the app cannot write to the Users/username folder. IOError: [Errno 13] Permission denied: u\'C:\\Users\\usersname\\AppData\\Roaming\\app\\data.dat\' What situation ca...
[ "A possible reason is that the file is locked. In this case you have no permission to write to the file until it is released.\nAre you sure you don't lock the file somehow yourself?!\n" ]
[ 1 ]
[]
[]
[ "permissions", "python", "windows" ]
stackoverflow_0008492272_permissions_python_windows.txt
Q: See Queue items in Pydev debug Is it possible, and how, to see the items in a Queue instance while debugging in PyDev, without popping them out via the interactive console? Best would be via the Expressions view of course as that would update while stepping the code A: You could use q.queue attribute to access t...
See Queue items in Pydev debug
Is it possible, and how, to see the items in a Queue instance while debugging in PyDev, without popping them out via the interactive console? Best would be via the Expressions view of course as that would update while stepping the code
[ "You could use q.queue attribute to access the underlying sequence:\n>>> q = Queue()\n>>> q.put(1)\n>>> q.queue\ndeque([1])\n\n" ]
[ 2 ]
[]
[]
[ "debugging", "pydev", "python", "queue" ]
stackoverflow_0008489697_debugging_pydev_python_queue.txt
Q: Python 2.6 virtualenv, pip throwing "ImportError: No module named _md5" I've been developing a django site (irrelevant) under python 2.5 up until now, when I wanted to switch to python 2.6 to make sure things worked there. However, when I was setting up my virtualenv for 2.6, pip threw an error "ImportError: No m...
Python 2.6 virtualenv, pip throwing "ImportError: No module named _md5"
I've been developing a django site (irrelevant) under python 2.5 up until now, when I wanted to switch to python 2.6 to make sure things worked there. However, when I was setting up my virtualenv for 2.6, pip threw an error "ImportError: No module named _md5". Background: I'm running on Ubuntu Maverick 10.10. My pyth...
[ "The problem ended up being different versions of python2.6 -- my virtualenv (which I had actually created at an earlier date to the same purpose) already had python 2.6.4 installed, while the system was up to 2.6.6.\nI had tried virtualenv <path> --no-site-packages --python=python2.6 --clear, but apparently --clea...
[ 3, 0 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0005487904_pip_python_virtualenv.txt
Q: Including Git submodules on pythonpath when using virtualenv I'm using Git for version control on a Django project. As much as possible, all the source-code that is not part of the project per se, but that the project depends on, is brought in as Git submodules. These live on a lib directory and have to be includ...
Including Git submodules on pythonpath when using virtualenv
I'm using Git for version control on a Django project. As much as possible, all the source-code that is not part of the project per se, but that the project depends on, is brought in as Git submodules. These live on a lib directory and have to be included on python path. The directory/files layout looks like: .git doc...
[ "dump all your installed packages in a requirement file (requirements.txt looks the standard naming) using\npip freeze > requirements.txt\n\neverytime you need a fresh virtualenv you just have to do:\nvirtualenv <name> --no-site-packages\npip install -r requirements.txt\n\nthe install -r requirements.txt works grea...
[ 3 ]
[]
[]
[ "django", "git", "python", "pythonpath", "virtualenv" ]
stackoverflow_0008492649_django_git_python_pythonpath_virtualenv.txt
Q: Unable to run a push queue task on Google Appengine with the Python27 SDK When trying start a simple push queue task on Google Appengine Python27 SDK (which ran fine on Python 2.5) I'm now getting a traceback ending with: File "c:\program files\google\google_appengine\google\appengine\api\taskqueue\ taskqueue_...
Unable to run a push queue task on Google Appengine with the Python27 SDK
When trying start a simple push queue task on Google Appengine Python27 SDK (which ran fine on Python 2.5) I'm now getting a traceback ending with: File "c:\program files\google\google_appengine\google\appengine\api\taskqueue\ taskqueue_stub.py", line 1662, in ExecuteTask connection.putheader(header_key, header_val...
[ "Looks like a bug and it has been reported: Issue 6460: Development Server - taskqueue stub type error \nTo get it working you'll need to patch the SDK manually, file: google/appengine/api /taskqueue/taskqueue_stub.py, line which looks like:\nheaders.append(('Content-Length', len(task.body())))\n\nfix to:\nheaders....
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008491250_google_app_engine_python.txt
Q: setting $PATH for Portable Python I've got a couple versions of Portable Python installed on my usb thumb drive so I can tinker with it when I'm away from my main computer, or if I want to try something with a different version. Right now its installed under 'F:\Portable Python 2.7.2.1\App\python.exe', which gets ...
setting $PATH for Portable Python
I've got a couple versions of Portable Python installed on my usb thumb drive so I can tinker with it when I'm away from my main computer, or if I want to try something with a different version. Right now its installed under 'F:\Portable Python 2.7.2.1\App\python.exe', which gets to be a handful to type over and over. ...
[ "If you were on *nix you could do a relative symbolic link\nI would try making your directory names much less verbose and definitely take white space out of them. How complicated are things are on your flash drive? Would this not make sense?\nF:\\python\\2.7\\python.exe\nI doubt you would have regular and portable ...
[ 0 ]
[]
[]
[ "path", "portable_python", "python" ]
stackoverflow_0008492803_path_portable_python_python.txt
Q: Can't pipe subprocesses with `python.subprocess` to resize and convert images in Django `model.save()` I want to create and modify image of website, and image can be created in right location now as below code, but I can't modify and format those images. class Bookmark(models.Model): title = models.CharField...
Can't pipe subprocesses with `python.subprocess` to resize and convert images in Django `model.save()`
I want to create and modify image of website, and image can be created in right location now as below code, but I can't modify and format those images. class Bookmark(models.Model): title = models.CharField(max_length=200) user = models.ForeignKey(User) link = models.ForeignKey(Link) def __uni...
[ "Your second process depends on the file which is generated by the first process. However the first process is not yet finished when the second is started, so png image does not yet exists. Use subprocess.call() instead, or the wait() method:\np1=subprocess.Popen(command_line, stdout=subprocess.PIPE)\nreturn_code =...
[ 0 ]
[]
[]
[ "django_models", "linux", "python", "subprocess" ]
stackoverflow_0008492848_django_models_linux_python_subprocess.txt
Q: python popen.communicate() with multiple stdin writes I have an external process that i am trying to trigger from python and then send information to via Popen.stdin.communicate(). The process I'm talking to writes a few lines to stdout then prompts the user for input via stdin (a number) it then writes a few ore ...
python popen.communicate() with multiple stdin writes
I have an external process that i am trying to trigger from python and then send information to via Popen.stdin.communicate(). The process I'm talking to writes a few lines to stdout then prompts the user for input via stdin (a number) it then writes a few ore lines and prompts for a second input via stdin. I want to r...
[ "As per python's documentation:\n\nNote that if you want to send data to the process’s stdin, you need to\n create the Popen object with stdin=PIPE. Similarly, to get anything\n other than None in the result tuple, you need to give stdout=PIPE\n and/or stderr=PIPE too.\n\n" ]
[ 0 ]
[]
[]
[ "pipe", "python", "stdin", "stdout", "stream" ]
stackoverflow_0008493102_pipe_python_stdin_stdout_stream.txt
Q: How to get log axes for a density plot with matplotlib? I am trying to make a 2D density plot (from some simulation data) with matplotlib. My x and y data are defined as the log10 of some quantities. How can I get logarithmic axes (with log minor ticks)? Here is an exemple of my code: import numpy as np import ma...
How to get log axes for a density plot with matplotlib?
I am trying to make a 2D density plot (from some simulation data) with matplotlib. My x and y data are defined as the log10 of some quantities. How can I get logarithmic axes (with log minor ticks)? Here is an exemple of my code: import numpy as np import matplotlib.pyplot as plt Data = np.genfromtxt("data") # A 2-co...
[ "From the matplotlib.pyplot.hist docstring, it looks like there is a 'log' argument to set to 'True' if you want log scale on axis.\nhist(x, bins=10, range=None, normed=False, cumulative=False,\n bottom=None, histtype='bar', align='mid',\n orientation='vertical', rwidth=None, log=False, **kwargs)\n\nlog:\nI...
[ 4, 3, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007688077_matplotlib_python.txt
Q: Hello World in Python I tried running a python script: print "Hello, World!" And I get this error: File "hello.py", line 1 print "Hello, World!" ^ SyntaxError: invalid syntax What is going on? A: print("Hello, World!") You are probably using Python 3.0, where print is now a func...
Hello World in Python
I tried running a python script: print "Hello, World!" And I get this error: File "hello.py", line 1 print "Hello, World!" ^ SyntaxError: invalid syntax What is going on?
[ "print(\"Hello, World!\")\n\nYou are probably using Python 3.0, where print is now a function (hence the parenthesis) instead of a statement.\n", "Unfortunately the xkcd comic isn't completely up to date anymore.\n\nSince Python 3.0 you have to write:\nprint(\"Hello world!\")\n\nAnd someone still has to write tha...
[ 186, 114, 16 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001077347_python_python_3.x.txt
Q: Django serves zero byte response This just happened to one of my sites and I have no idea what caused it. This happens for any URL that is served by mod_wsgi for a particular application, which used to work fine. Syntax errors in settings.py cause HTTP 500. Syntax errors in urls.py don't influence anything—seems ...
Django serves zero byte response
This just happened to one of my sites and I have no idea what caused it. This happens for any URL that is served by mod_wsgi for a particular application, which used to work fine. Syntax errors in settings.py cause HTTP 500. Syntax errors in urls.py don't influence anything—seems like this file is never loaded. What i...
[ "The culprit was this line:\nfrom django.contrib.auth.forms import AuthenticationForm\n\nin middleware.py.\nMoving the import into the function that uses AuthenticationForm solved the problem:\nfrom django.http import HttpResponseRedirect\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom ...
[ 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0008491977_apache_django_mod_wsgi_python.txt
Q: Assigning instances in os.walk in python I am trying to create a walker that goes through directories. Here are the inputs and outputs which I have partly working. I am using a test directory but I would like this to be done on any directory which is leading to some problems. [IN]: print testdir #name of the dire...
Assigning instances in os.walk in python
I am trying to create a walker that goes through directories. Here are the inputs and outputs which I have partly working. I am using a test directory but I would like this to be done on any directory which is leading to some problems. [IN]: print testdir #name of the directory [OUT]: ['j','k','l'] #directories under...
[ "I assume you want sub-dir to be accessible like a attribute, you can achieve that two ways\n\nGo thru list of files and create variables dynamically\nHook into attribute access and correctly return listers as needed\n\nI prefer second approach as it is lazy, better and easier to implement\nimport os\n\nclass DirLi...
[ 1, 0 ]
[]
[]
[ "instances", "python" ]
stackoverflow_0008493166_instances_python.txt
Q: Autocomplete for namedtuples (python) for Pydev, Eclipse? As above, I'd love to have some autocompleting for namedtuples in python, is there anyway to do? I use Pydev. A: PyDev doesn't currently analyze namedtuples to give you a better introspection for it. Please enter that as a feature request in the PyDev tra...
Autocomplete for namedtuples (python) for Pydev, Eclipse?
As above, I'd love to have some autocompleting for namedtuples in python, is there anyway to do? I use Pydev.
[ "PyDev doesn't currently analyze namedtuples to give you a better introspection for it. Please enter that as a feature request in the PyDev tracker (see: http://pydev.org/about.html for links).\n" ]
[ 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0008466094_eclipse_pydev_python.txt
Q: Matplotlib: Centroid of Scatter Plot Circles I have a Matplotlib scatter plot, plotting 3 different circles and I am trying to find the axes x, y coordinates of the center point of each of these circles, i.e. a number within the bbox between 0 and 1. I am trying to do this because I save the image to a .png file a...
Matplotlib: Centroid of Scatter Plot Circles
I have a Matplotlib scatter plot, plotting 3 different circles and I am trying to find the axes x, y coordinates of the center point of each of these circles, i.e. a number within the bbox between 0 and 1. I am trying to do this because I save the image to a .png file and want to find the corresponding x,y point in the...
[ "I think you might be interested in the ax.transData transformation. Using the transform method, you can convert points in 'Data' units to display units. See the transformation tutorial for more information about this. \nBelow I have an example that includes an axes that fills the whole plot, so it is a bit easier ...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008492890_matplotlib_python.txt
Q: CGI Script that prints out an incoming param I am trying to write out a python cgi script that will redirect me to a page that prints out one of the incoming params. The rewrite rule looks like this: RewriteRule ^(.*)$ /cgi-bin/redirect.py?url=%{HTTP_HOST}$1 [L,QSA,PT]. Basically all I want to do is print out the ...
CGI Script that prints out an incoming param
I am trying to write out a python cgi script that will redirect me to a page that prints out one of the incoming params. The rewrite rule looks like this: RewriteRule ^(.*)$ /cgi-bin/redirect.py?url=%{HTTP_HOST}$1 [L,QSA,PT]. Basically all I want to do is print out the param url between <h1></h1> tags. I have never wri...
[ "There are lots of resources on the internet for Hello World-type programs. Or you could go with the standard documentation for the answer.\n", "I don't know what \"[L,QSA,PT]\" does, but I would do something like ^(.*)$ /cgi-bin/redirect.py\nredirect.py should look something like:\n#!/usr/bin/env python\nprint \...
[ 0, 0 ]
[]
[]
[ "apache2", "cgi", "python" ]
stackoverflow_0008425215_apache2_cgi_python.txt
Q: add and delete events from iCalendar? I'm working on a small python program that automatically schedules events to my iCalendar. I've got most of it finished, and am at a place where I have all the information I need about an event, I just don't know how to interface with iCal. I've tagged applescript, because i...
add and delete events from iCalendar?
I'm working on a small python program that automatically schedules events to my iCalendar. I've got most of it finished, and am at a place where I have all the information I need about an event, I just don't know how to interface with iCal. I've tagged applescript, because if it is easier to schedule an event via tha...
[ "Opening AppleScript Editor and looking at the library for iCal isn't a bad idea.\nHere's an example:\ntell application \"iCal\"\n tell calendar \"My Calendar\"\n set theDate to current date\n make new event at end with properties {description:\"Event Description\", \n summary:\"Event Name\", lo...
[ 0 ]
[]
[]
[ "applescript", "icalendar", "python" ]
stackoverflow_0008493892_applescript_icalendar_python.txt
Q: Is there a way to lookup all reviews of a customer in Amazon's new Product Advertising API? Using ecs.py, I used to be able to get the reviews of a customer with a query like ecs.CustomerContentLookup(customerId, ResponseGroup='CustomerReviews'). This is now deprecated. Is there an alternative? Thanks.
Is there a way to lookup all reviews of a customer in Amazon's new Product Advertising API?
Using ecs.py, I used to be able to get the reviews of a customer with a query like ecs.CustomerContentLookup(customerId, ResponseGroup='CustomerReviews'). This is now deprecated. Is there an alternative? Thanks.
[]
[]
[ "Have you looked at using web page scraping to fetch/get the customer reviews / ratings?\nIf you know the customer id you should be able to extract all the information you need directly from the Amazon web pages.\n" ]
[ -1 ]
[ "amazon_web_services", "python" ]
stackoverflow_0008483263_amazon_web_services_python.txt
Q: Error in OpenERP I have some problem with my project: def get_timein(self, cr, uid, ids, context={}): obj = self.browse(cr, uid, ids, context=context)[0] timein = str(datetime.now()) self.write(cr, uid, ids, {'time_in':timein }, context=context) return 1 def get_timeout(self, cr, uid, ids, context...
Error in OpenERP
I have some problem with my project: def get_timein(self, cr, uid, ids, context={}): obj = self.browse(cr, uid, ids, context=context)[0] timein = str(datetime.now()) self.write(cr, uid, ids, {'time_in':timein }, context=context) return 1 def get_timeout(self, cr, uid, ids, context={}): obj=self.bro...
[ "def cho_dangnhap(self,cr,uid,ids,context={}):\n self.pool.get('x_luong').write(cr,uid,ids,{'state':'dangnhap'})\n self.get_timein(cr,uid,ids)\n return 1\ndef cho_rave(self,cr,uid,ids,context={}):\n self.pool.get('x_luong').write(cr,uid,ids,{'state':'rave'})\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008494136_python.txt