Qt with PyDev
I installed Aptana PyDev plugin to Aptana Studio 3 Beta. I want to write my first GUI application using Python and I want to use Qt for it. How to integrate Qt into PyDev, or is there any other alternative IDE to work with Qt?elementFontfont-familyfont-sizefont-stylefont-variantfont-weightletter-spacingline-heighttext-decorationtext-aligntext-indenttext-transformwhite-spaceword-spacingcolorBackgroundbg-attachmentbg-colorbg-imagebg-positionbg-repeatBoxwidthheightborder-topborder-rightborder-bottomborder-leftmarginpaddingmax-heightmin-heightmax-widthmin-widthoutline-coloroutline-styleoutline-widthPositioningpositiontopbottomrightleftfloatdisplayclearz-indexListlist-style-imagelist-style-typelist-style-positionTablevertical-alignborder-collapseborder-spacingcaption-sideempty-cellstable-layoutEffectstext-shadow-webkit-box-shadowborder-radiusOtheroverflowcursorvisibility ...Rohit -- http://mail.python.org/mailman/listinfo/python-list
Re: CPython on the Web
On 1/3/2011 11:13 PM, azakai wrote: On Jan 3, 10:11 pm, John Nagle wrote: On 1/1/2011 11:26 PM, azakai wrote: Hello, I hope this will be interesting to people here: CPython running on the web, http://syntensity.com/static/python.html That isn't a new implementation of Python, but rather CPython 2.7.1, compiled from C to JavaScript using Emscripten and LLVM. For more details on the conversion process, seehttp://emscripten.org It's a cute hack, but it's about 1000 times slower than CPython. Yes, as I said, "the code isn't optimized (so don't expect good performance)" :) It can get much faster with more work. Yea, right. You're three deep in interpreters. Performance is going to suck. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: list 2 dict?
or only convert the item when you need it leaving the lists as the source lyst = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b'] func = lambda alist, index: dict([(lyst[index*2], lyst[(index*2)+1]),]) func(lyst, 0) {1: 2} func(lyst, 2) {5: 6} ## or as a function def func(lyst, index): return dict(((lyst[index], lyst[index+1]),)) -- http://mail.python.org/mailman/listinfo/python-list
Matrix multiplication
Please, can anybody write me a simple recursive matrix multiplication using multiple threads in Python, or at least show me some guidelines how to write it myself Thank You -- http://mail.python.org/mailman/listinfo/python-list
PyPi question
Dear all, I am the PyUSB author and recently I was asked to update pyusb package in the PyPi. The point is that I am not the maintainer and don't know who is. Now I need to contact the current package maintainer but I could not find how to do so through PyPi (as maintainer's email does not show). Does anyone know how am I supposed to proceed (open a support request, maybe) ? Thanks in advance. -- Best Regards, Wander Lairson Costa LCoN - Laboratório de Computação Natural - Natural Computing Laboratory (http://www.mackenzie.com.br/lcon.html) Programa de Pós-Graduação em Engenharia Elétrica (PPGEE) Faculdade de Computação e Informática (FCI) Universidade Presbiteriana Mackenzie - SP - Brazil -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
Zdenko wrote: > Please, can anybody write me a simple recursive matrix multiplication > using multiple threads in Python, or at least show me some guidelines > how to write it myself No problem, I just need your bank account data to withdraw the payment and the address of your teacher whom to send the results. ;^) Seriously, things don't work like this. If you show effort, you will get help, but you don't get working solutions without even a bit of effort on your own. Start with a recursive algorithm, then make it multithreaded. Be prepared to make some experiments on how to distribute tasks to threads and collect them again. Uli -- http://mail.python.org/mailman/listinfo/python-list
CFP - ViNOrg 11 - 1st International Conference on Virtual and Networked Organizations: Emergent Technologies and Tools
2011-01-04
Thread
CFP - 1st International Conference on Virtual and Networked Organizations Emergent Technologies and Tools
ViNOrg 11 1st International Conference on Virtual and Networked Organizations Emergent Technologies and Tools -- Paper submission deadline: April 17, 2011 -- http://www.2100projects.org/vinorg11 vin...@2100projects.org -- Dear Professor, It is our great pleasure to invite you to participate in the 1st International Conference on Virtual and Networked Organizations Emergent Technologies and Tools, ViNOrg 11, to be held in Ofir, Portugal, from July 6-8, 2011. ViNOrg 11 is promoted by the 2100 Projects Association Scientific Association for Promotion of Technology and Management for Organizational and Social Transformative Change. The overall objectives of the conference are to contribute to the development, implementation and promotion of advanced emergent IC technologies to be used in future Virtual and Networked Organizations, through the discussion and sharing of knowledge, as well as experiences and scientific and technical results. A shortlist of intended topics include: metaverse, virtual and augmented reality, ubiquitous computing and organizations, grid computing, cloud computing and architectures, human-computer interfaces, serious games, intelligence and soft computing, data mining, web services, cognitive systems, social networks and other emergent IT/IS approaches in various function domains, such as decision support systems, planning, design, control, negotiation, marketing, management and many other, in the context of virtual and networked enterprises and organizations. All accepted full papers will be published in the Conference Proceedings to be published by Springer-Verlag in a book of the CCIS series (Communications in Computer and Information Science), which is listed in the ISI proceedings index. Authors of selected papers will be invited to extend their papers for publication in some international scientific journals. For more information please consult the conference webpage at http://www.2100projects.org/vinorg11 Looking forward to meeting you in Ofir (Portugal) next July 2011, accept our best regards. The conference co-chairs, * Goran D. Putnik (putni...@dps.uminho.pt), University of Minho, Portugal * Maria Manuela Cruz-Cunha (mcu...@ipca.pt), Polytechnic Institute of Cavado and Ave, Portugal -- http://www.2100projects.org/vinorg11 vin...@2100projects.org -- You are receiving this email because of your research activities on the conference related topics. To unsubscribe please send an email to vin...@2100projects.org with the subject "Unsubscribe". (please excuse us if you received this call more than once). -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On 4 jan, 11:15, Ulrich Eckhardt wrote: > Zdenko wrote: > > Please, can anybody write me a simple recursive matrix multiplication > > using multiple threads in Python, or at least show me some guidelines > > how to write it myself > > No problem, I just need your bank account data to withdraw the payment and > the address of your teacher whom to send the results. ;^) > > Seriously, things don't work like this. If you show effort, you will get > help, but you don't get working solutions without even a bit of effort on > your own. > > Start with a recursive algorithm, then make it multithreaded. Be prepared to > make some experiments on how to distribute tasks to threads and collect > them again. > > Uli Hi, just have a look here http://en.wikipedia.org/wiki/Matrix_multiplication and find out what parts can be parallelized ;) Gregory LEOCADIE -- http://mail.python.org/mailman/listinfo/python-list
Re: CPython on the Web
On Jan 3, 4:55 pm, azakai wrote: > But through a combination of optimizations on the side of Emscripten > (getting all LLVM optimizations to work when compiling to JS) and on > the side of the browsers (optimizing accesses on typed arrays in JS, > etc.), then I hope the code will eventually run quite fast, even > comparably to C. This is a very cool idea. It's quite fascinating to view the Javascript "machine code" for a complete CPython interpreter. I'm sure with a little work you'll be able to improve its performance, but I think "comparably to C" is going to be a tall order. If you can get this to work reasonably well, and manage to get it successfully deployed it somewhere, I'd recommend petitioning to have this be considered an official platform. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On 4.1.2011 11:15, Ulrich Eckhardt wrote: Zdenko wrote: Please, can anybody write me a simple recursive matrix multiplication using multiple threads in Python, or at least show me some guidelines how to write it myself No problem, I just need your bank account data to withdraw the payment and the address of your teacher whom to send the results. ;^) Seriously, things don't work like this. If you show effort, you will get help, but you don't get working solutions without even a bit of effort on your own. Start with a recursive algorithm, then make it multithreaded. Be prepared to make some experiments on how to distribute tasks to threads and collect them again. Uli Ok, I expected something like this :) Lets try this way: I wrote these two codes for example: this one is naive way of matrix multiplication using one thread from random import * from time import clock import threading t0 = clock() A=[] B=[] C=[] m=300 #size of matrix m x m for i in range(m): A.append([]) B.append([]) C.append([]) for j in range(m): A[i].append(randint(1,9)) B[i].append(randint(1,9)) C[i].append(0) class MyThread ( threading.Thread ): def run ( self ): for i in range(m): for j in range(m): for k in range(m): C[i][j]+=A[i][k]*B[k][j] t=MyThread() t.start() t.join() print clock() - t0, "seconds" this one is using two threads, each one is multiplying half of matrix import time from threading import Thread from random import randint t0 = time.clock() class MyThread(Thread): def __init__(self, poc, kr): Thread.__init__(self) self.poc=poc self.kr=kr def run(self): for i in range(self.poc,self.kr): for j in range(m): for k in range(m): C[i][j]+=A[i][k]*B[k][j] A=[] B=[] C=[] m=300 #size of matrix m x m for i in range(m): A.append([]) B.append([]) C.append([]) for j in range(m): A[i].append(randint(1,9)) B[i].append(randint(1,9)) C[i].append(0) thr1=MyThread(0,m/2) thr2=MyThread(m/2,m) thr1.start() thr2.start() thr1.join() thr2.join() print time.clock() - t0, "seconds" why is second one more than twice slower than first when it should be faster. I suspect that problem is in simultaneous access to matrix C but i don't know how to solve this. I used this just for example to see how the threading works so i can work on recursive and Strassen algorithm. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python comparison matrix
Awesome, thanks so much for you efforts and sharing. Idea: It would be great if we put this table into a python program where I can run a script against this table and a Python source code module (file) so that it would spit out a list of strings showing what python versions work with said source code file. python.exe get_versions.py myPythonSourceFile.py -insertMetaInfo Would prepend a text line to myPythonSourceFile.py in some format like: # __requires_python__ = ["Python 2.5-2.7"] or # __requires_python__ = ["Python", "2.5.x", "2.6.x", "2.7.x"] or # __requires_python__ = {"1.0.x":False, ..., "2.5.x":True, "2.6.x":True, "2.7.x":True] where key format is comparable agains on of the following: sys.version, sys.version_info, sys.winver, sys.api_version, sys.subversion Idea: Perhaps add the table you made a list of which libraries/packages are included in the distro to the different releases. Comparable against sys.builtin_module_names Anyone ambisous enough to play with those idea, be my guest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On 4 Gen, 07:13, Jean-Paul Calderone wrote: > On Jan 3, 6:17 pm, Adam Skutt wrote: > > > On Jan 3, 5:24 pm, Jean-Paul Calderone > > wrote: > > > > Of course. The whole point here is not about threads vs processes. > > > It's about shared memory concurrency vs non-shared memory > > > concurrency. You can implement both with threads and both with > > > processes, but threads are geared towards shared memory and processes > > > are geared towards non-shared memory. So what most people mean by > > > "use processes" is "don't use shared memory". > > > This is entirely my presumption, but I think if the OP were keenly > > aware of the differences between thread and processes, it's pretty > > likely he wouldn't have asked his question in the first place. > > Fair enough. :) > > > Also, I've written lots and lots of "use processes" code on multiple > > platforms, and much of it has used some sort of shared memory > > construct. It's actually pretty common, especially in code bases with > > a lot of history. Not all the world is Apache. > > Hee hee, Apache. :) > > > > > Adam- Nascondi testo citato > > - Mostra testo citato - BTW thanks for the suggestions. As in my original code snippet, the shared object that the threads are using is the Queue, that itself implement locking mechanism so I don't have to worry about concurrent access. Regarding my question, it was just to have a hint on how a thread termination can be handled as, per example, you have the consumer-producer pattern. Mattia -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On Dec 29 2010, 11:31 pm, gervaz wrote: > Hi all, I need to stop a threaded (using CTR+C or kill) application if > it runs too much or if I decide to resume the work later. > I come up with the following test implementation but I wanted some > suggestion from you on how I can implement what I need in a better or > more pythonic way. Here the code: This is a case that .NET (C#) handles better than Python or Java. It is unsafe to terminate an os level thread at an arbitrary point because it may be executing code in a critical section. Both Java and .NET used to provide ways to terminate threads "safely" by raising an asynchronous exception in the thread. Releasing locks (etc) that the thread holds could then be done in a finally section protecting the code. Python doesn't allow you to abort threads. Unfortunately the thread abort exception could also be raised in the finally section - prematurely aborting the lock / resource cleanup. Java handled this by deprecating thread aborting. (Python has never had it I believe.) .NET handled it by changing the semantics of thread aborting - the thread abort exception will never be raised in a finally block. This makes thread aborting safe, although technically you can subvert it by putting all your code in a finally block (you can also catch and cancel the thread abort exception). The standard advice is to use a flag and do manual checking to abort threads. This only works for fine grained operations and *doesn't* work for very coarse grained operations or where there aren't convenient places to check the flag. It's another place where people sometimes have a genuine need/use case yet people will insist on telling them they don't *really* want it... Anyway, although there are ways based on ctypes to abort Python threads it's not really safe. If you google you should find them, hopefully with intelligible caveat emptor warnings... All the best, Michael Foord > > import os > import signal > import time > from threading import Thread, current_thread > from queue import LifoQueue, Empty > > COMMAND = {"STOP": 0, "NORMAL": 1} > THREAD_NUM = 5 > > lq = LifoQueue() > > print("{0}\n".format(os.getpid())) > > class InterceptInterrupt(Exception): > pass > > class Handler: > def __init__(self, queue): > self._queue = queue > def __del__(self): > print("Bye bye!") > def getHandler(self, signum, frame): > print("Interrupt raised!") > for _ in range(THREAD_NUM): > self._queue.put((COMMAND["STOP"], None)) > raise InterceptInterrupt > > h = Handler(lq) > > signal.signal(signal.SIGINT, h.getHandler) > > for i in range(25): > lq.put((COMMAND["NORMAL"], i)) > > def do_work(queue): > while True: > time.sleep(5) > try: > cmd, value = queue.get(block=False) > if cmd == COMMAND["STOP"]: > print("{0}: STOP command > received!".format(current_thread().name)) > break > elif cmd == COMMAND["NORMAL"]: > print(value) > except Empty: > break > > threads = [Thread(target=do_work, args=(lq,)) for _ in > range(THREAD_NUM)] > > for t in threads: > t.start() > > while not lq.empty(): > try: > time.sleep(1) > except (IOError, InterceptInterrupt): > break > > for t in threads: > t.join() > > if lq.empty(): > print("The queue is empty.") > else: > print("The queue is NOT empty. Some additional work has to be > done.") > > Thank you, > Mattia -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On Jan 4, 3:12 pm, Fuzzyman wrote: > On Dec 29 2010, 11:31 pm, gervaz wrote: > > > Hi all, I need to stop a threaded (using CTR+C or kill) application if > > it runs too much or if I decide to resume the work later. > > I come up with the following test implementation but I wanted some > > suggestion from you on how I can implement what I need in a better or > > more pythonic way. Here the code: > > This is a case that .NET (C#) handles better than Python or Java. > Heh, so one possible option is to use IronPython :-) Michael Foord > It is unsafe to terminate an os level thread at an arbitrary point > because it may be executing code in a critical section. Both Java > and .NET used to provide ways to terminate threads "safely" by raising > an asynchronous exception in the thread. Releasing locks (etc) that > the thread holds could then be done in a finally section protecting > the code. Python doesn't allow you to abort threads. > > Unfortunately the thread abort exception could also be raised in the > finally section - prematurely aborting the lock / resource cleanup. > > Java handled this by deprecating thread aborting. (Python has never > had it I believe.) > > .NET handled it by changing the semantics of thread aborting - the > thread abort exception will never be raised in a finally block. This > makes thread aborting safe, although technically you can subvert it by > putting all your code in a finally block (you can also catch and > cancel the thread abort exception). > > The standard advice is to use a flag and do manual checking to abort > threads. This only works for fine grained operations and *doesn't* > work for very coarse grained operations or where there aren't > convenient places to check the flag. It's another place where people > sometimes have a genuine need/use case yet people will insist on > telling them they don't *really* want it... > > Anyway, although there are ways based on ctypes to abort Python > threads it's not really safe. If you google you should find them, > hopefully with intelligible caveat emptor warnings... > > All the best, > > Michael Foord > > > > > import os > > import signal > > import time > > from threading import Thread, current_thread > > from queue import LifoQueue, Empty > > > COMMAND = {"STOP": 0, "NORMAL": 1} > > THREAD_NUM = 5 > > > lq = LifoQueue() > > > print("{0}\n".format(os.getpid())) > > > class InterceptInterrupt(Exception): > > pass > > > class Handler: > > def __init__(self, queue): > > self._queue = queue > > def __del__(self): > > print("Bye bye!") > > def getHandler(self, signum, frame): > > print("Interrupt raised!") > > for _ in range(THREAD_NUM): > > self._queue.put((COMMAND["STOP"], None)) > > raise InterceptInterrupt > > > h = Handler(lq) > > > signal.signal(signal.SIGINT, h.getHandler) > > > for i in range(25): > > lq.put((COMMAND["NORMAL"], i)) > > > def do_work(queue): > > while True: > > time.sleep(5) > > try: > > cmd, value = queue.get(block=False) > > if cmd == COMMAND["STOP"]: > > print("{0}: STOP command > > received!".format(current_thread().name)) > > break > > elif cmd == COMMAND["NORMAL"]: > > print(value) > > except Empty: > > break > > > threads = [Thread(target=do_work, args=(lq,)) for _ in > > range(THREAD_NUM)] > > > for t in threads: > > t.start() > > > while not lq.empty(): > > try: > > time.sleep(1) > > except (IOError, InterceptInterrupt): > > break > > > for t in threads: > > t.join() > > > if lq.empty(): > > print("The queue is empty.") > > else: > > print("The queue is NOT empty. Some additional work has to be > > done.") > > > Thank you, > > Mattia -- http://mail.python.org/mailman/listinfo/python-list
Re: Qt with PyDev
On 01/04/2011 12:00 AM, RP Khare wrote: I installed Aptana PyDev plugin to Aptana Studio 3 Beta. I want to write my first GUI application using Python and I want to use Qt for it. How to integrate Qt into PyDev, or is there any other alternative IDE to work with Qt? element Font font-family font-size font-style font-variant font-weight letter-spacing line-height text-decoration text-align text-indent text-transform white-space word-spacing color Background bg-attachment bg-color bg-image bg-position bg-repeat Box width height border-top border-right border-bottom border-left margin padding max-height min-height max-width min-width outline-color outline-style outline-width Positioning position top bottom right left float display clear z-index List list-style-image list-style-type list-style-position Table vertical-align border-collapse border-spacing caption-side empty-cells table-layout Effects text-shadow -webkit-box-shadow border-radius Other overflow cursor visibility ... Rohit See either of these packages: PyQt: http://qt.nokia.com/products/ PySide: http://www.pyside.org/ Either one should work with PyDev. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
In article <2ebc11a5-1b45-4faa-97b9-c84f0db01...@k22g2000yqh.googlegroups.com>, Fuzzyman wrote: > It is unsafe to terminate an os level thread at an arbitrary point > because it may be executing code in a critical section. > [...] > The standard advice is to use a flag and do manual checking to abort > threads. This only works for fine grained operations and *doesn't* > work for very coarse grained operations or where there aren't > convenient places to check the flag. Another possibility is to not use threads! If you 1) Need asynchronous operation 2) Need iterruptability 3) Can't poll for an "please stop" signal You should look at running your "thread" as a separate process, which you can send a kill signal to when you want it to go away. You can then communicate with it via pipes, sockets, shared memory segments, whatever. Threads are a wonderful invention, but they are not a panacea for all possible parallelism tasks. Sometimes they're just the wrong tool. -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
I would be very suprised if you achieve faster results threading this problem. There's been much discussed on benefits or lack thereof to threading in Python (or in general). Threading is best used in situations where you are doing different kinds of tasks. For example if you want to do your matrix multiplication WHILE you were doing other things on your computer where matrix multiplication was a background process chugging away when you are not taxing the computer doing other stuff. Threading adds efficiency when you would have lots of "blocking" operations like reading in lots of big files from a comparable slow hard drive (compared to how fast a CPU processes data) or waiting on netword data (super slow compared to CPU processing). When you are doing mass numeric processing, you want to minimize the jumping from one function to another which uses overhead, recursion adds a small amount of uneccessary overhead, you want to minimize the need for the cpu to switch between threads or processes. If you still feel the need to use threads for some reason, for numeric processing I'd recommend using a "lighter" thread object, like a tiny thread or green thread or a threadlet or whatever they are calling them now. Another thing to note is it seems you might be expecting threads to run on different CPU cores expecting improvment. Be careful with this assumption. This is not always true. It is up to the CPU and OS to determine how threads are handled and perhaps the GIL to some extent. Beaware that Python has a GIL (some distributions). Google it if you don't know of it. To encourage better use of multi-core cpus you might consider the multiprocessing library included in Python 2.7 (I think) and above. I'm assuming that speed is an issue because you where timing your code. If you are doing actual serious number crunching there's lots of advice on this. The python Numpy package as well as Stackless Python (for microthreads or whatever thier called) comes to mind. Another thought. Ask yourself if you need a large in-memory or live set of processed numbers, in your case a fully and processed multiplied matrix. Usually a large set of in-memory numbers is something your going to use to simulate a model or to process and crunch further. Or is your actual usage going to be picking out a processed number here or there from the matrix. If this is true look at iterators or generators. Which would be a snapshot in time of your matrix multiplication. I like to think of Python generators like integral calculus (definition at: http://en.wikipedia.org/wiki/Integral_calculus) where the specific integral of a generator is often just 1. I'm loving generators a lot. For example there are generator accelorators which if you think it through means you can make generator deccelorators, useful for doing interpolation between elements of your matrix elements for example. I always forget if generators are thread safe though. Some indicators that generators could help: You're doing lots of for loops with range(). Also it's been measured that list comprehensions are slightly faster then while loops are a slightly faster then for loops. You can Google to confirm, enter something like "python fast iteration". Also if your numbers in your matix are actually not really numbers but objects with numbers, __slots__ is used to for large sets of objects (10s of millions at the very least) to minimize memory usage and perhaps with speed, if used properly. Just mentioning. I'd stay away from this though. Some of my informatation may be inaccurate (and even completely wrong; like I always get when a thread is best switched during a blocking verse a non-blocking operation) but there are some things to consider. -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
BTW http://www.python.org/dev/peps/pep-0211/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
See section titled: "'array' or 'matrix'? Which should I use?" at http://www.scipy.org/NumPy_for_Matlab_Users BTW http://www.python.org/dev/peps/pep-0211/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On Tue, Jan 4, 2011 at 4:22 AM, Zdenko wrote: > On 4.1.2011 11:15, Ulrich Eckhardt wrote: >> >> Zdenko wrote: >>> >>> Please, can anybody write me a simple recursive matrix multiplication >>> using multiple threads in Python, or at least show me some guidelines >>> how to write it myself >> >> No problem, I just need your bank account data to withdraw the payment and >> the address of your teacher whom to send the results. ;^) >> >> Seriously, things don't work like this. If you show effort, you will get >> help, but you don't get working solutions without even a bit of effort on >> your own. >> >> Start with a recursive algorithm, then make it multithreaded. Be prepared >> to >> make some experiments on how to distribute tasks to threads and collect >> them again. >> >> Uli >> > > Ok, I expected something like this :) > Lets try this way: > > I wrote these two codes for example: > > this one is naive way of matrix multiplication using one thread > > from random import * > from time import clock > import threading > > t0 = clock() > A=[] > B=[] > C=[] > m=300 #size of matrix m x m > > for i in range(m): > A.append([]) > B.append([]) > C.append([]) > for j in range(m): > A[i].append(randint(1,9)) > B[i].append(randint(1,9)) > C[i].append(0) > > class MyThread ( threading.Thread ): > > def run ( self ): > for i in range(m): > for j in range(m): > for k in range(m): > C[i][j]+=A[i][k]*B[k][j] > > t=MyThread() > t.start() > t.join() > print clock() - t0, "seconds" > > > > this one is using two threads, each one is multiplying half of matrix > > import time > from threading import Thread > from random import randint > > t0 = time.clock() > class MyThread(Thread): > def __init__(self, poc, kr): > Thread.__init__(self) > self.poc=poc > self.kr=kr > def run(self): > for i in range(self.poc,self.kr): > for j in range(m): > for k in range(m): > C[i][j]+=A[i][k]*B[k][j] > > A=[] > B=[] > C=[] > m=300 #size of matrix m x m > > for i in range(m): > A.append([]) > B.append([]) > C.append([]) > for j in range(m): > A[i].append(randint(1,9)) > B[i].append(randint(1,9)) > C[i].append(0) > thr1=MyThread(0,m/2) > thr2=MyThread(m/2,m) > thr1.start() > thr2.start() > thr1.join() > thr2.join() > print time.clock() - t0, "seconds" > > why is second one more than twice slower than first when it should be > faster. I suspect that problem is in simultaneous access to matrix C but i > don't know how to solve this. > > I used this just for example to see how the threading works so i can work on > recursive and Strassen algorithm. > -- > http://mail.python.org/mailman/listinfo/python-list > Threads in CPython are decent when you're doing I/O, not so good when you're doing CPU-bound tasks. When you're doing CPU-bound tasks, you may actually find that your application runs about 1/n times as fast, where n is the number of CPU's - that is, much slower. I don't mean that it just doesn't scale well, I mean that each additional CPU makes things slower for CPU-bound jobs. If you require java-like threading, you might be better off with Jython or Iron Python for now. pypy's likely to have good threading eventually, but last I heard it wasn't quite there yet. If you do require CPython, you might check out the greenlets module and/or PyCSP. Oh, and there's "stackless python", which amounts to a branch of CPython that's unlikely to be merged. It's supposed to be able to thread really well, and ISTR hearing that it's pretty similar to greenlets. The main force behind stackless is working on pypy now, I believe. Finally, with CPython, you can use the multiprocessing module to get pretty good parallelism via distinct processes. This way you tend to end up using queues for interprocess communication; these queues use shared memory. However, you might actually be able to put your matrix in shared memory - if it's large enough to justify that. I know you could put a linear array of homogeneous, scalar type in shared memory; I've not heard of a way of putting an aggregate type in shared memory. Naturally, you can fake an n dimensional array using a 1 dimensional array with a little multiplication and addition. As an example of using CPython with multiprocessing without having your matrix in shared memory, you could probably have one worker subprocess for each core on a system, divide up the cells of your result matrix by their coordinates (perhaps using an iterator and izip across the queues) and send a message (via a shared memory queue) with those coordinates to the appropriate subprocess. Then those subprocess send back the coordinates and the result at said coordinate via a different result queue. I suspect you'd want one queue for all the results, and one queue for each subprocess for initiating computati
Regular Expression for Finding and Deleting comments
I am trying to write a regular expression that finds and deletes (replaces with nothing) comments in a string/file. Comments are defined by the first non-whitespace character is a 'c' or a dollar sign somewhere in the line. I want to replace these comments with nothing which isn't too hard. The trouble is, the comments are replaced with a new-line; or the new-line isn't captured in the regular expression. Below, I have copied a minimal example. Can someone help? Thanks, Jeremy import re text = """ c C - Second full line comment (first comment had no text) c Third full line comment F44:N 2$ Inline comments start with dollar sign and go to end of line""" commentPattern = re.compile(""" (^\s*?c\s*?.*?| # Comment start with c or C \$.*?)$\n # Comment starting with $ """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) found = commentPattern.finditer(text) print("\n\nCard:\n--\n%s\n--" %text) if found: print("\nI found the following:") for f in found: print(f.groups()) else: print("\nNot Found") print("\n\nComments replaced with ''") replaced = commentPattern.sub('', text) print("--\n%s\n--" %replaced) -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On Jan 4, 3:31 pm, Roy Smith wrote: > In article > <2ebc11a5-1b45-4faa-97b9-c84f0db01...@k22g2000yqh.googlegroups.com>, > > Fuzzyman wrote: > > It is unsafe to terminate an os level thread at an arbitrary point > > because it may be executing code in a critical section. > > [...] > > The standard advice is to use a flag and do manual checking to abort > > threads. This only works for fine grained operations and *doesn't* > > work for very coarse grained operations or where there aren't > > convenient places to check the flag. > > Another possibility is to not use threads! If you > > 1) Need asynchronous operation > > 2) Need iterruptability > > 3) Can't poll for an "please stop" signal > > You should look at running your "thread" as a separate process, which > you can send a kill signal to when you want it to go away. You can then > communicate with it via pipes, sockets, shared memory segments, whatever. > > Threads are a wonderful invention, but they are not a panacea for all > possible parallelism tasks. Sometimes they're just the wrong tool. However some tasks / algorithms are done much better with threads than processes. Asynchronous operations are good for IO bound concurrency but not for CPU bound concurrency. Michael Foord -- http://www.voidspace.org.uk/ -- http://mail.python.org/mailman/listinfo/python-list
Re: CPython on the Web
On Jan 4, 1:11 am, John Nagle wrote: > On 1/1/2011 11:26 PM, azakai wrote: > > > Hello, I hope this will be interesting to people here: CPython running > > on the web, > > >http://syntensity.com/static/python.html > > > That isn't a new implementation of Python, but rather CPython 2.7.1, > > compiled from C to JavaScript using Emscripten and LLVM. For more > > details on the conversion process, seehttp://emscripten.org On loading, I "get script stack space quota is exhausted" under firefox 3.5.12, under linux. Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.12) Gecko/20100907 Fedora/3.5.12-1.fc12 Firefox/3.5.12 -- http://mail.python.org/mailman/listinfo/python-list
Re: CPython on the Web
On 01/04/2011 12:38 PM, gry wrote: > On Jan 4, 1:11 am, John Nagle wrote: > >> On 1/1/2011 11:26 PM, azakai wrote: >> >> >>> Hello, I hope this will be interesting to people here: CPython running >>> on the web, >>> >> >>> http://syntensity.com/static/python.html >>> >> >>> That isn't a new implementation of Python, but rather CPython 2.7.1, >>> compiled from C to JavaScript using Emscripten and LLVM. For more >>> details on the conversion process, seehttp://emscripten.org >>> > On loading, I "get script stack space quota is exhausted" under > firefox 3.5.12, under linux. > Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.12) Gecko/20100907 > Fedora/3.5.12-1.fc12 Firefox/3.5.12 > It's a Firefox bug apparently fixed in Firefox 4.x. Some versions of Firefox 3.6.x do work but most do not. Regards, Gerry -- http://mail.python.org/mailman/listinfo/python-list
Need your website?
Need a website for your enterprise or personal profile? Contact us now d212desi...@hotmail.com http://www.d212.com.ar Yours sincerely. -- http://mail.python.org/mailman/listinfo/python-list
Need your website?
Need a website for your enterprise or personal profile? Contact us now d212desi...@hotmail.com http://www.d212.com.ar Yours sincerely. -- http://mail.python.org/mailman/listinfo/python-list
Re: list 2 dict?
Here is something totally the opposite of a nice one liner: A hackish module with a bloated generator. Feel free to comment, so I can learn the errors of my ways. Try not to be too mean though. Try to think of the attached file as a demonstration of ideas instead of good coding practices. Don't be afraid to mention the good points too. I tried to send an email with an attachment (to hide my shame) but I kept getting email rejections. # === # list2dict.py # list item to dict item generator # I forget if generators are thread safe # devpla...@gmail.com # 2011-01 Jan-03 # def check_slice_bounds(list_len, start, stop, step): """Incomplete slice checker.""" # - # force step to be non-None if step is None: step = 1 # - # force step to be non-zero if step == 0: step = 1 # - # in iterating over list to be converted to dict # where list == [key, value, key, value] or in case swap==True # list = [value, key, value, key] # actual stepping is one for key, and plus one more for value step = step * 2 # - # force step to be smaller then size of list or -size of list if step > 0: if step > list_len: step = list_len else: if step < -list_len: step = -list_len # - # force step to be even for key, value iteration if step % 2 == 1: if step > 0: step = step - 1 else: step = step + 1 # - # set start to default; depending on step direction (+x vs -x) if start is None: if step > 0: start = 0 elif step == 0: start = 0 stop = start else: start = -1 # - # set stop to default; depending on step direction (+x vs -x) if stop is None: if step > 0: stop = list_len-1 elif step == 0: stop = start else: stop = -list_len # - # convert "start" to equivelent positive index if start < 0: if start < -list_len: raise IndexError("IndexError: list index out of range:", start) else: start = list_len + 1 + start # - # convert "stop" to equivelent positive index if stop < 0: if stop < -list_len: raise IndexError("IndexError: list index out of range:", stop) else: stop = list_len + 1 + stop return (start, stop, step) def gen(lyst, dyct=None, start=None, stop=None, step=None, swap=False): """ lyst == list to convert to dict dyct == external dict to be updated start == starting index stop step == amount to move index by; usually +1 or -1 (times 2) could be a float if clever enough. if step equals zero it is converted to 1 to prevent an infinite loop. step will be reset to be an index inbounds of a list len() swap 2nd item with the first item in the yield """ # - # Force into bool True or False from equivelent values if swap == True: swap = True else: swap = False # - # check and set lyst slice/index bounds of start, stop, step start, stop, step = check_slice_bounds(len(lyst), start, stop, step) # - index = start # - while 0 <= index < len(lyst): next = index + 1 if next == len(lyst): value = None else: value = lyst[next] key = lyst[index] # - # update external dict if given if dyct is not None: dyct[key] = value # - # effectively sway key with value == index, index+1 to index +1, index if swap: newindex = yield (value,key) else: newindex = yield (key,value) # - # process "newindex" variable if caller does a # gen.send(some_list_index) externally if newindex is None: index = index + (step) elif 0 <= newindex < len(lyst): # fix this to allow for negative index for negative stepping # but don't forget to convert it to its corrosponding # positive index index = newindex else: # fix this so it doesn't error on index 0 #raise IndexError("Index is out of range:", index) pass # - # Ungracefully coerce end of iteration if step > 0: if i
Re: list 2 dict?
The shorter version: This doesn't need any x = iter(list) line. perhaps more useful if you have a bunch of lists to be converted through out your code. def dictit(lyst): i = 0 while i < len(lyst): yield lyst[i], lyst[i+1] i = i + 2 l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b'] {d[0]:d[1] for d in dictit(l)} 3 again a dict comprehension func = lambda l: {k[0]:k[1] for k in dictit(l)} d = func(l) -- http://mail.python.org/mailman/listinfo/python-list
opinion: comp lang docs style
a opinion piece. 〈The Idiocy of Computer Language Docs〉 http://xahlee.org/comp/idiocy_of_comp_lang.html -- The Idiocy of Computer Language Docs Xah Lee, 2011-01-03 Worked with Mathematica for a whole day yesterday, after about 10 years hiatus. Very nice. Mathematica lang and doc, is quite unique. Most other langs drivel with jargons, pettiness, comp-sci pretentiousness, while their content is mathematically garbage. (unixism mumble jumple (perl, unix), or “proper”-engineering OOP fantasy (java), or impractical and ivory-tower adacemician idiocy as in Scheme & Haskell ( currying, tail recursion, closure, call-cc, lisp1 lisp2, and monad monad monad!)) (See: What are OOP's Jargons and Complexities ◇ Language, Purity, Cult, and Deception.) Mathematica, in its doc, is plain and simple. None of the jargon and pretention shit. Very easy to understand. Yet, some of its function's technical aspects are far more scholarly abstruse than any other lang (dealing with advanced math special functions that typically only a few thousand people in the world understand.). -- A Gander into the Idiocies Here's a gander into the doc drivel in common langs. -- unix In unix man pages, it starts with this type of garbage: SYNOPSIS gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ] gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ] zcat [ -fhLV ] [ name ... ] SYNOPSIS zip [-aabcddeeffghjkllmoqrrstuvvwx...@$] [-- longoption ...] [-b path] [-n suf fixes] [-t date] [-tt date] [zipfile [file ...]] [-xi list] Here, the mindset of unix idiots, is that somehow this “synopsis” form is technically precise and superior. They are thinking that it captures the full range of syntax in the most concise way. In practice, it's seldomly read. It's actually not accurate as one'd thought; no program can parse it and agree with the actual behavior. It's filled with errors, incomprehensible to human. Worse of all, the semantic of unix software's options are the worst rape to any possible science in computer science. See: The Nature of the Unix Philosophy ◇ Unix Pipe As Functional Language ◇ Unix zip Utility Path Problem. -- Python In Python, you see this kinda garbage: 7.1. The if statement The if statement is used for conditional execution: if_stmt ::= "if" expression ":" suite ( "elif" expression ":" suite )* ["else" ":" suite] (Source docs.python.org) Here, the mindset of the python idiots is similar to the unix tech geekers. They think that using the BNF notation makes their doc more clear and precise. The fact is, there are so many variations of BNF each trying to fix other's problem. BNF is actually not used as a computer language for syntax description. It's mostly used to communicate syntax to humans. Like regex, there are so many variations. But worse than regex in the sense that there are actually not many actual implementations of BNF. Real word syntax description language are usually nothing close to BNF. See: Pattern Matching vs Lexical Grammar Specification. This incomprehensible BNF notation is the only thing you get if you want to know the basic syntax of “if”, “for”, “while”, “lambda”, or other basic constructs of python. -- Perl In perl, you see this type of drivel: A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines and other control structures allow you to jump around within the code. Perl is a free-form language, you can format and indent it however you like. Whitespace mostly serves to separate tokens, unlike languages like Python where it is an important part of the syntax. Many of Perl's syntactic elements are optional. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as Do What I Mean, abbreviated DWIM. It allows programmers to be lazy and to code in a style with which they are comfortable. Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. Other languages have borrowed syntax from Perl, particularly its regular expression extensions. So if you have programmed in another language you will see familiar pieces in Perl. They often work the same, but see perltrap for information about how they differ. (Source perldoc.perl.org) Notice they introduced you to their lingo “DWIM”. Juvenile humor is a characteristics of perl's docs. It's a whole cult. They have “perl republic”, “state of the onion”, “apocalypse”, “perl monger”, “perl golf”, etc.(See: Larry Wall and Cults.) Another trait is irrelevant rambling. For example, in the above y
Re: Regular Expression for Finding and Deleting comments
On 04/01/2011 17:11, Jeremy wrote: I am trying to write a regular expression that finds and deletes (replaces with nothing) comments in a string/file. Comments are defined by the first non-whitespace character is a 'c' or a dollar sign somewhere in the line. I want to replace these comments with nothing which isn't too hard. The trouble is, the comments are replaced with a new-line; or the new-line isn't captured in the regular expression. Below, I have copied a minimal example. Can someone help? Thanks, Jeremy import re text = """ c C - Second full line comment (first comment had no text) c Third full line comment F44:N 2$ Inline comments start with dollar sign and go to end of line""" commentPattern = re.compile(""" (^\s*?c\s*?.*?| # Comment start with c or C \$.*?)$\n # Comment starting with $ """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) Part of the problem is that you're not using raw string literals or doubling the backslashes. Try soemthing like this: commentPattern = re.compile(r""" (^[ \t]*c.*\n| # Comment start with c or C [ \t]*\$.*) # Comment starting with $ """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) found = commentPattern.finditer(text) print("\n\nCard:\n--\n%s\n--" %text) if found: print("\nI found the following:") for f in found: print(f.groups()) else: print("\nNot Found") print("\n\nComments replaced with ''") replaced = commentPattern.sub('', text) print("--\n%s\n--" %replaced) -- http://mail.python.org/mailman/listinfo/python-list
Re: list 2 dict?
On 04/01/2011 05:33, Paul Rubin wrote: "Octavian Rasnita" writes: If I want to create a dictionary from a list... l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b'] dict(l[i:i+2] for i in xrange(0,len(l),2)) seems simplest to me. Or: dict(zip(l[0 : : 2], l[1 : : 2])) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression for Finding and Deleting comments
On Tuesday, January 4, 2011 11:26:48 AM UTC-7, MRAB wrote: > On 04/01/2011 17:11, Jeremy wrote: > > I am trying to write a regular expression that finds and deletes (replaces > > with nothing) comments in a string/file. Comments are defined by the first > > non-whitespace character is a 'c' or a dollar sign somewhere in the line. > > I want to replace these comments with nothing which isn't too hard. The > > trouble is, the comments are replaced with a new-line; or the new-line > > isn't captured in the regular expression. > > > > Below, I have copied a minimal example. Can someone help? > > > > Thanks, > > Jeremy > > > > > > import re > > > > text = """ c > > C - Second full line comment (first comment had no text) > > c Third full line comment > >F44:N 2$ Inline comments start with dollar sign and go to end of > > line""" > > > > commentPattern = re.compile(""" > > (^\s*?c\s*?.*?| # Comment start with c or C > > \$.*?)$\n # Comment starting with $ > > """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) > > > Part of the problem is that you're not using raw string literals or > doubling the backslashes. > > Try soemthing like this: > > commentPattern = re.compile(r""" > (^[ \t]*c.*\n| # Comment start with c or C > [ \t]*\$.*) # Comment starting with $ > """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) Using a raw string literal fixed the problem for me. Thanks for the suggestion. Why is that so important? Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression for Finding and Deleting comments
On 04/01/2011 19:37, Jeremy wrote: On Tuesday, January 4, 2011 11:26:48 AM UTC-7, MRAB wrote: On 04/01/2011 17:11, Jeremy wrote: I am trying to write a regular expression that finds and deletes (replaces with nothing) comments in a string/file. Comments are defined by the first non-whitespace character is a 'c' or a dollar sign somewhere in the line. I want to replace these comments with nothing which isn't too hard. The trouble is, the comments are replaced with a new-line; or the new-line isn't captured in the regular expression. Below, I have copied a minimal example. Can someone help? Thanks, Jeremy import re text = """ c C - Second full line comment (first comment had no text) c Third full line comment F44:N 2$ Inline comments start with dollar sign and go to end of line""" commentPattern = re.compile(""" (^\s*?c\s*?.*?| # Comment start with c or C \$.*?)$\n # Comment starting with $ """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) Part of the problem is that you're not using raw string literals or doubling the backslashes. Try soemthing like this: commentPattern = re.compile(r""" (^[ \t]*c.*\n| # Comment start with c or C [ \t]*\$.*) # Comment starting with $ """, re.VERBOSE|re.MULTILINE|re.IGNORECASE) Using a raw string literal fixed the problem for me. Thanks for the suggestion. Why is that so important? Regexes often use escape sequences, but so do string literals, and a sequence which is intended for the regex engine might not get passed along correctly. For example, in a normal string literal \b means 'backspace' and will be passed to the regex engine as that; in a regex it usually means 'word boundary': A regex for "the" as a word: \bthe\b As a raw string literal: r"\bthe\b" As a normal string literal: "\\bthe\\b" "\bthe\b" means: backspace + "the" + backspace -- http://mail.python.org/mailman/listinfo/python-list
Error python + cx_Oracle :Oracle-Error-Message: ORA-01036: illegal variable name/number
Hi, i need help with the next error: "ERR_PYTHON:Oracle-Error-Message: ORA-01036: illegal variable name/number", i used the cx_Oracle module, and the error not is only Oracle Error. The error its for that python don't translate the query, with the variables ":VARIABLE" when the VARIABLE is a number, this is th ecause of Oracle error. The template is: updateQUERYBSCS var. The code : == class HilosPrepago(object): def __init__(self,numhilos,listadoSegmentos,archivoLOG,arregloSalida): global NHilos global LSegmnts global ALog global listadoSalida global path_sal global queue global loggingRegister global updateQUERYBSCS queue = Queue() listadoSalida = arregloSalida ALog = archivoLOG LSegmnts = listadoSegmentos NHilos = numhilos loggingRegister = log_register(ALog) updateQUERYBSCS = """UPDATE CONCIL_ICC SET CONTRATO_ICC = :CONTRATO_ICC, CONTRATO_ATS = :CONTRATO_BSCS, PLAN_ICC = :PLAN_ICC, PLAN_ATS = :PLAN_BSCS, IVA_ICC = :IVA_ICC, IVA_ATS = :IVA_BSCS, IVA_MAPEO = :IVA_MAPEO, PROFILE_ICC = :PROFILE_ICC, PROFILE_ATS = :PROFILE_BSCS, LEG_SOG_ICC = :LEG_SOG_ICC, LEG_SOG_ATS = :LEG_SOG_BSCS, LIC_SOG_ICC = :LIC_SOG_ICC, LIC_SOG_ATS = :LIC_SOG_BSCS, LEGLIG_SOG_ICC = :LEGLIC_SOG_ICC, LEGLIG_SOG_ATS = :LEGLIC_SOG_BSCS, LICN_SOG_ICC = :LICN_SOG_ICC, LICN_SOG_ATS = :LICN_SOG_BSCS, LDN_SOG_ICC = :LDN_SOG_ICC, LDN_SOG_ATS = :LDN_SOG_BSCS, REFILL_SOG_ICC = :REFILL_SOG_ICC, REFILL_SOG_ATS = :REFILL_SOG_BSCS, REFILL_PROM_ICC = :REFILL_PROM_ICC, REFILL_PROM_ATS = :REFILL_PROM_BSCS, DIA_RECARGA_ICC = :DIA_RECARGA_ICC, DIA_RECARGA_PROM_ICC = :DIA_RECARGA_PROM_ICC, DIA_RECARGA_ATS = :DIA_RECARGA_BSCS, CEL_IMSI_ICC = :CEL_IMSI_ICC, CEL_IMSI_ATS = :CEL_IMSI_BSCS, STATUS_ICC = :STATUS_ICC, STATUS_ATS = :STATUS_BSCS, ERROR_CONTRATO = to_number(:ERROR_CONTRATO), ERROR_PLAN = to_number(:ERROR_PLAN), ERROR_IVA_BSCS = to_number(:ERROR_IVA_BSCS), ERROR_IVA_ICC = to_number(:ERROR_IVA_ICC), ERROR_PROFILE = to_number(:ERROR_PROFILE), ERROR_LEGSOG = to_number(:ERROR_LEGSOG), ERROR_LICSOG = to_number(:ERROR_LICSOG), ERROR_LEGLICSOG = to_number(:ERROR_LEGLICSOG), ERROR_LICNSOG = to_number(:ERROR_LICNSOG), ERROR_LDNSOG = to_number(:ERROR_LDNSOG), ERROR_REFILLSOG = to_number(:ERROR_REFILLSOG), ERROR_REFILLPROMOCION = to_number(:ERROR_REFILLPROMOCION), ERROR_DIA_RECARGA = to_number(:ERROR_DIA_RECARGA), ERROR_DIA_RECARGAPROM = to_number(:ERROR_DIA_RECARGAPROM), ERROR_IMSI = to_number(:ERROR_IMSI), ERROR_STATUS = to_number(:ERROR_STATUS), ERROR_ENALTA = to_number(:ERROR_ENALTA), ERROR_ENELIMINACION = to_number(:ERROR_ENELIMINACION), PLANACTUALPROMO = :PLANACTUALPROMO, LLEVAPROMOCION = :LLEVAPROMOCION, DUPLICIDAD_DN = to_number(:DUPLICIDAD_DN), VALIDADO_PRODUCCION = :VALIDADO_PRODUCCION, CORREGIDO_EN_ALU = :CORREGIDO_EN_ALU, MENSAJE_CORRECCION = :MENSAJE_CORRECCION WHERE TELEFONO_ATS = :TELEFONO_BSCS """ #threading.Thread.__init__(self) def ejecutaHilo(self,lista,listaRegistrosOUT,archLog,hilo): from OracleConnections import OracleConnections print "Iniciando la ejecucion para el hilo... %s" % hilo listaUnica = lista.get() loggingRegister.registrarLog('Lista de datos...'+str(listaUnica)) FullNameLOG = str(archLog)+'_
Re: Interrput a thread
On Jan 4, 12:31 pm, Fuzzyman wrote: > On Jan 4, 3:31 pm, Roy Smith wrote: > > > > > In article > > <2ebc11a5-1b45-4faa-97b9-c84f0db01...@k22g2000yqh.googlegroups.com>, > > > Fuzzyman wrote: > > > It is unsafe to terminate an os level thread at an arbitrary point > > > because it may be executing code in a critical section. > > > [...] > > > The standard advice is to use a flag and do manual checking to abort > > > threads. This only works for fine grained operations and *doesn't* > > > work for very coarse grained operations or where there aren't > > > convenient places to check the flag. > > > Another possibility is to not use threads! If you > > > 1) Need asynchronous operation > > > 2) Need iterruptability > > > 3) Can't poll for an "please stop" signal > > > You should look at running your "thread" as a separate process, which > > you can send a kill signal to when you want it to go away. You can then > > communicate with it via pipes, sockets, shared memory segments, whatever. > > > Threads are a wonderful invention, but they are not a panacea for all > > possible parallelism tasks. Sometimes they're just the wrong tool. > > However some tasks / algorithms are done much better with threads than > processes. > > Asynchronous operations are good for IO bound concurrency but not for > CPU bound concurrency. > > Asynchronous and threads aren't mutually exclusive. An asynchronous multithreading or multiprocessing library is perfectly well suited for CPU bound concurrency. > > Michael Foord > --http://www.voidspace.org.uk/ -- http://mail.python.org/mailman/listinfo/python-list
Trying to decide between PHP and Python
About once a year, I have to learn yet another programming language. Given all the recommendations (an outstanding accolade from Bruce Eckel, author of "Thinking in Java") I have set my aim to Python. Sounds kinda cool. The indentation-as-block is unique, but that is how I always indent, anyway. Can any of you nice folks post a snippet of how to perform a listing of the current directory and save it in a string? Something like this: $ setenv FILES = `ls` Bonus: Let's say that I want to convert the names of the files to lowercase? As 'tolower()' TIA, -Ramon -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On Tue, Jan 04 2011, Xah Lee wrote: > a opinion piece. > > 〈The Idiocy of Computer Language Docs〉 > http://xahlee.org/comp/idiocy_of_comp_lang.html > > -- > The Idiocy of Computer Language Docs > > Xah Lee, 2011-01-03 > > Worked with Mathematica for a whole day yesterday, after about 10 > years hiatus. Very nice. Mathematica lang and doc, is quite unique. > Most other langs drivel with jargons, pettiness, comp-sci > pretentiousness, while their content is mathematically garbage. > (unixism mumble jumple (perl, unix), or “proper”-engineering OOP > fantasy (java), or impractical and ivory-tower adacemician idiocy as > in Scheme & Haskell ( currying, tail recursion, closure, call-cc, > lisp1 lisp2, and monad monad monad!)) (See: What are OOP's Jargons and > Complexities ◇ Language, Purity, Cult, and Deception.) > > Mathematica, in its doc, is plain and simple. None of the jargon and > pretention shit. Very easy to understand. Yet, some of its function's > technical aspects are far more scholarly abstruse than any other lang > (dealing with advanced math special functions that typically only a > few thousand people in the world understand.). > > -- > A Gander into the Idiocies > > Here's a gander into the doc drivel in common langs. > > -- > unix > > In unix man pages, it starts with this type of garbage: > > SYNOPSIS >gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ] >gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ] >zcat [ -fhLV ] [ name ... ] > > SYNOPSIS >zip [-aabcddeeffghjkllmoqrrstuvvwx...@$] [-- > longoption ...] [-b path] [-n suf >fixes] [-t date] [-tt date] [zipfile [file ...]] [-xi > list] > > Here, the mindset of unix idiots, is that somehow this “synopsis” form > is technically precise and superior. They are thinking that it > captures the full range of syntax in the most concise way. Actually, it *does* capture the full range of syntax in a concise way. If you know of man pages where the Synopsis does not match the syntax then you have found a documentation bug, which should be reported so that it can be fixed. In fact, if anything the real problem with the Synopsis is that it is too concise. Fortunately gzip is a bit of an extreme example. Most man pages look more like this: --8<---cut here---start->8--- NAME tar — The GNU version of the tar archiving utility SYNOPSIS tar [-] A --catenate --concatenate | c --create | d --diff --compare | --delete | r --append | t --list | --test-label | u --update | x --extract --get [options] [pathname ...] --8<---cut here---end--->8--- That synopsis is pretty useful. If you have used tar before and just need a refresher chances are very good that the synopsis will do the trick. If you look at the man pages from the Linux Programmer's Manual the Synopsis makes even more sense. --8<---cut here---start->8--- NAME open, creat - open and possibly create a file or device SYNOPSIS #include #include #include int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); --8<---cut here---end--->8--- Heck, that's basically precisely what I want to know. > In practice, it's seldomly read. It's actually not accurate as one'd > thought; no program can parse it and agree with the actual behavior. > It's filled with errors, incomprehensible to human. I've been using UNIX man pages for quite some time, and I don't think that I have ever come across an error. I am sure that there are errors, but I am also sure that Mathematica's documentation has its share of errors as well. > Worse of all, the semantic of unix software's options are the worst > rape to any possible science in computer science. See: The Nature of > the Unix Philosophy ◇ Unix Pipe As Functional Language ◇ Unix zip > Utility Path Problem. It seems to me that the problem is not UNIX software in general, but rather that the zip function does not have an analogue of tar's -C option (which sets the current directory for the command). > -- > Python > > In Python, you see this kinda garbage: > > 7.1. The if statement > > The if statement is used for conditional execution: > if_stmt ::= "if" expression ":" suite > ( "elif" expression ":" suite )* > ["else" ":" suite] > > (Source docs.python.org) > > Here, the mindset of the python idiots is similar to the unix tech > geekers. They think that using the BNF notation makes their doc more > clear and precise. The fact is, there are so many variations of BNF > each trying to fix other's problem. BNF
Re: opinion: comp lang docs style
On Jan 4, 12:24 pm, Xah Lee wrote: > a opinion piece. > > 〈The Idiocy of Computer Language > Docs〉http://xahlee.org/comp/idiocy_of_comp_lang.html > > -- > The Idiocy of Computer Language Docs > > Xah Lee, 2011-01-03 > > Worked with Mathematica for a whole day yesterday, after about 10 > years hiatus. Very nice. Mathematica lang and doc, is quite unique. > Most other langs drivel with jargons, pettiness, comp-sci > pretentiousness, while their content is mathematically garbage. > (unixism mumble jumple (perl, unix), or “proper”-engineering OOP > fantasy (java), or impractical and ivory-tower adacemician idiocy as > in Scheme & Haskell ( currying, tail recursion, closure, call-cc, > lisp1 lisp2, and monad monad monad!)) (See: What are OOP's Jargons and > Complexities ◇ Language, Purity, Cult, and Deception.) > > Mathematica, in its doc, is plain and simple. None of the jargon and > pretention shit. Very easy to understand. Yet, some of its function's > technical aspects are far more scholarly abstruse than any other lang > (dealing with advanced math special functions that typically only a > few thousand people in the world understand.). > > -- > A Gander into the Idiocies > > Here's a gander into the doc drivel in common langs. > > -- > unix > > In unix man pages, it starts with this type of garbage: > > SYNOPSIS > gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ] > gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ] > zcat [ -fhLV ] [ name ... ] > > SYNOPSIS > zip [-aabcddeeffghjkllmoqrrstuvvwx...@$] [-- > longoption ...] [-b path] [-n suf > fixes] [-t date] [-tt date] [zipfile [file ...]] [-xi > list] > > Here, the mindset of unix idiots, is that somehow this “synopsis” form > is technically precise and superior. They are thinking that it > captures the full range of syntax in the most concise way. In > practice, it's seldomly read. It's actually not accurate as one'd > thought; no program can parse it and agree with the actual behavior. > It's filled with errors, incomprehensible to human. Worse of all, the > semantic of unix software's options are the worst rape to any possible > science in computer science. See: The Nature of the Unix Philosophy ◇ > Unix Pipe As Functional Language ◇ Unix zip Utility Path Problem. > > -- > Python > > In Python, you see this kinda garbage: > > 7.1. The if statement > > The if statement is used for conditional execution: > if_stmt ::= "if" expression ":" suite > ( "elif" expression ":" suite )* > ["else" ":" suite] > > (Source docs.python.org) > > Here, the mindset of the python idiots is similar to the unix tech > geekers. They think that using the BNF notation makes their doc more > clear and precise. The fact is, there are so many variations of BNF > each trying to fix other's problem. BNF is actually not used as a > computer language for syntax description. It's mostly used to > communicate syntax to humans. Like regex, there are so many > variations. But worse than regex in the sense that there are actually > not many actual implementations of BNF. Real word syntax description > language are usually nothing close to BNF. See: Pattern Matching vs > Lexical Grammar Specification. > > This incomprehensible BNF notation is the only thing you get if you > want to know the basic syntax of “if”, “for”, “while”, “lambda”, or > other basic constructs of python. > > -- > Perl > > In perl, you see this type of drivel: > > A Perl program consists of a sequence of declarations and > statements which run from the top to the bottom. Loops, subroutines > and other control structures allow you to jump around within the code. > > Perl is a free-form language, you can format and indent it however > you like. Whitespace mostly serves to separate tokens, unlike > languages like Python where it is an important part of the syntax. > > Many of Perl's syntactic elements are optional. Rather than > requiring you to put parentheses around every function call and > declare every variable, you can often leave such explicit elements off > and Perl will figure out what you meant. This is known as Do What I > Mean, abbreviated DWIM. It allows programmers to be lazy and to code > in a style with which they are comfortable. > > Perl borrows syntax and concepts from many languages: awk, sed, C, > Bourne Shell, Smalltalk, Lisp and even English. Other languages have > borrowed syntax from Perl, particularly its regular expression > extensions. So if you have programmed in another language you will see > familiar pieces in Perl. They often work the same, but see perltrap > for information about how they differ. > > (Source perldoc.perl.org) > > Notice they introduced you to their lingo “DWIM”. Juvenile humor is a
Re: Trying to decide between PHP and Python
On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: > About once a year, I have to learn yet another programming language. > Given all the recommendations (an outstanding accolade from Bruce Eckel, > author of "Thinking in Java") I have set my aim to Python. Sounds kinda > cool. > > The indentation-as-block is unique, but that is how I always indent, > anyway. > > Can any of you nice folks post a snippet of how to perform a listing of > the current directory and save it in a string? > > Something like this: > > $ setenv FILES = `ls` > > Bonus: Let's say that I want to convert the names of the files to > lowercase? As 'tolower()' > > TIA, > > -Ramon 1) import os files = ' '.join(os.listdir('/home/dan')) 2) import os import string files = string.lower(' '.join(os.listdir('/home/dan'))) As to choice between Python and PHP, I would say learn anything but PHP. Even Perl has fewer tentacles than PHP. -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On 1/4/2011 1:24 PM, an Arrogant Ignoramus wrote: what he called a opinion piece. I normally do not respond to trolls, but while expressing his opinions, AI made statements that are factually wrong at least as regards Python and its practitioners. 1. He correctly notes that the Python Language Reference includes snippets of BNF grammar with the intention of making the doc clear and precise. The if statement is used for conditional execution: if_stmt ::= "if" expression ":" suite ( "elif" expression ":" suite )* ["else" ":" suite] He incorrectly claims that the inclusion fails in its purpose. This is based on the irrelevant fact that 'BNF' has many versions (Python only uses one, explained in 1.2. Notation) and the false claim that "BNF is actually not used as a computer language for syntax description.". Actually, the above snippet is a quotation (with initial ':' expanded to '::=' and newlines added) from the file Grammar/Grammar: "if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]" The CPython program Parser/pgen takes Grammar/Grammar as input and produces the parser tables that CPython uses to parse Python code. In other words, CPython uses its well-defined version of extended BNF as a 'computer language for syntax description', contrary to AI's claim. I presume other implementations make either human or machine use of the same file. 2. AI also claims that this notation is 'incomprehensible'. Perhaps to him, but not to me or most the the subset of users who care about it. One way to expand the BNF into English is as follows: An if-statement starts with an if-clause consisting of the word 'if', an expression, a colon, and a suite. 'expression' and a 'suite' have already been defined elsewhere. The if clause can optionally be followed any count (including 0) of elif-clauses which are the same as if-clauses but with 'elif' substituted for 'if'. An if-statement can optionally be terminated with an else-clause consisting of 'else' and a suite. Even if such long-winded paraphrases were added to the doc (and I do not think they should be), in addition to the explanations currently given, the grammar snippet would still be needed to show the exact technical definition that CPython actually uses, for those who wan precisely that. (The people who care include those who want to change the grammar or those who think the behavior might might match the grammar.) 3. AI's complaint is deceptive and deficient in omitting any mention the part of the docs *intended* to teach beginners: the Tutorial. The main doc pages list the Tutorial first, as what one should start with. That is where I started and I cannot remember if I have ever read the formal if-statement grammar before, as I knew how to write such before I ever looked at the Language Reference. Guido and other developers do not and never have expected people to learn about if-statements from the grammar. The tutorial says: " 4.1. if Statements Perhaps the most well-known statement type is the if statement. For example: >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages. " I think this says by example and plain English just what a Python programmer needs to know. It is, of course, followed by many other examples in the remainder of the tutorial. If one wants to critique the 'Python Docs', especially as regards to usefulness to beginners, one must start with the Tutorial; and if one wants to use if statements as an example, one must start with the above. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Troll Alert (do not click)
On Jan 4, 8:19 am, SHILPA wrote: > UNSEEN HOT SEXY PHOTOS > http://karomasti9.blogspot.com/2011/01/never.html > SEXY DIYA MIRZA > http://karomasti9.blogspot.com/2010/12/diya-mirza.html > HOT AISHWARIYA > RAIhttp://karomasti9.blogspot.com/2010/12/aish.html > priyamani hot&sexy > photoshttp://karomasti9.blogspot.com/2010/12/priyamani.html > KATRINA SEXY > PHOTOShttp://karomasti9.blogspot.com/2010/12/katrina.html > ANUSHKA HOT > PHOTOShttp://karomasti9.blogspot.com/2010/12/anuska.html > BEAUTIFUL AISHWARIYA > RAIhttp://karomasti9.blogspot.com/2010/12/aiesh.html > TRISHA HOT > PHOTOShttp://karomasti9.blogspot.com/2010/11/trisha-hot.html > AMISHAPATEL HOT > VIDEOShttp://karomasti9.blogspot.com/search/label/amisha > HANSIKHA HOT SEXY > PHOTOShttp://karomasti9.blogspot.com/search/label/HANSIKA > HOT SEXY COLLEGE > GIRLShttp://karomasti9.blogspot.com/search/label/hot > BEAUTIFUL > LARADATTAhttp://karomasti9.blogspot.com/search/label/laradatta > NIKISHA HOT > BOOBShttp://karomasti9.blogspot.com/search/label/nikisha > PRIYANKA SPICY LATEST > PICShttp://karomasti9.blogspot.com/search/label/priyanka > ONLY FOR YOUTHhttp://karomasti9.blogspot.com/search/label/spicy > SRILEKHA UNSEENED > PHOTOShttp://karomasti9.blogspot.com/search/label/Srilekha > CHOPRA UNBELIVABLE > PHOTOShttp://karomasti9.blogspot.com/search/label/chopra > HOT BIPASA BASU > PHOTOShttp://karomasti9.blogspot.com/search/label/bipasa > TRISHA IN A SEXY > FEELhttp://karomasti9.blogspot.com/search/label/thrisha > SRISHA HOT BOOBS > SHOWhttp://karomasti9.blogspot.com/search/label/srisha > BEAUTIFUL POONAM > PHOTOShttp://karomasti9.blogspot.com/search/label/poonam -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Jan 4, 2:29 pm, Dan M wrote: > On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: > > About once a year, I have to learn yet another programming language. > > Given all the recommendations (an outstanding accolade from Bruce Eckel, > > author of "Thinking in Java") I have set my aim to Python. Sounds kinda > > cool. > > > The indentation-as-block is unique, but that is how I always indent, > > anyway. > > > Can any of you nice folks post a snippet of how to perform a listing of > > the current directory and save it in a string? > > > Something like this: > > > $ setenv FILES = `ls` > > > Bonus: Let's say that I want to convert the names of the files to > > lowercase? As 'tolower()' > > > TIA, > > > -Ramon > > 1) > import os > files = ' '.join(os.listdir('/home/dan')) > > 2) > import os > import string > files = string.lower(' '.join(os.listdir('/home/dan'))) > > As to choice between Python and PHP, I would say learn anything but PHP. > Even Perl has fewer tentacles than PHP. Not to mention that it took me 9 minutes to get a reply from you... Quite speedy community support. That is a very important parameter in my technology decisions these days. Thanks! -Ramon -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 04 Jan 2011 12:32:28 -0800, Google Poster wrote: > Not to mention that it took me 9 minutes to get a reply from you... > Quite speedy community support. > > That is a very important parameter in my technology decisions these > days. > > Thanks! > > -Ramon This Usenet group is a truly awesome resource. I'm a Python newbie myself, and the times I've posted here looking for direction I have been very pleased with the results. Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: String building using join
gervaz writes: > Hi all, I would like to ask you how I can use the more efficient join > operation in a code like this: > class Test: > ... def __init__(self, v1, v2): > ... self.v1 = v1 > ... self.v2 = v2 > ... def prg(l): > ... txt = "" > ... for x in l: > ... if x.v1 is not None: > ... txt += x.v1 + "\n" > ... if x.v2 is not None: > ... txt += x.v2 + "\n" > ... return txt > ... You can change the prg() function above slightly to make it a generator function: def genprg(l): for x in l: if x.v1 is not None: yield x.v1 if x.v2 is not None: yield x.v2 Then you can rewrite prg using join: def prg(l): return '\n'.join(genprg(l)) This way you save yourself from creating a list. I know this is not the one liner that others have suggested but it shows a general way of transforming a piece of code in order to make use of generator functions. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Jan 4, 2:34 pm, Dan M wrote: > On Tue, 04 Jan 2011 12:32:28 -0800, Google Poster wrote: > > Not to mention that it took me 9 minutes to get a reply from you... > > Quite speedy community support. > > > That is a very important parameter in my technology decisions these > > days. > > > Thanks! > > > -Ramon > > This Usenet group is a truly awesome resource. My kinda place. :-) Now, I will embark on my learning journey the proper way: reading some Internet tutorials, instead of cheating like I just did. -Ramon -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, Jan 4, 2011 at 3:20 PM, Google Poster wrote: > > About once a year, I have to learn yet another programming language. > Given all the recommendations (an outstanding accolade from Bruce > Eckel, author of "Thinking in Java") I have set my aim to Python. > Sounds kinda cool. > > The indentation-as-block is unique, but that is how I always indent, > anyway. > > Can any of you nice folks post a snippet of how to perform a listing > of the current directory and save it in a string? > > Something like this: > > $ setenv FILES = `ls` > import os FILES = os.listdir('.') will give you a list of all the files in the current directory. If you wanted that as a single string, just join all of the file names with whatever you want as a separator. files_str = '\n'.join(FILES) It's a bit different than what your original command does- it doesn't use the external "ls" command, it just gives you the list of files already parsed. > Bonus: Let's say that I want to convert the names of the files to > lowercase? As 'tolower()' > Strings in Python have a lower() method. files_str = files_str.lower() > TIA, > > -Ramon > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
JSONBOT 0.6 RELEASED
Hello world and the best wishes for 2011 for all of you ! i'm pleased to announce version 0.6 of JSONBOT, a release that saw it's complete codebase refactored. Things have moved into their own package, making it easier to distribute JSONBOT to the various OS around. I even renamed the name of the distribution to "jsb", so use the jsb-0.6.tar.gz or "easy_install jsb" to get this version of JSONBOT. So once again i need to ask existing users to upgrade their JSONBOT install, see http://jsonbot.appspot.com/docs/html/handbook/UPGRADE.html for instructions on how to do that. Functionality of the bot is the same as 0.5. For more information on JSONBOT, see http://jsonbot.googlecode.com or join us on #dunkbots Freenode. Bot documentation and demo is on http://jsonbot.appspot.com I hope you enjoy this release of JSONBOT, i'm glad i can start working on 0.7 ;] About JSONBOT: JSONBOT is a remote event-driven framework for building bots that talk JSON to each other over XMPP. This distribution provides bots built on this framework for console, IRC, XMPP for the shell and WWW and XMPP for the Google Application engine. JSONBOT is all of the following: * a shell console bot * a shell IRC bot * a shell XMPP bot * a Web bot running on Google Application Engine * a XMPP bot running on Google Application Engine * a Google Wave bot running op Google Application Engine * the XMPP bots are used to communicate between bots * plugin infrastructure to write your own functionality * event driven framework by the use of callbacks Bart -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, Jan 4, 2011 at 12:29 PM, Dan M wrote: > On Tue, 04 Jan 2011 12:20:42 -0800, Google Poster wrote: > >> About once a year, I have to learn yet another programming language. >> Given all the recommendations (an outstanding accolade from Bruce Eckel, >> author of "Thinking in Java") I have set my aim to Python. Sounds kinda >> cool. >> >> The indentation-as-block is unique, but that is how I always indent, >> anyway. >> >> Can any of you nice folks post a snippet of how to perform a listing of >> the current directory and save it in a string? >> >> Something like this: >> >> $ setenv FILES = `ls` >> >> Bonus: Let's say that I want to convert the names of the files to >> lowercase? As 'tolower()' > import os > import string > files = string.lower(' '.join(os.listdir('/home/dan'))) Most of the string module has been deprecated for quite a while now; use string methods instead: files = ' '.join(os.listdir('/home/dan')).lower() Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
I confess that I haven't used php so someone correct me if I'm wrong. Looking at the history of the two languages, it is my impression that php originated as a language for web/CGI development which eventually added features enabling it to be used (sparingly) as a general purpose language. Python on the other hand is a general purpose language that has added features, in the form of library modules, that enable it to be used as a web/CGI development. Given these histories, one might ask, do you want to learn a new language for general purposes including web development, or do you want to learn a new language that is specifically focused on web/CGI? If the later, php will be an excellent choice, if the former, Python. If you only want to learn one language, or at least only want to learn one at this time, Python seems like a more useful choice - but only if you work (or also work) on some applications other than web/CGI. Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Jan 4, 8:20 pm, Google Poster wrote: > Can any of you nice folks post a snippet of how to perform a listing > of the current directory and save it in a string? > > Something like this: > > $ setenv FILES = `ls` > > Bonus: Let's say that I want to convert the names of the files to > lowercase? As 'tolower()' I'd just like to mention one more python nicety: list comprehension. If you wanted the filenames as a list of strings, with each made lowercase then the following would serve well: import os filenames = os.listdir('.') filenames_lower = [fn.lower() for fn in filenames] You could also combine this into one line: import os filenames_lower = [fn.lower() for fn in os.listdir('.')] Regards, Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Error python + cx_Oracle :Oracle-Error-Message: ORA-01036: illegal variable name/number
On Tue, Jan 4, 2011 at 12:57 PM, Mauricio Martinez Garcia wrote: > > Hi, i need help with the next error: > > "ERR_PYTHON:Oracle-Error-Message: ORA-01036: illegal variable name/number", > i used the cx_Oracle module, and the error not is only Oracle Error. > > The error its for that python don't translate the query, with the variables > ":VARIABLE" when the VARIABLE is a number, this is th ecause of Oracle > error. You can only specify bind parameters that are used in the query. The dict you are passing in has 56 key/value pairs, but your query has only 55 variables. "TELEFONO_ICC" does not appear to be used anywhere in the query. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
> As to choice between Python and PHP, I would say learn anything but PHP. > Even Perl has fewer tentacles than PHP. type this in a form field 2.2250738585072011e-308 http://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/ cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
Google Poster writes: > On Jan 4, 2:34 pm, Dan M wrote: > > This Usenet group is a truly awesome resource. > > My kinda place. :-) Can I ask, since you'll be joining us here, that you use your name (“Ramon” according to your signature, but preferably a full name) in your “From” field to identify your messages better? -- \ “I am too firm in my consciousness of the marvelous to be ever | `\ fascinated by the mere supernatural …” —Joseph Conrad, _The | _o__) Shadow-Line_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 4 Jan 2011, Dan M wrote: > As to choice between Python and PHP, I would say learn anything but PHP. > Even Perl has fewer tentacles than PHP. However, the quality of code depends heavily on who writes it. My impression is that more folks of "I did it and it works so it is good, right?" attitude can be found among Perl/PHP crowd (compared to Python or Ruby or...). The reason is probably the "easyness" of those languages (mostly because of tons of readymade code on the net) which - wrongly - suggests they are already "there", no need to learn anymore. But I find, from time to time, nice code written in, say, PHP and from this I know it is possible to use it without screwing up. I guess it requires just some learning, some books (leaning towards theory rather than teaching dummies whatever in 2 and 1/10 days) and about five years (or maybe ten, or maybe only two) - after that, you can learn PHP and Perl if you really want to :-). I guess stackoverflow can give some pointers about it. Myself, I see neither of the two as promising for me, so I deflect them. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Jan 4, 3:09 pm, Alex Willmer wrote: > On Jan 4, 8:20 pm, Google Poster wrote: > > > Can any of you nice folks post a snippet of how to perform a listing > > of the current directory and save it in a string? > > > Something like this: > > > $ setenv FILES = `ls` > > > Bonus: Let's say that I want to convert the names of the files to > > lowercase? As 'tolower()' > > I'd just like to mention one more python nicety: list comprehension. > If you wanted the filenames as a list of strings, with each made > lowercase then the following would serve well: > > import os > filenames = os.listdir('.') > filenames_lower = [fn.lower() for fn in filenames] > > You could also combine this into one line: > > import os > filenames_lower = [fn.lower() for fn in os.listdir('.')] > > Regards, Alex The syntax reminds me of Lots of Interspersed Silly Parentheses (L.I.S.P.), but without the parentheses. :-) -Ramon -- http://mail.python.org/mailman/listinfo/python-list
Re: Troll Alert (do not click)
On Tue, 04 Jan 2011 12:30:21 -0800, Google Poster wrote: [snip spam] Good lord, why the hell are you RE-POSTING spam??? Did you actually think it was HELPFUL to defeat everyone's anti-spam filters? Most people won't see the original spam, and then you "helpfully" resend it. Thanks a lot, if not for you we might not have seen it at all -- and if we did, we almost certainly wouldn't have clicked on it without the misleading subject line. I thought you were complaining about Xah Lee, which is always fun to read, not re-posting Indian porno spam. If I didn't know better, I'd seriously wonder whether you are, in fact, the spammer, just pretending to be replying to some other spammer. A false name (do your friends call you "Google Poster"?), a misleading subject line (it's not a troll post, it's spam), a trick to defeat filters and win the off-topic URLs many more links. Hmmm. Please don't try to "help" in this way again. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 04 Jan 2011 13:09:13 -0800, Alex Willmer wrote: > You could also combine this into one line: > > import os > filenames_lower = [fn.lower() for fn in os.listdir('.')] That's two lines :) Here are a couple of nicely obfuscated one-liners: [name.lower() for name in __import__('os').listdir('.')] map(str.lower, __import__('os').listdir('.')) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On 1/4/2011 4:22 PM, Google Poster wrote: The syntax reminds me of Lots of Interspersed Silly Parentheses (L.I.S.P.), but without the parentheses. I haven't heard that version before. The one I heard was: "Lots of Irritating Single Parentheses". Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On Tue, 04 Jan 2011 13:22:33 +0100, Zdenko wrote: > I wrote these two codes for example: > > this one is naive way of matrix multiplication using one thread [...] > this one is using two threads, each one is multiplying half of matrix [...] > why is second one more than twice slower than first when it should be > faster. I suspect that problem is in simultaneous access to matrix C but > i don't know how to solve this. Can I suggest that your timing code leaves something to be desired? * You time too much. You're interested in how long it takes to multiply two matrices, but you time how long it takes to do much more than just the multiplication: your timing code covers the time it takes to create the class object (which will be trivial), and build the matrix (non- trivial), as well as perform the multiplication. * Your perform the timing test once, which makes it subject to sampling errors. (Although if the process takes a long time, say, multiple seconds, the sampling error will *probably* be small relative to the measured time. But not always.) * You use time.clock, but without knowing which operating system you are running, it's impossible to tell whether you should be using time.time instead. Whether these issues will actually make a practical difference in this *specific* case, I don't know, but as a general rule, the most accurate way to perform these sorts of timing tests is with the timeit module. Something like this: A = ... # initialise matrix A B = ... # and B C = ... # and the result def mult1(A, B, C): # Multiply matrices A and B using 1 thread. t = MyThread() t.start() t.join() def mult2(A, B, C): # Multiply matrices A and B using 2 threads. t1 = MyThread() t2 = MyThread() t1.start() t2.start() t1.join() # Block until thread 1 is done. t2.join() # Now block until thread 2 is done. setup1 = "from __main__ import A, B, C, mult1" setup2 = "from __main__ import A, B, C, mult2" from timeit import Timer t1 = Timer("mult1(A, B, C)", setup1) t2 = Timer("mult2(A, B, C)", setup2) # Now perform the timing tests. best1 = min(t1.repeat()) best2 = min(t2.repeat()) By default, Timer.repeat will measure the time taken by one million iterations of the code snippet, and take three measurements. You almost always only care about the smallest measurement -- any larger times will represent sampling error. If it takes too long to time one million iterations, either make the matrices smaller, or pass keyword arguments number and/or repeat to the repeat method: # best of five measurements of one hundred iterations best1 = min(t1.repeat(number=100, repeat=5)) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On 01/04/2011 01:34 PM, Terry Reedy wrote: > On 1/4/2011 1:24 PM, an Arrogant Ignoramus wrote: > > what he called >> a opinion piece. > > I normally do not respond to trolls, but while expressing his opinions, > AI made statements that are factually wrong at least as regards Python > and its practitioners. Given that most trolls include factually false statements, the above is inconsistent. And speaking of arrogant, it is just that to go around screaming "troll" about a posting relevant to the newsgroup it was posted in because you don't happen to agree with its content. In doing so you lower your own credibility. (Which is also not helped by your "Arrogant Ignoramus" name-calling.) > [...] > 2. AI also claims that this notation is 'incomprehensible'. Since incomprehensibility is clearly subjective your claim that it is a factual error is every bit as hyperbolic as his. > [...] > 3. AI's complaint is deceptive and deficient in omitting any mention the > part of the docs *intended* to teach beginners: the Tutorial. The main > doc pages list the Tutorial first, as what one should start with. That > [...] > If one wants to critique the 'Python Docs', especially as regards to > usefulness to beginners, one must start with the Tutorial; and if one > wants to use if statements as an example, one must start with the above. No. The language reference (LR) and standard library reference (SLR) must stand on their own merits. It is nice to have a good tutorial for those who like that style of learning. But it should be possible for a programmer with a basic understanding of computers and some other programming languages to understand how to program in python without referring to tutorials, explanatory websites, commercially published books, the source code, etc. The difficulty of doing that is a measure of the failure of the python docs to achive a level quality commensurate with the language itself. FWIW, I think the BNF in the LR is perfectly reasonable given the target audience I gave above. The failure of the LR has more to do with missing or excessively terse material -- it concentrates too exclusively on syntax and insufficiently on semantics. Much of the relevant semantics information is currently mislocated in the SLR. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
In article <4d23a29d.7030...@yahoo.com>, Alan Meyer wrote: > On 1/4/2011 4:22 PM, Google Poster wrote: > > > The syntax reminds me of Lots of Interspersed Silly Parentheses > > (L.I.S.P.), but without the parentheses. > > I haven't heard that version before. The one I heard was: > > "Lots of Irritating Single Parentheses". > > Alan Long Involved Stupid Parentheses. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Tue, 4 Jan 2011, Roy Smith wrote: > In article <4d23a29d.7030...@yahoo.com>, Alan Meyer > wrote: > > > On 1/4/2011 4:22 PM, Google Poster wrote: > > > > > The syntax reminds me of Lots of Interspersed Silly Parentheses > > > (L.I.S.P.), but without the parentheses. > > > > I haven't heard that version before. The one I heard was: > > > > "Lots of Irritating Single Parentheses". > > > > Alan > > Long Involved Stupid Parentheses. Heh. One day, guys, when you have nothing better to do, try writing a parser for Lisp-like language (Common Lisp, Scheme, whatever). After that, do the same with some other language of your preference (Python, Java, whatever). Compare time and code spent... Regards :-) Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On Jan 4, 10:12 am, Fuzzyman wrote: > > This is a case that .NET (C#) handles better than Python or Java. > Nope, read the documentation for Thread.Abort() carefully. Thread.Abort() can cause termination inside a static constructor, which is very bad. You sure your application can cope with that? Mine can't. Thread.Abort() is only safe for self-abortion, app domain termination and a few other very narrow and obscure scenarios. It is not a safe way to end arbitrary threads doing arbitrary processing. > It's another place where people > sometimes have a genuine need/use case yet people will insist on > telling them they don't *really* want it... > Because there's no safe way to do it. It's fundamentally a racy operation, with the typical horrible consequences when you lose. Removing the race requires support from the application, i.e., you have to write the code yourself. Frequently, it's simply not possible to remove the race. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
In article , Tomasz Rola wrote: > Heh. One day, guys, when you have nothing better to do, try writing a > parser for Lisp-like language (Common Lisp, Scheme, whatever). After that, > do the same with some other language of your preference (Python, Java, > whatever). Compare time and code spent... There is no doubt that lisp is easy to parse. Even I can increment a counter every time I see '(' and decrement it every time I see ')'. But, computers are there to make life easy on people, not the other way around. There. Now that I've tossed some gasoline on the language wars fire, I'll duck and run in the other direction :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
Tomasz Rola writes: > Heh. One day, guys, when you have nothing better to do, try writing a > parser for Lisp-like language (Common Lisp, Scheme, whatever). After > that, do the same with some other language of your preference (Python, > Java, whatever). Compare time and code spent... Perhaps Lisp is a simpler language to parse than Python. Perhaps a machine with only one instruction http://en.wikipedia.org/wiki/One_instruction_set_computer> is simpler to implement than one with a broader instruction set. So what? -- \ “Shepherds … look after their sheep so they can, first, fleece | `\ them and second, turn them into meat. That's much more like the | _o__) priesthood as I know it.” —Christopher Hitchens, 2008-10-29 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
On Wed, 5 Jan 2011, Ben Finney wrote: > > Tomasz Rola writes: > > Heh. One day, guys, when you have nothing better to do, try writing a > > parser for Lisp-like language (Common Lisp, Scheme, whatever). After > > that, do the same with some other language of your preference (Python, > > Java, whatever). Compare time and code spent... > Perhaps Lisp is a simpler language to parse than Python. > Perhaps a machine with only one instruction > http://en.wikipedia.org/wiki/One_instruction_set_computer> is > simpler to implement than one with a broader instruction set. > So what? So... nothing at all. My intention was to point out that parentheses (or rather, simple syntax that is enabled when using them) can give a boost in some situations. BTW, my own experience tells me, they are not really as bad as some folk tales imply. Of course, there is also esthetic reason - some people don't like parentheses, period. I am ok with this. Me, OTOH, I have esthetic incompatibility with Perl and to some extent with PHP. No problem for me :-). Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_r...@bigfoot.com ** -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
On 1/4/2011 2:15 AM, Ulrich Eckhardt wrote: Zdenko wrote: Please, can anybody write me a simple recursive matrix multiplication using multiple threads in Python, or at least show me some guidelines how to write it myself No problem, I just need your bank account data to withdraw the payment and the address of your teacher whom to send the results. ;^) Seriously, things don't work like this. If you show effort, you will get help, but you don't get working solutions without even a bit of effort on your own. Start with a recursive algorithm, then make it multithreaded. Be prepared to make some experiments on how to distribute tasks to threads and collect them again. If you want to do matrix multiplication from Python, use NumPy. Anything you write in Python itself and run in CPython will be far, far slower. CPython without NumPy is about 60x slower than C on basic array math. Writing high-speed parallel number-crunching code that outperforms off the shelf libraries is typically non-trivial. If there's some easy way to make a simple operation like matrix multiply go faster, it's probably been done already. If you're really into this, look into the Unified Parallel C effort and its libraries. The supercomputer types spend their lives doing this sort of thing. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Interrput a thread
On 1/4/2011 6:11 PM, Adam Skutt wrote: On Jan 4, 10:12 am, Fuzzyman wrote: This is a case that .NET (C#) handles better than Python or Java. Nope, read the documentation for Thread.Abort() carefully. Thread.Abort() can cause termination inside a static constructor, which is very bad. You sure your application can cope with that? Mine can't. Thread.Abort() is only safe for self-abortion, app domain termination and a few other very narrow and obscure scenarios. It is not a safe way to end arbitrary threads doing arbitrary processing. It's another place where people sometimes have a genuine need/use case yet people will insist on telling them they don't *really* want it... Because there's no safe way to do it. It's fundamentally a racy operation, with the typical horrible consequences when you lose. Removing the race requires support from the application, i.e., you have to write the code yourself. Frequently, it's simply not possible to remove the race. There are systems where there's support designed in for thread abort. LISP/Scheme systems tend to support it. QNX, the real-time OS, has well worked out thread-abort semantics at the C level. (QNX has really good features for "not getting stuck", like the ability to put a time limit on any system call.) But Python doesn't support things like that. What you'd really like in Python is the ability for one thread to be able to force an exception in another thread, plus a mechanism for locking out such exceptions for critical sections. It's not worth having, though, in a system where you can really only run one thread at a time. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
In article , Google Poster wrote: > >The syntax reminds me of Lots of Interspersed Silly Parentheses >(L.I.S.P.), but without the parentheses. You're not the first person to make that observation: http://norvig.com/python-lisp.html See also: http://norvig.com/python-iaq.html -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "Think of it as evolution in action." --Tony Rand -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
In article , Roy Smith wrote: >In article <4d23a29d.7030...@yahoo.com>, Alan Meyer >wrote: >> On 1/4/2011 4:22 PM, Google Poster wrote: >>> >>> The syntax reminds me of Lots of Interspersed Silly Parentheses >>> (L.I.S.P.), but without the parentheses. >> >> I haven't heard that version before. The one I heard was: >> "Lots of Irritating Single Parentheses". > >Long Involved Stupid Parentheses. http://www.netfunny.com/rhf/jokes/90q2/lispcode.html -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ "Think of it as evolution in action." --Tony Rand -- http://mail.python.org/mailman/listinfo/python-list
Which coding style is better? public API or private method inside class definition
For example: I'm writing simple class: class Numbers: def __init__(self, numbers): self._numbers = numbers def get_all(self): for number in self._numbers: yield number If I want to add another method for yielding even numbers only, I may use: def get_even(self): for numbers in self._numbers: if numbers % 2 == 0: yield number or, I can use public method 'get_all' instead of using private attribute '_numbers', like: def get_even(self): for numbers in self.get_all(): if numbers % 2 == 0: yield number Which coding style do you prefer? I'm more toward public API way, since it requires less code change if I refactor private data structure later. Plz give pros and cons of these. -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
I found typo after posting: local name 'numbers' and 'number' are mixed. Plz don't report bug but focus on coding style only :-) -- http://mail.python.org/mailman/listinfo/python-list
Just Starting in on programming
I was told this was good and some of the easier way to start programming. I'm just wondering if this statement is true and if so what is it I should do to really start getting in there and go ahead and start using some other languages. Thank you those who reply and help in advance Tyler Ryan Carroll -- http://mail.python.org/mailman/listinfo/python-list
Re: Which coding style is better? public API or private method inside class definition
I think it depends on where you're willing to deal with changes. As it stands, if you make changes to get_all that will effect the way get_even works. If there's a logical chain that your code needs to follow and such changes would be acceptable, use them, because it's easier to change one thing once instead of one thing twice. In general, I try to code in a way that will reduce the number of places I'll have to change or refactor. Josh -- http://mail.python.org/mailman/listinfo/python-list
Problem inserting an element where I want it using lxml
I'm having some trouble inserting elements where I want them using the lxml ElementTree (Python 2.6). I presume I'm making some wrong assumptions about how lxml works and I'm hoping someone can clue me in. I want to process an xml document as follows: For every occurrence of a particular element, no matter where it appears in the tree, I want to add a sibling to that element with the same name and a different value. Here's the smallest artificial example I've found so far demonstrates the problem: Add another bingo after this What I'd like to produce is this: Add another bingo after this Here's my program: cut here - from lxml import etree as etree xml = """ Add another bingo after this """ tree = etree.fromstring(xml) # A list of all "bingo" element objects in the unmodified original xml # There's only one in this example elems = tree.xpath("//bingo") # For each one, insert a sibling after it bingoCounter = 0 for elem in elems: parent = elem.getparent() subIter = parent.iter() pos = 0 for subElem in subIter: # Is it one we want to create a sibling for? if subElem == elem: newElem = etree.Element("bingo") bingoCounter += 1 newElem.text = "New bingo %d" % bingoCounter newElem.tail = "\n" parent.insert(pos, newElem) break pos += 1 newXml = etree.tostring(tree) print("") print(newXml) cut here - The output follows: output - Add another bingo after this New bingo 1 output - Setting aside the whitespace issues, the bug in the program shows up in the positioning of the insertion. I wanted and expected it to appear immediately after the original "bingo" element, and before the "bar" element, but it appeared after the "bar" instead of before it. Everything works if I take the "something" element out of the original input document. The new "bingo" appears before the "bar". But when I put it back in, the inserted bingo is out of order. Why should that be? What am I misunderstanding? Is there a more intelligent way to do what I'm trying to do? Thanks. Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Just Starting in on programming
On 01/05/2011 12:22 AM, Thai wrote: > I was told this was good and some of the easier way to start >programming. I'm just wondering if this statement is true and if >so what is it I should do to really start getting in there and go >ahead and start using some other languages. > >Thank you those who reply and help in advance > Tyler Ryan Carrollhttp://docs.python.org/tutorial/ You were told what was good? Get started in where? If you're just learning to program, I found http://www.alan-g.me.uk/ was a very good resource, and I learned a lot. #python recommends http://www.greenteapress.com/thinkpython/html/index.html in the topic, and the Python tutorial at http://docs.python.org/tutorial/ is quality, you may learn quite a bit from it. If you have questions, I suggest you look into the tutor mailing list, tu...@python.org ~Corey Richardson -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem inserting an element where I want it using lxml
Here's a trimmed down version of how I did this (using ElementTree standalone, but the API should be the same) This is from a class definition and the _elem attribute is a link to an ElementTree.Element object. ... def _add_elem(self, tagName, text, attrib ={}): """_add_elem(tagName, text, attrib={}) Adds a child element in the appropriate place in the tree. Raises an IndexError if the checker does not allow an addition child of tagName. """ last_child = None for child in self._elem.findall('.//%s' % tagName): last_child = child if last_child is None: new_child = ET.SubElement(self._elem, tagName, attrib) else: new_child = ET.Element(tagName, attrib) self._elem.insert(self._elem._children.index(last_child)+1, new_child) new_child.text=str(text) return new_child I don't think you need to count the instances of the bingo node (unless you want to prevent too many from being added in). Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem inserting an element where I want it using lxml
Oh, and I usually use a separate function to indent my xml for readability when I need to actually look at the xml. It's easier than trying to change the element in situ and make it look nice. Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On Tue, 04 Jan 2011 15:17:37 -0800, ru...@yahoo.com wrote: >> If one wants to critique the 'Python Docs', especially as regards to >> usefulness to beginners, one must start with the Tutorial; and if one >> wants to use if statements as an example, one must start with the >> above. > > No. The language reference (LR) and standard library reference (SLR) > must stand on their own merits. It is nice to have a good tutorial for > those who like that style of learning. But it should be possible for a > programmer with a basic understanding of computers and some other > programming languages to understand how to program in python without > referring to tutorials, explanatory websites, commercially published > books, the source code, etc. No it shouldn't. That's what the tutorial is for. The language reference and standard library reference are there to be reference manuals, not to teach beginners Python. In any case, your assumption that any one documentation work should stand on its own merits is nonsense -- *nothing* stands alone. Everything builds on something else. Technical documentation is no different: it *must* assume some level of knowledge of its readers -- should it be aimed at Python experts, or average Python coders, or beginners, or beginners to programming, or at the very least is it allowed to assume that the reader already knows how to read? You can't satisfy all of these groups with one document, because their needs are different and in conflict. This is why you have different documentation -- tutorials and reference manuals and literate source code and help text are all aimed at different audiences. Expecting one document to be useful for all readers' needs is like expecting one data type to be useful for all programming tasks. Reasonable people might disagree on what a particular documentation work should target, and the best way to target it, but not on the need for different documentation for different targets. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: opinion: comp lang docs style
On 2011-01-04 22:29:31 -0800, Steven D'Aprano said: In any case, your assumption that any one documentation work should stand on its own merits is nonsense -- *nothing* stands alone. +1 How many RFCs still in use today don't start with: The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 I posted a response on the article itself, rather than pollute a mailing list with replies to a troll. The name calling was a rather large hint as to the intention of the "opinion", either that or whoever translated the article (man or machine) was really angry at the time. ;) - Alice. -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix multiplication
Zdenko wrote: > >Please, can anybody write me a simple recursive matrix multiplication >using multiple threads in Python, or at least show me some guidelines >how to write it myself Matrix multiplication is not generally done recursively. There's no conceptual gain. It makes more sense iteratively. -- Tim Roberts, t...@probo.com Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem inserting an element where I want it using lxml
Alan Meyer, 05.01.2011 06:57: I'm having some trouble inserting elements where I want them using the lxml ElementTree (Python 2.6). I presume I'm making some wrong assumptions about how lxml works and I'm hoping someone can clue me in. I want to process an xml document as follows: For every occurrence of a particular element, no matter where it appears in the tree, I want to add a sibling to that element with the same name and a different value. Here's the smallest artificial example I've found so far demonstrates the problem: Add another bingo after this What I'd like to produce is this: Add another bingo after this Looks trivial to me. ;) Here's my program: cut here - from lxml import etree as etree xml = """ Add another bingo after this """ tree = etree.fromstring(xml) # A list of all "bingo" element objects in the unmodified original xml # There's only one in this example elems = tree.xpath("//bingo") # For each one, insert a sibling after it bingoCounter = 0 for elem in elems: parent = elem.getparent() subIter = parent.iter() ".iter()" gives you a recursive iterator that will also yield the "something" Element in your case, thus the incorrect counting. You only want the children, so you should iterate over the Element itself. pos = 0 for subElem in subIter: # Is it one we want to create a sibling for? if subElem == elem: There is an .index() method on Elements that does what you want to achieve here. However, the right way to do it is to use ".addnext()". http://codespeak.net/lxml/api/lxml.etree._Element-class.html Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to decide between PHP and Python
From: "Tomasz Rola" On Tue, 4 Jan 2011, Dan M wrote: As to choice between Python and PHP, I would say learn anything but PHP. Even Perl has fewer tentacles than PHP. However, the quality of code depends heavily on who writes it. My impression is that more folks of "I did it and it works so it is good, right?" attitude can be found among Perl/PHP crowd (compared to Python or Ruby or...). The reason is probably the "easyness" of those languages (mostly because of tons of readymade code on the net) which - wrongly - suggests they are already "there", no need to learn anymore. Yes you are right. Perl is much flexible than all other languages and there was written a lot of bad code in the past that can now be found on the net, beeing very hard for a newbie to find only the good examples and tutorials. But Perl offers many helpful modules for testing the apps so for good programmers there is not true the idea of "it works so it's ok". Usually we compare the languages although we always think to all aditional modules and libraries we can use with them for creating apps. Thinking this way, Perl is better than Python for creating web apps, because Catalyst framework is more advanced than the frameworks for Python and it is more flexible even than Ruby on Rails, DBIx::Class ORM is a very advanced ORM and a very clean one and Perl web apps can use strong templating systems and form processors, unicode is a native code for Perl for a long time and so on. So how good is the language depends on what you need to use it for. (But I hope that this won't start a language war, because I have just done the same on a Perl mailing list telling about some Perl disadvantages towards Python :) Octavian -- http://mail.python.org/mailman/listinfo/python-list