online money
online money online business money is very important http://worldlangs.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: File-writing not working in Windows?
On Jun 6, 10:18 pm, [EMAIL PROTECTED] wrote: > All, > > I have the following code: > for fileTarget in dircache.listdir("directory"): > (dirName, fileName) = os.path.split(fileTarget) > f = open(fileTarget).readlines() > copying = False > for i in range(len(f)): > for x in range (0,24,1): > if (re.search(self.Info[x][3], f[i])): > #If we have a match for our start of section... > if (self.Info[x][2] == True): > #And it's a section we care about... > copying = > True #Let's start copying the lines out > to the temporary file... > if (os.name == "posix"): > if (self.checkbox25.GetValue() == > False): > tempfileName = "tempdir/" + > self.Info[x][0] + "_tmp_" + fileName + ".txt" > else: > tempfileName = > self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt" > else: > if (self.checkbox25.GetValue() == > False): > tempfileName = "tempdir\\" + > self.Info[x][0] + "_tmp_" + fileName + ".txt" > else: > tempfileName = > self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt" > else: > copying = False > if (re.search(self.Info[x][4], f[i])): > #Now we've matched the end of our section... > copying = > False #So let's stop copying out to > the temporary file... > if (copying == True): > g = open(tempfileName, > 'a') #Open that file in append mode... > > g.write(f[i]) #Write the line... > g.close() > > This code works PERFECTLY in Linux. Where I have a match in the file > I'm processing, it gets cut out from the start of the match until the > end of the match, and written to the temporary file in tempdir. > > It does not work in Windows. It does not create or write to the > temporary file AT ALL. It creates the tempdir directory with no > problem. > > Here's the kicker: it works perfectly in Windows if Windows is running > in VMware on a Linux host! (I assume that that's because VMware is > passing some call to the host.) > > Can anyone tell me what it is that I'm missing which would prevent the > file from being created on Windows natively? > > I'm sorry I can't provide any more of the code, and I know that that > will hamper your efforts in helping me, so I apologise up front. > > Assumptions: > You can assume self.checkbox25.GetValue() is always false for now, and > self.Info[x][0] contains a two character string like "00" or "09" or > "14". There is always a match in the fileTarget, so self.Info[x][2] > will always be true at some point, as will self.Info[x][4]. I am > cutting an HTML file at predetermined comment sections, and I have > control over the HTML files that are being cut. (So I can force the > file to match what I need it to match if necessary.) > > I hope however that it's something obvious that a Python guru here > will be able to spot and that this n00b is missing! > > Thanks! Well, not to be rude, but that's quite a spaghetti code, some of the guilt, however, was for the mailing program that cuts 80+ lines. Others was the use of things like "for i in range(len(f)):" or "if (a == True)". Try checking whether you're trying to write to a path like r"\dir \file.txt" or r"dir\file.txt" instead of r"C:\dir\file.txt" in Windows. If that doesn't solve the problem, tell us a few things: - Any error messages? Or simply nothing is written out? - Has a blank file get created? -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
"Mensanator" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | On Jun 7, 6:43?pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: | > zip(range(9,20), iterable) | | Oh, dear. You didn't actually try this, did you? Works fine in Py3, which is what I use now. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Jun 8, 12:24 am, Mensanator <[EMAIL PROTECTED]> wrote: > On Jun 7, 5:21�am, Paul Miller <[EMAIL PROTECTED]> wrote: > > > On Fri, 06 Jun 2008 18:01:45 -0700, Mensanator wrote: > > > What happens if your iterables aren't the same length? > > > I chose not to consider that case, > > That's a bad habit to teach a newbie, isn't it? > > > since they were the same length in the > > original post. � > > The issue I'm stressing is HOW they got to be > the same size. If I was teaching programming > and the OP turned in that example, I would mark > him down. Not because he got the answer wrong. > Not because he used zip. Not because he failed > to use enumerate or itertools. But because he > hardcoded the array bounds and THAT'S the lesson > the OP should take away from this. Mark him down? Rather blind attack on the approach. If I have a variable coord that contains (x, y, z) and I hardcoded their meanings and bounds, you're still marking me down for the possibility of adding a fourth dimension? While I'm aware that I won't ever be concerned by the fourth, fifth, ... dimensions ever in my life. In some usage, hardcoding has no harm and in fact might be useful. If I have a data that contains 8 sections, and I know that since this is a low level protocol, it's not going to grow legs and arms. It's natural to use a list/tuple and hardcode the datas length. > > Based on the variable names, it seemed reasonable that > > there would always be a 1-to-1 correspondence between > > elements of each list. � > > Yes, reasonable at the time. But this is Python, > not C. Lists can change size under program control, > a feature that's extremely useful. But there's a > price for that usefulness. Practices that made > sense in C (define a constant to set array bounds) > aren't transportable over to systems that simply > don't have the restrictions that require those > practices. > > > However, if you do > > > score_costs = [(base_scores[i], score_costs[i]) for i in range (min (len > > (base_scores), len (score_costs))] > > > then you get exactly what you would get using zip. � > > And if the iterables change size dynamically, you > could get either a crash due to index out of range > or else silently a wrong answer. > > > That's one heck of a > > long line, though, hence my earlier comment: > > I have no problem telling the OP this method. > But I think you should warn him about potential > problems. > > Surely you didn't intend to leave him to twist > in the wind so that he learns a thing or two > when his programs crash? That's the best way to learn: "making mistakes". You don't learn anything if you never make mistakes. > > If it doing what zip() does makes sense, then just use zip(). �Otherwise, > > check for the case where the iterables are of different length, and do > > the appropriate thing (raise an error, pad the shorter one, whatever). > > That's all I'm suggesting. Along with pointing out > that enumerate or itertools can do this for him. I think it's up to the OP, not you, to decide whether the use of bare zip is enough and whether data truncation might or might not be a problem. It seems that since he has used zip in his original post, he thought it fits his situation best, perhaps its truncation behavior is something he wanted to exploit in the first place. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
Hi list. Do test-driven development or behaviour-driven development advocate how to do higher-level testing than unit testing? >From reading up on the subject, I see that there are formally these types of testing: unit integration system acceptance I'm asking about this, because as suggested by various posters, I have written my latest (small) app by following a Behaviour-Driven Development style. The small app consists of about 5 relatively simple classes, each with behaviour tests, and mocks for the other objects it uses. I wrote the tests before any code (I cheated a bit here and there, like adding logging before adding logger mocks and tests to check that the logging took place). That went well, and the code ended up much more modular than if I hadn't followed BDD. And I feel more confident about the code quality than before ;-) The testing module has about 2x the lines of code as the code being tested. My problem is that I haven't run the app once yet during development :-/ It looks like I've fallen into the trap described here: http://en.wikipedia.org/wiki/Test-driven_development#Fakes.2C_mocks_and_integration_tests Should I go ahead and start manually testing (like I would have from the beginning if I wasn't following TDD), or should I start writing automated integration tests? Is it worth the time to write integration tests for small apps, or should I leave that for larger apps? I've tried Googling for integration testing in the context of TDD or BDD and haven't found anything. Mostly information about integration testing in general. When following BDD or TDD, should one write integration tests first (like the unit tests), or later? Or don't those practices cover anything besides unit testing? Which integration test process should one use? (top down, bottom up, big bang, etc). Thanks in advance for any tips. David. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQlite none english char
Gandalf wrote: > I works with python 2.5 on windows, And I use sqlite3 > > Now, I have problem searching string in Hebrew in my database > > I have table called "test" with field num and test > firs row i insert "1" and "עברית" (that is "Hebrew" in Hebrew) > second row i insert "2" and "English" [...] I recommend you use Unicode strings for all your Python strings in the application. You can then be that things will just work with the sqlite3 module. The problem is that the sqlite3 module doesn't currently check if what you insert into the database is in UTF-8 encoding. But if it isn't, you're likely to run into problems later on. So, let's assume that you've written your Python using a UTF-8 editor, you can then use something like: # coding: utf-8 as the first line in the script. Among others, this will allow you to write Unicode literals in UTF-8, i. e. do something like: data = u"עברית". then you can insert this into the database: cur.execute("insert into test(test) values (?)", (data,)) Note that I use the parametrized form of execute() with ? as placeholders. *Always* use this when the SQL statement is not constant, but has parameters of some sort. > [...] > cur.execute("select * from `test` where text like '%"+i+"%' ") > for row in cur: > print row[1] > > but this one print me nothing > instead of עברית This could be two problems. Either (likely) it simply isn't found because you inserted garbage (non-UTF-8 data) or you got a decoding error to UTF-8 executing the select, which the sqlite3 module will currently unfortunately ignore and return a None value instead. Again, use the parametrized form of the execute() statement with Unicode Python strings to avoid any problems. cur.execute("select * from test where text like '%' || ? || '%'", (searchstr,)) !!! Ok, I just found out that you used the + operator in SQL to concatenate strings. Don't, as it will not work (except on maybe MySQL). Use the || operator instead! Note that when you use cur.execute(sql, params), then params is actually a tuple of parameters. In the above examples there was only one parameter, so it was a one-tuple, which is written as (element,). Dont'write it as (element), because Python will not recognize it as a tuple then. Don't hesitate to ask if you need further help. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: simple question on list manipulation from a newbie
On Jun 8, 4:42 pm, Sengly <[EMAIL PROTECTED]> wrote: [snip] > Thank you all for your help. I found a solution as the following: The following is a solution to what? > > alist = [ > {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'}, That is not yet valid Python. You will get a syntax error pointing to the comma after 'domestic_dog'. Do you mean: (1) alist = [ {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')}, {'noun': ('frump', 'dog')}, # etc ] or (2) alist = [ ('dog', 'domestic_dog', 'Canis_familiaris'), ('frump', 'dog'), # etc ] or (3) something else? > {'noun': 'frump', 'dog'}, > {'noun': 'dog',}, > {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'}, > {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog', > 'wiener', 'wienerwurst', 'weenie'}, > {'noun': 'pawl', 'detent', 'click', 'dog'}, > {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'}, > ] > > def getAll(alist): > list=[] > for i in range(0,len(alist)): > list.extend(alist[i][:]) Note: the use of [:] to copy the contents of each element indicates that you think that each element is a sequence (list/tuple/whatever) i.e. option (2) above. > return list > Whatever that is solving, it could be written much more clearly as: answer = [] # don't shadow the builtin list function # and use meaningful names for sublist in alist: answer.extend(sublist[:]) return answer Aside: Why do you think you need to copy sublist? Does the plot involve later mutation of alist? And it can be done even more clearly using a list comprehension: [element for sublist in alist for element in sublist] HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Can this be done with list comprehension?
On Jun 8, 7:27 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > "Karlo Lozovina" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > | I figured that out few minutes ago, such a newbie mistake :). The fix I > | came up with is: > | > | result = ['something'] + [someMethod(i) for i in some_list] > | > | Are there any other alternatives to this approach? > > result = [something] > result.extend(someMethod(i) for i in some_list) > > avoids creating and deleting an intermediate list or: result = ['something'].extend(someMethod(i) for i in some_list) it also avoids intermediate list and is one line. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Jun 8, 8:56 am, Mensanator <[EMAIL PROTECTED]> wrote: > On Jun 7, 8:22�pm, John Salerno <[EMAIL PROTECTED]> wrote: > > > Mensanator wrote: > > > What I DID say was that how the builtins actually > > > work should be understood and it APPEARED that the > > > OP didn't understand that. Maybe he understood that > > > all along but his example betrayed no evidence of > > > that understanding. > > > Well, the truth is that I know zip truncates to the shorter of the two > > arguments, > > Ok, sorry I thought otherwise. > > > and also in my case the two arguments would always be the > > same length. > > Yes, because you're controlling the source code. > But since lists are mutable, source code literals > don't always control the length of the list. Since when source code literals ever control the length of a list? What controls the length of the list is the semantic meaning of the list, in some cases it just makes no sense that the list would ever have different length. (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On 22 May, 17:14, cm_gui <[EMAIL PROTECTED]> wrote: > Python is slow. Almost all of the web applications written in > Python are slow. Zope/Plone is slow, sloow, so very slooow. Even > Google Apps is not faster. Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. You might like to look at Norvig's analysis which supports your view about Python being slow. http://norvig.com/python-lisp.html Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Different execution time in python code between embedded or standalone
HI list, I found the problem guys, when I embedded python code didn't call to PyEval_InitThreads(); This function initialize GIL and other data structures for do a python code thread safe. I believe the python traditional ( python name_script.py ) run always a thread safe interpreter. Therefore, it's normal found best performance in no thread safe environment and thread safe environment. But I have a small question, if I have a typical PyObject_CallObject environment and main code don't call to PyEval_InitThreads() after Py_Initialize(), if in python code function called launch some threads this interpreter will be prepare for handle more one thread with python thread safe environment, can everybody help me ? Thks On Tue, Jun 3, 2008 at 9:58 PM, Pau Freixes <[EMAIL PROTECTED]> wrote: > Hi list, > > First Hello to all, this is my and hope not end message to the list :P > > This last months I have been writting a program in c like to mod_python > for embedding python language, it's a middleware for dispatch and execute > python batch programs into several nodes. Now I'm writing some python > program for test how scale this into several nodes and comparing with > "standalone" performance. > > I found a very strange problem with one application named md5challenge, > this aplication try to calculate the max number md5 digest in several > seconds, md5challenge use a simple signal alarm for stop program when time > has passed. This is the code of python script > > def handler_alrm(signum, frame): > global _signal > global _nrdigest > global _f > > > _signal = True > > def try_me(): > global _nrdigest > global _f > global _signal > > _f = open("/dev/urandom","r") > while _signal is not True: > buff = _f.read(_const_b) > md5.md5(buff).hexdigest() > _nrdigest = _nrdigest + 1 > > if _f is not None : > _f.close() > > def main( req ): > global _nrdigest > > > signal.signal(signal.SIGALRM, handler_alrm) > signal.alarm(req.input['time']) > > > try_me() > > req.output['count'] = _nrdigest > > return req.OK > > > if __name__ == "__main__": > > # test code > class test_req: > pass > > req = test_req() > req.input = { 'time' : 10 } > req.output = { 'ret' : 0, 'count' : 0 } > req.OK = 1 > > main(req) > > print "Reached %d digests" % req.output['count'] > > > When I try to run this program in standalone into my Pentium Dual Core > md4challenge reached 1.000.000 milion keys in 10 seconds but when i try to > run this in embedded mode md5challenge reached about 200.000 more keys !!! I > repeat this test many times and always wins embedded mode !!! What's > happen ? > > Also I tested to erase read dependencies from /dev/random, and calculate > all keys from same buffer. In this case embedded mode win always also, and > the difference are more bigger !!! > > Thks to all, can anybody help to me ? > -- > Pau Freixes > Linux GNU/User -- Pau Freixes Linux GNU/User -- http://mail.python.org/mailman/listinfo/python-list
Re: SQlite none english char
On Jun 8, 11:00 am, Gerhard Häring <[EMAIL PROTECTED]> wrote: > Gandalf wrote: > > I works with python 2.5 on windows, And I use sqlite3 > > > Now, I have problem searching string in Hebrew in my database > > > I have table called "test" with field num and test > > firs row i insert "1" and "עברית" (that is "Hebrew" in Hebrew) > > second row i insert "2" and "English" [...] > > I recommend you use Unicode strings for all your Python strings in the > application. You can then be that things will just work with the sqlite3 > module. > > The problem is that the sqlite3 module doesn't currently check if what > you insert into the database is in UTF-8 encoding. But if it isn't, > you're likely to run into problems later on. > > So, let's assume that you've written your Python using a UTF-8 editor, > you can then use something like: > > # coding: utf-8 > > as the first line in the script. Among others, this will allow you to > write Unicode literals in UTF-8, i. e. do something like: > > data = u"עברית". > > then you can insert this into the database: > > cur.execute("insert into test(test) values (?)", (data,)) > > Note that I use the parametrized form of execute() with ? as > placeholders. *Always* use this when the SQL statement is not constant, > but has parameters of some sort. > > > [...] > > cur.execute("select * from `test` where text like '%"+i+"%' ") > > for row in cur: > > print row[1] > > > but this one print me nothing > > instead of עברית > > This could be two problems. Either (likely) it simply isn't found > because you inserted garbage (non-UTF-8 data) or you got a decoding > error to UTF-8 executing the select, which the sqlite3 module will > currently unfortunately ignore and return a None value instead. > > Again, use the parametrized form of the execute() statement with Unicode > Python strings to avoid any problems. > > cur.execute("select * from test where text like '%' || ? || '%'", > (searchstr,)) > > !!! Ok, I just found out that you used the + operator in SQL to > concatenate strings. Don't, as it will not work (except on maybe MySQL). > Use the || operator instead! > > Note that when you use cur.execute(sql, params), then params is actually > a tuple of parameters. In the above examples there was only one > parameter, so it was a one-tuple, which is written as (element,). > Dont'write it as (element), because Python will not recognize it as a > tuple then. > > Don't hesitate to ask if you need further help. > > -- Gerhard I solved the problem by entering data manually but now the problem is that i had to delete this function: con.text_factory = str and now I can't see the data that I entered thought my sqlite manager -- http://mail.python.org/mailman/listinfo/python-list
Re: Can this be done with list comprehension?
Lie <[EMAIL PROTECTED]> wrote: > On Jun 8, 7:27 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: >> "Karlo Lozovina" <[EMAIL PROTECTED]> wrote in message >> >> news:[EMAIL PROTECTED] >> | I figured that out few minutes ago, such a newbie mistake :). The >> | fix I came up with is: >> | >> | result = ['something'] + [someMethod(i) for i in some_list] >> | >> | Are there any other alternatives to this approach? >> >> result = [something] >> result.extend(someMethod(i) for i in some_list) >> >> avoids creating and deleting an intermediate list > > or: > result = ['something'].extend(someMethod(i) for i in some_list) > > it also avoids intermediate list and is one line. and also throws the list away as soon as it creates it. Didn't you read earlier in this thread: list methods that mutate the list in-place return None. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
David <[EMAIL PROTECTED]> writes: > I'm asking about this, because as suggested by various posters, I > have written my latest (small) app by following a Behaviour-Driven > Development style. Congratulations on taking this step. > That went well, and the code ended up much more modular than if I > hadn't followed BDD. And I feel more confident about the code > quality than before ;-) The testing module has about 2x the lines of > code as the code being tested. This ratio isn't unusual, and is in fact a little on the low side in my experience. If you get decent (well-founded!) confidence in the resulting application code, then it's certainly a good thing. > My problem is that I haven't run the app once yet during development > :-/ That might be an artifact of doing bottom-up implementation exclusively, leading to a system with working parts that are only integrated into a whole late in the process. I prefer to alternate between bottom-up implementation and top-down implementation. I usually start by implementing (through BDD) a skeleton of the entire application, and get it to the point where a single trivial user story can be satisfied by running this minimally-functional application. Then, I make an automated acceptance test for that case, and ensure that it is run automatically by a build infrastructure (often running on a separate machine) that: - exports the latest working tree from the version control system - builds the system - runs all acceptance tests, recording each result - makes those results available in a summary report for the build run, with a way to drill down to the details of any individual steps That automated build is then set up to run either as a scheduled job periodically (e.g. four times a day), or as triggered by every commit to the version control system branch nominated for "integration" code. > Should I go ahead and start manually testing (like I would have from > the beginning if I wasn't following TDD), or should I start writing > automated integration tests? In my experience, small applications often form the foundation for larger systems. Time spent ensuring their build success is automatically determined at every point in the development process pays off tremendously, in the form of flexibility in being able to use that small application with confidence, and time saved not needing to guess about how ready the small app is for the nominated role in the larger system. > Is it worth the time to write integration tests for small apps, or > should I leave that for larger apps? There is a threshold below which setting up automated build infrastructure is too much overhead for the value of the system being tested. However, this needs to be honestly appraised: can you *know*, with omniscient certainty, that this "small app" isn't going to be pressed into service in a larger system where its reliability will be paramount to the success of that larger system? If there's any suspicion that this "small app" could end up being used in some larger role, the smart way to bet would be that it's worth the effort of setting up automated build testing. > I've tried Googling for integration testing in the context of TDD or > BDD and haven't found anything. Mostly information about integration > testing in general. I've had success using buildbot http://buildbot.net/> (which is packaged as 'buildbot' in Debian GNU/Linux) for automated build and integration testing and reporting. > When following BDD or TDD, should one write integration tests first > (like the unit tests), or later? All the tests should proceed in parallel, in line with the evolving understanding of the desired behaviour of the system. This is why the term "behaviour driven development" provide more guidance: the tests are subordinate to the real goal, which is to get the developers, the customers, and the system all converging on agreement about what the behaviour is meant to be :-) Your customers and your developers will value frequent feedback on progress, so: - satisfying your automated unit tests will allow you to - satisfy your automated build tests, which will allow you to - satisfy automated user stories ("acceptance tests"), which will allow the customer to - view an automatically-deployed working system with new behaviour (and automated reports for behaviour that is less amenable to direct human tinkering), which will result in - the customers giving feedback on that behaviour, which will inform - the next iteration of behaviour changes to make, which will inform - the next iteration of tests at all levels :-) -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Problem pickling exceptions in Python 2.5/2.6
I'm having troubles pickling classes that extend Exception. Given the following source: class Foo(object): def __init__(self, m): self.m=m class Bar(Exception): def __init__(self, m): self.m=m import pickle s=pickle.dumps(Foo("test")) pickle.loads(s) # normal object works s=pickle.dumps(Bar("test")) pickle.loads(s) # exception object fails When running this in Python 2.5 or Python 2.6a, it crashes on the last line, with: [C:\]c:\python25\python.exe pickling.py Traceback (most recent call last): File "pickling.py", line 14, in pickle.loads(s) # exception object fails File "C:\Python25\lib\pickle.py", line 1374, in loads return Unpickler(file).load() File "C:\Python25\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python25\lib\pickle.py", line 1133, in load_reduc value = func(*args) TypeError: __init__() takes exactly 2 arguments (1 given) This used to work fine in Python 2.3 and 2.4... What has been changed in 2.5? Is there a way to get rid of the error? (I tried some stuff with __getinitargs__ and __getnewargs__ but couldn't get it to work). --irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get System.Timers.Timer
John Machin wrote: > One grabs one's googler and goes a-huntin' ... > ==>> http://msdn.microsoft.com/en-us/library/system.timers.aspx > Looks like part of .NET so one might expect that one already have it. > However one would need to use IronPython to access it ... Or the PythonDotNET extension for CPython. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting Math Problem
On Jun 6, 2:25 am, "Rüdiger Werner" <[EMAIL PROTECTED]> wrote: > "BEES INC" <[EMAIL PROTECTED]> schrieb im Newsbeitragnews:[EMAIL PROTECTED] > ... > > Problem: Star Ratings > > People can rate cheeseburgers on my website with a star rating of 0-5 > stars (whole stars only), 5 being mighty tasty and 0 being disgusting. > I would like to show the average of everyone's ratings of a particular > cheeseburger to the nearest half star. I have already calculated the > average rating as a float (star_sum) and the total number of people > that rated the particular cheeseburger (num_raters). The result should > be stored as a float in a variable named "stars." > My Solution (in Python): > > Well seems this is a typical half even rounding problem. > > See > > http://mail.python.org/pipermail/python-list/2008-April/485889.html > > for a long discussion > > However since your problem looks like a typical homework problem i made my > example > buggy by intention. > > However the result should be correct. > > have fun! > > def myround(x): >   d, m = divmod(x, 2) >   return 2*d + round(m - 1) + 1 > > num = 1.5 > for _i in xrange(30): >   print num, ' -> ', myround(num * 2)/2 >   num -= 0.1 > > >pythonw -u "test18.py" > > 1.5  ->  1.5 > 1.4  ->  1.5 > 1.3  ->  1.5 > 1.2  ->  1.0 > 1.1  ->  1.0 > 1.0  ->  1.0 > 0.9  ->  1.0 > 0.8  ->  1.0 > 0.7  ->  0.5 > 0.6  ->  0.5 > 0.5  ->  0.5 > 0.4  ->  0.5 > 0.3  ->  0.5 > 0.2  ->  0.0 > 0.1  ->  0.0 > -1.94289029309e-016  ->  0.0   < --- hint for bug > -0.1  ->  0.0 > -0.2  ->  0.0 > -0.3  ->  -0.5 > -0.4  ->  -0.5 > -0.5  ->  -0.5 > -0.6  ->  -0.5 > -0.7  ->  -0.5 > -0.8  ->  -1.0 > -0.9  ->  -1.0 > -1.0  ->  -1.0 > -1.1  ->  -1.0 > -1.2  ->  -1.0 > -1.3  ->  -1.5 > -1.4  ->  -1.5 > > >Exit code: 0 > > to avoid the bug have a look at: > > http://mail.python.org/pipermail/python-list/2008-April/485934.html > > and try this example: > > num = 3 > for _i in xrange(num * 10,-num *10, -1): >   if myround(float(_i)/10) != myround(num): >     print num, " -> ", myround(num ), " --- ",  myround(float(_i)/10) >     print "-" >   num -= 0.1 Well, I don't think that's the problem. I don't think the OP cares what the rounding method is, it doesn't really matters that much in this case since this function is only used for output and the underlying rating value is untouched. In that case, try this: from __future__ import division rating = round(star_sum / num_raters) whole, half = divmod(rating, 2) -- http://mail.python.org/mailman/listinfo/python-list
time.clock() or Windows bug?
hi, In this code I read out an instrument during a user determined period, and save the relative time of the sample (since the start of the test) and the readback value in a csv file. #v+ from datetime import * from time import * from visa import * from random import * [..] for Reading in range(Readings): RelTimeOfSample = "%.1f" % clock() #PwrMtr.write("READ?") #Sample = "%.3f" % float(PwrMtr.read()) Sample = "%.3f" % (uniform(8.9,9.3))# Simulation of reading. print "Sample %s, at %s seconds from start; Output power is: %s dBm" % (Reading+1, RelTimeOfSample, Sample) writer.writerow([RelTimeOfSample, Sample]) ResultFile.flush() sleep(6.6) #v- Output: Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm Sample 2, at 6.6 seconds from start; Output power is: 9.280 dBm Sample 3, at 13.2 seconds from start; Output power is: 9.096 dBm Sample 4, at 19.8 seconds from start; Output power is: 9.166 dBm Sample 5, at 26.4 seconds from start; Output power is: 8.918 dBm Sample 6, at 33.0 seconds from start; Output power is: 9.183 dBm Sample 7, at 39.7 seconds from start; Output power is: 8.903 dBm Sample 8, at 46.3 seconds from start; Output power is: 9.138 dBm Sample 9, at 52.9 seconds from start; Output power is: 9.163 dBm Sample 10, at 59.5 seconds from start; Output power is: 9.075 dBm Sample 11, at 66.1 seconds from start; Output power is: 9.230 dBm Sample 12, at 72.7 seconds from start; Output power is: 9.225 dBm Sample 13, at 79.3 seconds from start; Output power is: 9.053 dBm Sample 14, at 85.9 seconds from start; Output power is: 9.066 dBm Sample 15, at 92.5 seconds from start; Output power is: 9.109 dBm Sample 16, at 99.1 seconds from start; Output power is: 9.286 dBm Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm Sample 25, at 158.8 seconds from start; Output power is: 9.139 dBm Sample 26, at 165.4 seconds from start; Output power is: 9.241 dBm Sample 27, at 172.1 seconds from start; Output power is: 8.938 dBm Sample 28, at 178.7 seconds from start; Output power is: 8.947 dBm Sample 29, at 185.3 seconds from start; Output power is: 9.252 dBm Sample 30, at 191.9 seconds from start; Output power is: 9.082 dBm Sample 31, at 198.5 seconds from start; Output power is: 9.224 dBm Sample 32, at 205.1 seconds from start; Output power is: 8.902 dBm Sample 33, at 211.7 seconds from start; Output power is: 9.182 dBm Sample 34, at 218.3 seconds from start; Output power is: 8.974 dBm Sample 35, at 224.9 seconds from start; Output power is: 9.129 dBm Sample 36, at 231.5 seconds from start; Output power is: 9.214 dBm Sample 37, at 238.1 seconds from start; Output power is: 9.188 dBm Sample 38, at 244.8 seconds from start; Output power is: 8.909 dBm Sample 39, at 251.4 seconds from start; Output power is: 9.197 dBm Sample 40, at 258.0 seconds from start; Output power is: 8.946 dBm Sample 41, at 264.6 seconds from start; Output power is: 9.228 dBm Sample 42, at 271.2 seconds from start; Output power is: 8.938 dBm Sample 43, at 92071.3 seconds from start; Output power is: 8.964 dBm Sample 44, at 284.4 seconds from start; Output power is: 9.276 dBm Sample 45, at 291.0 seconds from start; Output power is: 8.932 dBm Sample 46, at 297.6 seconds from start; Output power is: 9.158 dBm But look at the timestamps of samples 21, 22 and 43. What is causing this? I've replaced the time.clock() with time.time(), and that seems to solve the problem, but I would like to know if it's something I misunderstand or if it's a problem with the platform (Windows Server 2003) or the time.clock() function. T:\Theo\Python>ver Microsoft Windows [Version 5.2.3790] T:\Theo\Python>c:\Python25\python.exe --version Python 2.5.1 Thanks, Theo -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError while reading xml file (newbie question)
You won't believe how helpful your reply was. I was looking for a problem that did not exist. You wrote : > (3) why you think you need to have "data.decode(.)" at all and after that : > (7) are you expecting non-ASCII characters after H_C= ? what > characters? when you open your xml file in a browser, what do you see > there? And I went back to see why I was doing this in the first place (couldn't remember after struggling for so many hours) and I opened the file in Interent explorer. The browser wouldn't open it because it didn't like the encoding declared in the tag "System does not support the specified encoding. Error processing resource 'http://scores24live.com/xml/live.xml'. Line 1, ..." (IE was the only program that complained, FF and some other tools opened it without hassle) Then I went back and looked for the original message that got me struggling and it was this : xml.parsers.expat.ExpatError: unknown encoding: line 1, column 30 From then on it was easy to see that it was the xml encoding that was wrong : when I switched that to : everything just worked. I can't thank you enough for opening my eyes... PS.: The UnicodeEncodeError must have something to do with Java's UTF-8 implementation (the xml is produced by a Dom4j on a J2EE server). Those characters I posted in the original message should have read "ΚΙΝΑ" (China in Greek) but I after I copy pasted them in the post it came up like this : H_C="Γ�Γ�Γ�Γ�" A_C which is weird because this page is UTF encoded which means that characters should be 1 or 2 bytes long. From the message you see that instead of 4 characters it reads 8 which means there were extra information in the string. If the above is true then it might be something for python developers to address in the language. If someone wishes to investigate further here is the link for info on java utf and the file that caused the UnicodeEncodeError : http://en.wikipedia.org/wiki/UTF-8 (the java section) http://java.sun.com/javase/6/docs/api/java/io/DataInput.html#modified-utf-8 the xml file : http://dsigned.gr/live.xml On Jun 8, 3:50 am, John Machin <[EMAIL PROTECTED]> wrote: > On Jun 8, 10:12 am, nikosk <[EMAIL PROTECTED]> wrote: > > > > > I just spent a whole day trying to read an xml file and I got stuck > > with the following error: > > > Exception Type: UnicodeEncodeError > > Exception Value:'charmap' codec can't encode characters in position > > 164-167: character maps to > > Exception Location: C:\Python25\lib\encodings\cp1252.py in encode, > > line 12 > > > The string that could not be encoded/decoded was: H_C="Γ�Γ�Γ�Γ�" A_C > > > After some tests I can say with confidence that the error comes up > > when python finds those greek characters after H_C=" > > > The code that reads the file goes like this : > > > from xml.etree import ElementTree as ET > > > def read_xml(request): > > data = open('live.xml', 'r').read() > > data = data.decode('utf-8', 'replace') > > data = ET.XML(data) > > > I've tried all the combinations of str.decode str.encode I could > > think of but nothing. > > > Can someone please help ? > > Perhaps, with some more information: > (1) the *full* traceback > (2) what encoding is mentioned up the front of the XML file > (3) why you think you need to have "data.decode(.)" at all > (4) why you think your input file is encoded in utf8 [which may be > answered by (2)] > (5) why you are using 'replace' (which would cover up (for a while) > any non-utf8 characters in your file) > (6) what "those greek characters" *really* are -- after fiddling with > encodings in my browser the best I can make of that is four capital > gamma characters each followed by a garbage byte or a '?'. Do > something like: > > print repr(open('yourfile.xml', 'rb').read()[before_pos:after_pos]) > > (7) are you expecting non-ASCII characters after H_C= ? what > characters? when you open your xml file in a browser, what do you see > there? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's a call-tip to do?
"Terry Reedy" wrote: > "Raymond Hettinger" wrote > > Tal Einat wrote: > > > I just ran into this. In IDLE (Python 2.5), the call-tip for > > itertools.count is: > > "x.__init__(...) initializes x; see x.__class__.__doc__ for signature" > > | My IDLE (1.2.2 running on Python 2.5.2) has the correct call-tip. > > As does my 3.0 version. count([first_val]) -> count object Sorry, my bad. I'm working with an experimental version of CallTips.py, and apparently it works differently... I should have tested this before posting. The problem still exists though; try the following, for example: class A: def __init__(self): "Doc-string for the constructor" The call-tip for A will be empty, instead of showing the constructor's doc-string. In my version, which prefers the __init__ doc-string to the class's doc-string, the call-tip works for the above example but not for itertools.count and such. It seems to me that preferring the __init__ doc-string should be the way to go... am I wrong? - Tal Einat reduce(lambda m,x:[m[i]+s[-1] for i,s in enumerate(sorted(m))], [[chr(154-ord(c)) for c in '.&-&,l.Z95193+179-']]*18)[3] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Paul Rubin wrote: > This is bogus about 95% of the time though. For the cases where it is > really desired, I think it's best to require the target class to be > enable it specifically somehow, maybe by inheriting from a special > superclass. That could let the compiler statically resolve member > lookups the rest of the time. No it wouldn't. Think about multiple inheritance. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > How about #define class struct Won't work. Consider `template ...'. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Russ P. <[EMAIL PROTECTED]> wrote: > The idea of being able to discern properties of an object by its name > alone is something that is not normally done in programming in > general. Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, or Erlang then. And that's just the ones I can think of off the top of my head. * Prolog and Erlang distinguish atoms from variables by the case of the first letter; also `_' is magical and is equivalent to a new variable name every time you use it. * Smalltalk distinguishes between global and local variables according to the case of the first letter. * Haskell distinguishes between normal functions and constructors (both data constructors and type constructors) by the case of the first letter, and has Prolog's `_' convention. * ML allows a single-quote in variable names, but reserves names beginning with a single-quote for type variables. It also has Prolog's `_' convention. As far as I can see, discerning properties of a thing from its name seems relatively common. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Fuzzyman <[EMAIL PROTECTED]> wrote: > So, you are stating that no API programmer using Python *ever* has a > valid or genuine reason for wanting (even if he can't have it) genuine > 'hiding' of internal state or members from consumers of his (or > her...) API? I don't want to speak for whoever you were responding to, but from my point of view... Yes. I understand the difference between the documented interface of a system and the details of its implementation. But sometimes it can be useful to take advantage of implementation details, particularly if the published interface is inadequate in some way. Whether or not I choose to make use of implementation details is a trade-off between immediate convenience and maintainability, but that's something I can make a rational decision about. By enforcing your `data hiding', you're effectively telling me that I'm too stupid to make rational decisions of this sort. And that's actually extremely insulting. -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
ANN: Pyrex 0.9.8.3
Pyrex 0.9.8.3 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Compiling multiple .pyx files in one go works properly now, and can be substantially faster if you have a lot of modules that cimport from each other. I had to rearrange various things to make this work, so I hope I haven't broken anything. The compatibility rules for nogil function pointers have been fixed, so you can assign a nogil function to a function pointer that isn't declared nogil (but not the other way around). Plus a few other bug fixes listed in CHANGES. What is Pyrex? -- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code correctness, and testing strategies
Thanks for your informative reply. On Sun, Jun 8, 2008 at 12:28 PM, Ben Finney <[EMAIL PROTECTED]> wrote: > David <[EMAIL PROTECTED]> writes: > [...] > >> My problem is that I haven't run the app once yet during development >> :-/ > > That might be an artifact of doing bottom-up implementation > exclusively, leading to a system with working parts that are only > integrated into a whole late in the process. > I did do it in a mostly top-down way, but didn't stop the BDD process to actually run the app :-) It sounds like what you are suggesting is something like this: 1) Following BDD, get a skeleton app working Then, your BDD process gets a few extra steps: Old steps: 1) Write a test which fails for [new feature] 2) Write code for [new feature] to pass the test 3) Refactor if needed New steps: 4) Run the app like an end-user, and see that it works for the [new feature] 5) Write an automated test which does (4), and verifies the [new feature] is working correctly Does this mean that you leave out the formal 'integration' and 'systems' testing steps? By actually running the app you are doing those things more or less. Could you also leave out the unit tests, and just write automated acceptance tests? I guess that would have problems if you wanted to re-use code in other apps. Or, if acceptance tests break then it's harder to see which code is causing the problem. Also, if you had to implement a few "user stories" to get your app into a skeleton state, do you need to go back and write all the missing acceptance tests? I have a few problems understanding how to write automated acceptance tests. Perhaps you can reply with a few URLs where I can read more about this :-) 1) services If your app starts, and keeps running indefinitely, then how do you write acceptance tests for it? Does your acceptance tests need to interact with it from the outside, by manipulating databases, system time, restarting the service, etc? I presume also that acceptance tests need to treat your app as a black box, so they can only check your apps output (log files, database changes, etc), and not the state of objects etc directly. 2) User interfaces How do you write an acceptance test for user interfaces? For unit tests you can mock wx or gtk, but for the 'real' app, that has to be harder. Would you use specialised testing frameworks that understand X events or use accessibility/dcop/etc interaction? 3) Hard-to-reproduce cases. How do you write acceptance tests for hard-to-reproduce cases where you had to use mock objects for your unit tests? ... In cases like the above, would you instead: - Have a doc with instructions for yourself/testers/qa to manually check features that can't be automatically tested - Use 'top-down' integration tests, where you mock parts of the system so that that features can be automatically tested. - Some combination of the above [...] >> Is it worth the time to write integration tests for small apps, or >> should I leave that for larger apps? > > There is a threshold below which setting up automated build > infrastructure is too much overhead for the value of the system being > tested. There is no 'build' process (yet), since the app is 100% Python. But I will be making a Debian installer a bit later. My current 'build' setup is something like this: 1) Make an app (usually C++, shell-script, Python, or mixed) 2) Debianise it (add a debian subdirectory, with control files so Debian build tools know how to build binaries from my source, and how they should be installed & uninstalled). 3) When there are new versions, manually test the new version, build a binary debian installer (usually in a Debian Stable chroot with debian tools), on my Debian Unstable dev box, and upload the deb file (and updated Debian repo listing files) to a 'development' or 'unstable' branch on our internal Debian mirror. 4) Install the new app on a Debian Stable testing box, run it, and manually check that the new logic works 5) Move the new version to our Debian repo's live release, from where it will be installed into production. If I adopt BDD, my updated plan was to use it during app development and maintenance, but not for later testing. Do you suggest that after building a .deb in the chroot, the app should also be automatically installed under a chroot & acceptance tests run on my dev machine? Or should I package the acceptance tests along with the app, so that they can be (manually) run on test servers before going into production? Or do both? I've considered setting up a centralised build server at work, but currently I'm the only dev which actually builds & packages software, so it wouldn't be very useful. We do have other devs (PHP mostly), but they don't even use version control :-/. When they have new versions (on their shared PHP dev & testing servers), I copy it into my version control, confirm the changed files with them, build an installer, and upload onto our mirror, so it can be instal
china supply nike shoes oz,nike air max 95,dunk...
"China (www.getvogue.com) supply Nike_Air_Max_87,Nike_Air_Max_95,Nike_Air_Max_360,Nike_Air_Max_Ltd,Nike_Air_Max_TN,Nike_Air_Max_Rift,Nike_Shoes_R3,Nike_Shoes_R4,Nike_Shoes_R5,Nike_Shoes_R6,Nike_Shoes_NZ,Nike_Shoes_OZ,Nike_Shoes_TL,Nike_Shoes_Monster,Nike_Sho¬es_Energia,Nike_Shoes_Turob,Air_Force_1s etc.More please sign in My website! China supply LV Dunk shoes,UGG Boots,Lacoste Puma trainers,D&G Prada Hogan Dsquared2 etc.-please sign in VIEW PROFILE--- " -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question, list comprehension
Johannes Bauer <[EMAIL PROTECTED]> wrote: > import time > localtime = time.localtime(1234567890) > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], > localtime[2], localtime[3], localtime[4], localtime[5]) > print fmttime > > fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in > range(0, 5)]) To reduce typing, set format = '%04d-%02d-%02d %02d:%02d:%02d' Two problems. * Firstly, range(0, 5) == [0, 1, 2, 3, 4], so it's not big enough. Python tends to do this half-open-interval thing. Once you get used to it, you'll find that it actually reduces the number of off-by-one errors you make. * Secondly, the result of a list comprehension is a list; (Unsurprising, really, I know.) But the `%' operator only extracts multiple arguments from a tuple, so you'd need to convert: format % tuple(localtime[i] for i in xrange(6)] (I've replaced range by xrange, which avoids building an intermediate list, and the first argument to range or xrange defaults to zero anyway.) Another poster claimed that localtime returns a tuple. This isn't correct: it returns a time.struct_time, which is not a tuple as you can tell: >>> '%s' % localtime '(2009, 2, 13, 23, 31, 30, 4, 44, 0)' This is one of those times when Python's duck typing fails -- string formatting really wants a tuple of arguments, and nothing else will do. But you can slice a time.struct_time, and the result /is/ a genuine tuple: >>> type(localtime[:6]) which is nice: >>> format % localtime[:6] '2009-02-13 23:31:30' But really what you wanted was probably >>> time.strftime('%Y-%m-%d %H:%M:%S', localtime) '2009-02-13 23:31:30' -- [mdw] -- http://mail.python.org/mailman/listinfo/python-list
Re: Most effective coding.. IDE question.
dave wrote: Hello everyone, I'm a beginning self-taught python student. Currently, I work out my code within IDLE then when I have a version that I like, or that's working, I move it over to a new window and save it. I've been playing w/ Komodo IDE lately, and while it's nice, what I don't like is the "one line at a time" (produced by hitting up-arrow) in the shell. In IDLE, ctrl-p can reproduce a whole function or class - opposed to only the last line in Komodo. Is my IDLE method common? Or am I simply creating more of a headache for myself? What do you recommend? I'm not that advanced and don't need anything fancy. I'm on OS X. Thanks! Dave For th simplest work, you could try skite as an editor; it takes you code in on window, and sends the output to another when you press F5. But--'not advanced' or not--I would suggest you look forward to the time when you will need version control, unit tests, and other utilities of a more comprehensive environment. Take a look at Eclipse, for example. For several sceencasts, python and eclipse included: http://showmedo.com/videos/programming_tools -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
In article <[EMAIL PROTECTED]>, Mark Wooding <[EMAIL PROTECTED]> wrote: > * Prolog and Erlang distinguish atoms from variables by the case of > the first letter; also `_' is magical and is equivalent to a new > variable name every time you use it. Can you explain that in more detail? A literal reading of what you wrote would mean that if you did (assuming this is even legal syntax): _ = 1; y = _; the _'s are different variables, which is absurd enough to make me believe I just misunderstood you. -- http://mail.python.org/mailman/listinfo/python-list
Re: File-writing not working in Windows?
On Jun 8, 4:11 am, Lie <[EMAIL PROTECTED]> wrote: > On Jun 6, 10:18 pm, [EMAIL PROTECTED] wrote: > > > > > > > All, > > > I have the following code: > > for fileTarget in dircache.listdir("directory"): > > (dirName, fileName) = os.path.split(fileTarget) > > f = open(fileTarget).readlines() > > copying = False > > for i in range(len(f)): > > for x in range (0,24,1): > > if (re.search(self.Info[x][3], f[i])): > > #If we have a match for our start of section... > > if (self.Info[x][2] == True): > > #And it's a section we care about... > > copying = > > True #Let's start copying the lines out > > to the temporary file... > > if (os.name == "posix"): > > if (self.checkbox25.GetValue() == > > False): > > tempfileName = "tempdir/" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > else: > > tempfileName = > > self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt" > > else: > > if (self.checkbox25.GetValue() == > > False): > > tempfileName = "tempdir\\" + > > self.Info[x][0] + "_tmp_" + fileName + ".txt" > > else: > > tempfileName = > > self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt" > > else: > > copying = False > > if (re.search(self.Info[x][4], f[i])): > > #Now we've matched the end of our section... > > copying = > > False #So let's stop copying out to > > the temporary file... > > if (copying == True): > > g = open(tempfileName, > > 'a') #Open that file in append mode... > > > g.write(f[i]) #Write the line... > > g.close() > > > This code works PERFECTLY in Linux. Where I have a match in the file > > I'm processing, it gets cut out from the start of the match until the > > end of the match, and written to the temporary file in tempdir. > > > It does not work in Windows. It does not create or write to the > > temporary file AT ALL. It creates the tempdir directory with no > > problem. > > > Here's the kicker: it works perfectly in Windows if Windows is running > > in VMware on a Linux host! (I assume that that's because VMware is > > passing some call to the host.) > > > Can anyone tell me what it is that I'm missing which would prevent the > > file from being created on Windows natively? > > > I'm sorry I can't provide any more of the code, and I know that that > > will hamper your efforts in helping me, so I apologise up front. > > > Assumptions: > > You can assume self.checkbox25.GetValue() is always false for now, and > > self.Info[x][0] contains a two character string like "00" or "09" or > > "14". There is always a match in the fileTarget, so self.Info[x][2] > > will always be true at some point, as will self.Info[x][4]. I am > > cutting an HTML file at predetermined comment sections, and I have > > control over the HTML files that are being cut. (So I can force the > > file to match what I need it to match if necessary.) > > > I hope however that it's something obvious that a Python guru here > > will be able to spot and that this n00b is missing! > > > Thanks! > > Well, not to be rude, but that's quite a spaghetti code, some of the > guilt, however, was for the mailing program that cuts 80+ lines. > Others was the use of things like "for i in range(len(f)):" or "if (a > == True)". > > Try checking whether you're trying to write to a path like r"\dir > \file.txt" or r"dir\file.txt" instead of r"C:\dir\file.txt" in > Windows. > > If that doesn't solve the problem, tell us a few things: > - Any error messages? Or simply nothing is written out? > - Has a blank file get created?- Hide quoted text - > > - Show quoted text - Thanks to everyone for the help. I really do appreciate your suggestions and time; again I apologise for not being able to give you all the code to diagnose. I understand that it made this more difficult and thank you for the input! The error was not with the script. The error was with the HTML that was being parsed! It's the last thing I considered to check, and where I should have started. John, thank you for the link to the style guide. I can see its use and will make my code conform to the standards. Thanks again to everyone! -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
In article <[EMAIL PROTECTED]>, Mark Wooding <[EMAIL PROTECTED]> wrote: > By enforcing your `data hiding', you're effectively telling me that I'm > too stupid to make rational decisions of this sort. And that's actually > extremely insulting. I think that's taking it a bit far. Python doesn't let you manipulate pointers directly. For example, I can't do: s = "foo" sp = address(s) sp[2] = 'x' print s and have it print "fox". Is this because I'm too stupid to make rational decision of this sort? No, it's because the Python programming model exposes some things and hides others which are deemed inappropriate or too low level. One of the things it hides is direct access to raw memory. I don't see that as fundamentally different from a C++ string class which declares its internal buffer to be private. If the goose's pot is black, then the gander's kettle is an equal shade of dark grey. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
I don't know about Erlang (though I'd think it's behaviour sould be similar to prolog), but at least in Prolog, yes, _ and _ are different variables. The whole idea of "_" is that it is a placeholder that can bind to anything, but will be immediately discarded. It's just syntactic sugar so you don't have to create new names for things you don't care about, which could be a problem in prolog (once bound, cannot be bound again on the same branch) or erlang (once bound, bound forever). I just tried on erlang: f(0,_) -> 1+_; f(X,_) -> X*f(X-1,_). produces an error: ./t.erl:4: variable '_' is unbound ./t.erl:5: variable '_' is unbound (referring to the right side uses of the _ symbol) while the definition: f(0,Y)->1+Y; f(X,Y)->X*f(X-1,Y). produces a [very weird, just for testing purposes, don't use it at home] version of 'factorial'. So, you understood well. As I haven't been following this thread, I won't go offtopic talking about functional languages. But yes, on functional (and declarative?) languages, it makes a lot of sense to have a 'symbol' that represents a new variable any time you use it. Cheers, -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie Quoting Roy Smith <[EMAIL PROTECTED]>: > In article <[EMAIL PROTECTED]>, > Mark Wooding <[EMAIL PROTECTED]> wrote: > > > * Prolog and Erlang distinguish atoms from variables by the case of > > the first letter; also `_' is magical and is equivalent to a new > > variable name every time you use it. > > Can you explain that in more detail? A literal reading of what you wrote > would mean that if you did (assuming this is even legal syntax): > >_ = 1; >y = _; > > the _'s are different variables, which is absurd enough to make me believe > I just misunderstood you. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Trying out safethread patch
I'd like to take the python-safethread code out for a spin, but I'm not sure where to start. I downloaded the latest diff: http://python-safethread.googlecode.com/files/safethread-bzr-36020.diff checked out Python 3.0 from the bzr mirror, then ran patch in the typical way. That doesn't apply cleanly at all (too much water under the bridge since this the patch was made). I was thinking if I back up my bzr repository to r36020, apply the patch then sync with the latest bzr revision that might work, but I have no bzr experience. I haven't any idea how to do that. Any suggestions? Thx, -- Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/ "Be different, express yourself like everyone else." -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Jun 8, 3:19�am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > "Mensanator" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > | On Jun 7, 6:43?pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > | > zip(range(9,20), iterable) > | > | Oh, dear. You didn't actually try this, did you? > > Works fine in Py3, which is what I use now. You really ARE cruel to the newbies, aren't you? Don't you think it would have been appropriate to attach a large red label: WARNING! PY3! -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Jun 8, 4:04 am, Lie <[EMAIL PROTECTED]> wrote: > On Jun 8, 8:56 am, Mensanator <[EMAIL PROTECTED]> wrote: > > > > > > > On Jun 7, 8:22�pm, John Salerno <[EMAIL PROTECTED]> wrote: > > > > Mensanator wrote: > > > > What I DID say was that how the builtins actually > > > > work should be understood and it APPEARED that the > > > > OP didn't understand that. Maybe he understood that > > > > all along but his example betrayed no evidence of > > > > that understanding. > > > > Well, the truth is that I know zip truncates to the shorter of the two > > > arguments, > > > Ok, sorry I thought otherwise. > > > > and also in my case the two arguments would always be the > > > same length. > > > Yes, because you're controlling the source code. > > But since lists are mutable, source code literals > > don't always control the length of the list. > > Since when source code literals ever control the length of a list? Isn't score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] considered a literal? > What controls the length of the list is the semantic meaning of the > list, Wha do you mean by that? The list contains 11 objects. How could the length be any different? > in some cases it just makes no sense that the list would ever > have different length. And in such case there won't be any problem, will there? Is that a good habit to teach a newbie? To write code that only works for special cases? > > (snip)- Hide quoted text - > > - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help porting Perl function
In <[EMAIL PROTECTED]> John Machin <[EMAIL PROTECTED]> writes: >It's nothing to do with list comprehensions, which are syntactical >sugar for traditional loops. You could rewrite your list comprehension >in the traditional manner... >and it would still fail for the same reason: mutating the list over >which you are iterating. I normally deal with this problem by iterating backwards over the indices. Here's how I coded the function (in "Python-greenhorn style"): def cull(list): culled = [] for i in range(len(list) - 1, -1, -1): if not_wanted(list[i]): culled.append(list.pop(i)) return culled ...where not_wanted() is defined elsewhere. (For my purposes at the moment, the greater generality provided by making not_wanted() a parameter to cull() was not necessary.) The specification of the indices at the beginning of the for-loop looks pretty ignorant, but aside from that I'm happy with it. Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help porting Perl function
In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes: >In <[EMAIL PROTECTED]> John Machin <[EMAIL PROTECTED]> writes: >>It's nothing to do with list comprehensions, which are syntactical >>sugar for traditional loops. You could rewrite your list comprehension >>in the traditional manner... >>and it would still fail for the same reason: mutating the list over >>which you are iterating. >I normally deal with this problem by iterating backwards over the >indices. Here's how I coded the function (in "Python-greenhorn >style"): ***BLUSH*** Somehow I missed that John Machin had posted almost the exact same implementation that I posted in my reply to him. Reading too fast. Reading too fast. Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
How to get full path to script?
How can a script know its absolute path? (__file__ only gives the path it was used to invoke the script.) Basically, I'm looking for the Python equivalent of Perl's FindBin. The point of all this is to make the scripts location the reference point for the location of other files, as part of a self-contained distribution. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get full path to script?
On Sun, Jun 8, 2008 at 1:03 PM, kj <[EMAIL PROTECTED]> wrote: > > > > How can a script know its absolute path? (__file__ only gives the > path it was used to invoke the script.) > > Basically, I'm looking for the Python equivalent of Perl's FindBin. > > The point of all this is to make the scripts location the reference > point for the location of other files, as part of a self-contained > distribution. > > TIA! > > Kynn > > -- Anything dealing with file paths is probably going to be in the os.path module. The function you are looking for is os.path.abspath(). http://docs.python.org/lib/module-os.path.html > > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Newbie help (TypeError: int argument required)
Hi, I am new to python. I have been having trouble using the MysqlDB. I get an error pointing from the line cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = %u", (self.title, self.text, self.id)) Here is the error: line 56, in save cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = %u", (self.title, self.text, self.id)) File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line 151, in execute query = query % db.literal(args) TypeError: int argument required However when I print out type(self.id) I get . So surely I have provided an int argument. Any ideas anyone?? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get full path to script?
"kj" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] How can a script know its absolute path? (__file__ only gives the path it was used to invoke the script.) Basically, I'm looking for the Python equivalent of Perl's FindBin. The point of all this is to make the scripts location the reference point for the location of other files, as part of a self-contained distribution. TIA! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. import os print os.path.abspath(__file__) -Mark -- http://mail.python.org/mailman/listinfo/python-list
PERSONAL BANKRUPTCY
http://onenesstemplenemam.blogspot.com http://bankruptcy5.blogspot.com/ http://filingbankruptcy1.blogspot.com/ http://bankruptcyattorney1.blogspot.com/ http://personalbankruptcy1.blogspot.com/ http://chapter13bankruptcy1.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Jun 8, 5:52 am, Mark Wooding <[EMAIL PROTECTED]> wrote: > By enforcing your `data hiding', you're effectively telling me that I'm > too stupid to make rational decisions of this sort. And that's actually > extremely insulting. 1) I suggest you not take it personally. 2) Local data within functions is hidden. Should you have access to that too? Are you insulted that you don't? 3) I have suggested that "indirect" or "back door" access could be provided to private data and methods via some sort of name mangling rule akin to the current rule for leading double underscores. This would provide access in a pinch, but it would make sure the client is aware that he or she or it is accessing private data (and it would do so without leading underscores). 4) My understanding is that most Python software is released or shipped as source code (or at least with the source code included). That means that the client would need only to remove my suggested "priv" keyword to gain access. Have you ever actually had to use Python software for which you had no access to the source code? -- http://mail.python.org/mailman/listinfo/python-list
Re: time.clock() or Windows bug?
Theo v. Werkhoven <[EMAIL PROTECTED]> wrote: > In this code I read out an instrument during a user determined period, > and save the relative time of the sample (since the start of the test) > and the readback value in a csv file. > > from datetime import * > from time import * > from visa import * > from random import * > [..] > for Reading in range(Readings): > RelTimeOfSample = "%.1f" % clock() > #PwrMtr.write("READ?") > #Sample = "%.3f" % float(PwrMtr.read()) > Sample = "%.3f" % (uniform(8.9,9.3))# Simulation of reading. > print "Sample %s, at %s seconds from start; Output power is: %s dBm" > % (Reading+1, RelTimeOfSample, Sample) > writer.writerow([RelTimeOfSample, Sample]) > ResultFile.flush() > sleep(6.6) > > Output: > Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm [snip] > Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm > Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm > Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm > Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm > Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm > Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm > Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm > Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm [snip] > But look at the timestamps of samples 21, 22 and 43. > What is causing this? > I've replaced the time.clock() with time.time(), and that seems to > solve the problem, but I would like to know if it's something I > misunderstand or if it's a problem with the platform (Windows Server > 2003) or the time.clock() function. time.clock() uses QueryPerformanceCounter under windows. There are some known problems with that (eg with Dual core AMD processors). See http://msdn.microsoft.com/en-us/library/ms644904.aspx And in particular On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. I would have said time.time is what you want to use anyway though because under unix time.clock() returns the elapsed CPU time which is not what you want at all! -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help porting Perl function
2008/6/7, kj <[EMAIL PROTECTED]>: > > > > ... The original Perl function takes a reference to an array, removes > from this array all the elements that satisfy a particular criterion, > > and returns the list consisting of the removed elements. ... > > > > Just out of curiosity, as I didn't find any mention of filter() in the suggestions in this thread, I'd like to ask, whether there are some reasons, why not to use it (or the itertools equivalent); actually it seems to me to be the simplest way to acomplish the mentioned task (as the solutions not modifying the original list were proposed too). e.g.: >>> lst=range(14) >>> odd = filter(lambda x: x % 2, lst) >>> even = filter(lambda x: not x % 2, lst) >>> lst, odd, even (or a version using itertools.ifilter, ifilterfalse) Are there maybe some significant performance disadvantages in the two subsequent implied loops over the input list? Regards, Vlastimil Brom -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
On Jun 8, 5:40 am, Mark Wooding <[EMAIL PROTECTED]> wrote: > Russ P. <[EMAIL PROTECTED]> wrote: > > The idea of being able to discern properties of an object by its name > > alone is something that is not normally done in programming in > > general. > > Really? You obviously haven't noticed Prolog, Smalltalk, Haskell, ML, > or Erlang then. And that's just the ones I can think of off the top of > my head. > > * Prolog and Erlang distinguish atoms from variables by the case of > the first letter; also `_' is magical and is equivalent to a new > variable name every time you use it. > > * Smalltalk distinguishes between global and local variables according > to the case of the first letter. > > * Haskell distinguishes between normal functions and constructors > (both data constructors and type constructors) by the case of the > first letter, and has Prolog's `_' convention. > > * ML allows a single-quote in variable names, but reserves names > beginning with a single-quote for type variables. It also has > Prolog's `_' convention. > > As far as I can see, discerning properties of a thing from its name > seems relatively common. Well, "common" in Prolog, Smalltalk, Haskell, ML, and Erlang is hardly common in general. I'll bet that Java and C/C++ are used more in North Dakota than all those languages combined are used in the entire world. That's not to say they aren't interesting academic languages, of course. As for using the case of the first letter to distinguish between local and global variables, is that just a naming convention or is it actually enforced by the compiler (or interpreter)? If it's actually enforced, that seems rather restrictive to me. What if I want to name a local variable after a proper name or an uppercase acronym? I guess I'm just out of luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get full path to script?
In <[EMAIL PROTECTED]> "Mark Tolonen" <[EMAIL PROTECTED]> writes: >import os >print os.path.abspath(__file__) Great. Thanks! Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help (TypeError: int argument required)
On Jun 8, 1:43 pm, Iain Adams <[EMAIL PROTECTED]> wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > line 56, in save > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? >From MySQLdb User's Guide (http://mysql-python.sourceforge.net/ MySQLdb.html): To perform a query, you first need a cursor, and then you can execute queries on it: c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price < %s""", (max_price,)) In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5". -- http://mail.python.org/mailman/listinfo/python-list
Re: time.clock() or Windows bug?
The carbonbased lifeform Nick Craig-Wood inspired comp.lang.python with: > Theo v. Werkhoven <[EMAIL PROTECTED]> wrote: >> Output: >> Sample 1, at 0.0 seconds from start; Output power is: 8.967 dBm > [snip] >> Sample 17, at 105.7 seconds from start; Output power is: 9.147 dBm >> Sample 18, at 112.4 seconds from start; Output power is: 9.284 dBm >> Sample 19, at 119.0 seconds from start; Output power is: 9.013 dBm >> Sample 20, at 125.6 seconds from start; Output power is: 8.952 dBm >> Sample 21, at 91852.8 seconds from start; Output power is: 9.102 dBm >> Sample 22, at 91862.7 seconds from start; Output power is: 9.289 dBm >> Sample 23, at 145.4 seconds from start; Output power is: 9.245 dBm >> Sample 24, at 152.0 seconds from start; Output power is: 8.936 dBm > [snip] >> But look at the timestamps of samples 21, 22 and 43. >> What is causing this? >> I've replaced the time.clock() with time.time(), and that seems to >> solve the problem, but I would like to know if it's something I >> misunderstand or if it's a problem with the platform (Windows Server >> 2003) or the time.clock() function. > > time.clock() uses QueryPerformanceCounter under windows. There are > some known problems with that (eg with Dual core AMD processors). > > See http://msdn.microsoft.com/en-us/library/ms644904.aspx > > And in particular > > On a multiprocessor computer, it should not matter which processor > is called. However, you can get different results on different > processors due to bugs in the basic input/output system (BIOS) or > the hardware abstraction layer (HAL). To specify processor > affinity for a thread, use the SetThreadAffinityMask function. Alright, that explains that then. > I would have said time.time is what you want to use anyway though > because under unix time.clock() returns the elapsed CPU time which is > not what you want at all! You're right, using fuctions that do not work cross platform isn't smart. Cheers for the explanation Nick Theo -- theo at van-werkhoven.nlICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" -- http://mail.python.org/mailman/listinfo/python-list
Q re documentation Python style
I'm a Perlhead trying to learn the Way of Python. I like Python overall, but every once in a while I find myself trying to figure out why Python does some things the way it does. At the moment I'm scratching my head over Python's docstrings. As far as I understand this is the standard way to document Python code. I think that's fine for simple functions, but I have some functions that require a very long docstring to document, and somehow I find it a bit disconcerting to stick a few screenfuls of text between the top line of a function definition and its body. I guess I'm still a lot more comfortable with Perl's POD, which allows more flexibility on the placement of the documentation relative to the source code. I expect that the reply to this quibble about very long docstrings will be something like: if your function requires several screenfuls of text to document, then it is too complex or it is doing too much; refactor it into a collection of simpler functions that will have shorter docstrings. Fair enough. In general I agree with this sentiment, except that I think that sometimes even simple functions require a lot of documentation. For example, I want to document a function that takes a dictionary as argument, and this dictionary is expected to have 5 keys. (When the number of mandatory arguments gets above 4, I find that it's too difficult to remember their order, so I resort to using a dictionary as the single argument.) The semantics for each of these keys needs to be described. Plus, of course, I need to describe what the function returns. That's a few screenfuls right there... I guess this is a rambling way to ask: are docstrings *it* as far Python documentation goes? Or is there a second, more flexible system? Then again, I suppose that Python's relative formal rigidity is considered by many to be a strength. Which means that, to be comfortable with Python, one has to learn to like this (relatively) rigid structure... But I thought I'd ask. :) Kynn -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
I guess this is a rambling way to ask: are docstrings *it* as far Python documentation goes? Or is there a second, more flexible system? Docstrings are it. Yet there are several ways how their content is interpreted. Google for example epydoc. You can embed links that way. I don't know perl, and even less it's documentation system. Yet I wonder: *where* do you put your function documentation, if not at the function? And if it is some sort of link (I guess it must be, or do you declare function docs totally unrelated to the functions themselves?), I have to say - I'd rather open the sourcefile and see what a function is about than having to manually follow links. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
On Sun, Jun 8, 2008 at 2:17 PM, kj <[EMAIL PROTECTED]> wrote: > > > I'm a Perlhead trying to learn the Way of Python. I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. At the moment > I'm scratching my head over Python's docstrings. As far as I > understand this is the standard way to document Python code. I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. I guess I'm > still a lot more comfortable with Perl's POD, which allows more > flexibility on the placement of the documentation relative to the > source code. > > I expect that the reply to this quibble about very long docstrings > will be something like: if your function requires several screenfuls > of text to document, then it is too complex or it is doing too > much; refactor it into a collection of simpler functions that will > have shorter docstrings. > > Fair enough. In general I agree with this sentiment, except that > I think that sometimes even simple functions require a lot of > documentation. For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) The semantics > for each of these keys needs to be described. Plus, of course, I > need to describe what the function returns. That's a few screenfuls > right there... > > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? > > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... > > But I thought I'd ask. :) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. > -- > http://mail.python.org/mailman/listinfo/python-list > If you use named parameters in your functions and methods, order is not so important... >>> def foo(a=None, b=None, c=None): ...print a,b,c ... >>> b(c=1, a=2, b=3) 2 3 1 -- Stand Fast, tjg. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow
On May 22, 7:14 pm, cm_gui <[EMAIL PROTECTED]> wrote: > Python is slow. Almost all of the web applications written in > Python are slow. Zope/Plone is slow, sloow, so very slooow. Even > Google Apps is not faster. Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. I do not have much experience on python but, php is %25 more faster than python in a simple iteration. -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
On Jun 8, 5:17 pm, kj <[EMAIL PROTECTED]> wrote: > I'm a Perlhead trying to learn the Way of Python. Welcome to the light, my son. > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? You can define a decorator to inject the docstring; at least the docstring will not come between the function line and the body. Define the decorator like this: def doc(docstring): def inject_doc(function): function.func_doc = docstring return function return inject_doc And then you could do this: @doc("This is the docstring.") def some_function(): do_whatever() I think most tools that use docstrings actually execute the module, which means by the time the tool sees it the docstring will have been assigned, though I'm not sure they all do. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
On Jun 9, 7:17 am, kj <[EMAIL PROTECTED]> wrote: [snip] > For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) Like myfunc({'strarg': 'foo', 'intarg': 42}) ?? So the start of this function would look something like this: def myfunc(dictarg): strarg = dictarg['strarg'] intarg = dictarg['intarg'] # the real work starts now Why not use keyword args? >>> def func(a1, a2): ...print 'a1=%r a2=%r' % (a1, a2) ... >>> func('foo', 42) a1='foo' a2=42 >>> func(a1='foo', a2=42) a1='foo' a2=42 >>> func(a2=42, a1='foo') a1='foo' a2=42 >>> Have you read this section in the Python tutorial: "4.7 More on Defining Functions" (http://docs.python.org/tut/ node6.html#SECTION00670) HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: sendKey
Gandalf wrote: I found some script that send keys , But I couldn't manage to send CTRL+c with none of them can any one tell me what i'm doing wrong: import win32api import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run("Notepad") win32api.Sleep(100) shell.AppActivate("Notepad") win32api.Sleep(100) shell.SendKeys("112435435") win32api.Sleep(100) shell.SendKeys("^a") # that wouldn't select all win32api.Sleep(100) shell.SendKeys("^c")# that wouldn't copy Works for me, using Vista and ActiveState Python 2.5.1.1. import SendKeys SendKeys.SendKeys("""^c""") Thank you! -- Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
kj wrote: ... I want to document a function that takes a dictionary as argument, and this dictionary is expected to have 5 keys. When the number of mandatory > arguments gets above 4, I find that it's too difficult to remember > their order, so I resort to using a dictionary as the single argument. Do you know you can call a function with mandatory args as keyword args? def f(value, scale, metrics, color, age, validity): print 'f', value, scale, metrics, color, age, validity ... f(23, age=6, scale=2.5, metrics=2, validity='strong', color='red') You can even use your arg dictionaries in transitional code: call_dict = {'value': 23, 'age': 6, 'scale': 2.5, 'metrics': 2, 'validity': 'strong', 'color': 'red'} f(**call_dict) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
On Jun 8, 10:17 pm, kj <[EMAIL PROTECTED]> wrote: > I'm a Perlhead trying to learn the Way of Python. I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. At the moment > I'm scratching my head over Python's docstrings. As far as I > understand this is the standard way to document Python code. I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. Hi Kynn, Strings on their own are also valid statements so if in Perl you might documentbefore the sub statement or even after the function definition then you could put extra information in a tripple quoted string statement before your function and put the bare essentials in the function itself. This would leave the def nearer the body of the function, but I don't know of anyone else that does this. - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
How to close app after x seconds.
Hi I have small app that I want to close tself after x seconds. Basically start show some message and close. I come up with something like this but it does not work. Can anyone help me with it? #!/usr/bin/env python import wx import time class MyFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) self.CreateStatusBar() self.SetStatusText("Some message here") class MyApp(wx.App): def OnInit(self): self.frame = MyFrame('TITLE', (100, 100), (400,100)) self.frame.Show() self.SetTopWindow(self.frame) self.ID_Timer = wx.NewEventType() self.timer = wx.Timer(self, self.ID_Timer) self.timer.Start(5000, False) self.Bind(wx.EVT_TIMER, self.appclose, self.timer) #wx.EVT_TIMER(self, self.ID_Timer, self.appclose) return True def appclose(self, evt): self.frame.Destroy() if __name__ == '__main__': app = MyApp(0) app.MainLoop() Ralph http://TheOrangeIT.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
Mensanator wrote: On Jun 8, 3:19�am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: "Mensanator" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | On Jun 7, 6:43?pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: | > zip(range(9,20), iterable) | | Oh, dear. You didn't actually try this, did you? Works fine in Py3, which is what I use now. You really ARE cruel to the newbies, aren't you? Don't you think it would have been appropriate to attach a large red label: WARNING! PY3! Heh heh, don't worry. Every time I see a range function, I immediately think "creates a list". Not sure how I got into that habit, but it happens every time! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
Sh4wn wrote: data hiding. I know member vars are private when you prefix them with 2 underscores, but I hate prefixing my vars, I'd rather add a keyword before it. Others touched on this, but I thought I'd throw it in here as well since I was just reading about this. Apparently the double underscore convention has nothing to do with data hiding. It's simply a mechanism for avoiding name clashes, and data hiding only *seems* to be a result of it. Not that that helps your situation any. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to close app after x seconds.
On Jun 8, 8:51 pm, ralphz <[EMAIL PROTECTED]> wrote: > Hi > > I have small app that I want to close tself after x seconds. Basically > start show some message and close. > > I come up with something like this but it does not work. Can anyone help > me with it? > > #!/usr/bin/env python > > import wx > import time > > class MyFrame(wx.Frame): > def __init__(self, title, pos, size): > wx.Frame.__init__(self, None, -1, title, pos, size) > self.CreateStatusBar() > self.SetStatusText("Some message here") > > class MyApp(wx.App): > def OnInit(self): > > self.frame = MyFrame('TITLE', (100, 100), (400,100)) > self.frame.Show() > > self.SetTopWindow(self.frame) > self.ID_Timer = wx.NewEventType() > self.timer = wx.Timer(self, self.ID_Timer) > self.timer.Start(5000, False) > self.Bind(wx.EVT_TIMER, self.appclose, self.timer) > #wx.EVT_TIMER(self, self.ID_Timer, self.appclose) > return True > > def appclose(self, evt): > self.frame.Destroy() > > if __name__ == '__main__': > app = MyApp(0) > app.MainLoop() > > Ralphhttp://TheOrangeIT.org It works for me just fine. How is it not working for you? By the way, showing your message in the statusbar is not a good display method--it's small and it is only seen in conjunction with a frame above it that is doing something. You could just put the message as staticText. -- http://mail.python.org/mailman/listinfo/python-list
Re: sendKey
Gandalf wrote: I found some script that send keys , But I couldn't manage to send CTRL+c with none of them can any one tell me what i'm doing wrong: import win32api import win32com.client shell = win32com.client.Dispatch("WScript.Shell") shell.Run("Notepad") win32api.Sleep(100) shell.AppActivate("Notepad") win32api.Sleep(100) shell.SendKeys("112435435") win32api.Sleep(100) shell.SendKeys("^a") # that wouldn't select all win32api.Sleep(100) shell.SendKeys("^c")# that wouldn't copy import SendKeys SendKeys.SendKeys("""^c""") Thank you! Your code didn't work for me, either. But shell.SendKeys("^a^c") works...go figure. -- http://mail.python.org/mailman/listinfo/python-list
deleting objects by finding all references and deleting?
Hi, I read in some earlier messages that an object in Python is only removed or freed from memory when all references to that object have been deleted. Is this so? If so, is there a way to get all of the references to an object, so that they may all be deleted, thus actually deleting the object? I have a very large python simulation, and I need to make sure that my object are deleted when I need them to be. I am experiencing some speed/memory issues (I create an approx. 75,000 complex objects). Thanks, Jake-- http://mail.python.org/mailman/listinfo/python-list
Re: Why does python not have a mechanism for data hiding?
"Well, "common" in Prolog, Smalltalk, Haskell, ML, and Erlang is hardly common in general. I'll bet that Java and C/C++ are used more in North Dakota than all those languages combined are used in the entire world." I would say python has more in common with the mentioned family than with the C or java families, although I guess it's more in between. Perl, PHP and Ruby all have significant variable names also. It is not that uncommon. 2) Local data within functions is hidden. Should you have access to that too? Are you insulted that you don't? Local data within functions is not hidden. Local data within functions vanish when the function completes. The ability for temporary data is important, and the convention of having functions be temporary keeps things sane. Not quite the same as what this discussion is about. All of the attributes of an object also vanish when the object does... 3) I have suggested that "indirect" or "back door" access could be provided to private data and methods via some sort of name mangling rule akin to the current rule for leading double underscores. This would provide access in a pinch, but it would make sure the client is aware that he or she or it is accessing private data (and it would do so without leading underscores). I honestly don't get the strong objection to leading underscores. They are a low-tech way of saying "don't touch", which won't muck about with very sticky implementation problems that private attributes would have, potential performance problems etc. They work NOW. Even if priv or some such is in the running to be added to python, it's going to be years. 4) My understanding is that most Python software is released or shipped as source code (or at least with the source code included). That means that the client would need only to remove my suggested "priv" keyword to gain access. Have you ever actually had to use Python software for which you had no access to the source code? So when someone releases an api doesn't match what I am doing 100%, I should fork the project? This doesn't seem to be a good solution for anybody. And it seems exceptionally dumb to do so just to go through and remove some keywords. -- http://mail.python.org/mailman/listinfo/python-list
Re: import cherrypy2
luca72 <[EMAIL PROTECTED]> wrote: > >No i haven't install lino > >but if frmp the python of this computer i make import cherrypy2 i >import it without problem this is the python path: It's quite possible that this other system has both CherryPy 2.x and CherryPy 3.x installed, and the admin wanted them both to be available at the same time. However, by default CherryPy always installs itself as "cherrypy" with no number. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: time.clock() or Windows bug?
Nick Craig-Wood <[EMAIL PROTECTED]> wrote: > >time.clock() uses QueryPerformanceCounter under windows. There are >some known problems with that (eg with Dual core AMD processors). > >See http://msdn.microsoft.com/en-us/library/ms644904.aspx > >And in particular > >On a multiprocessor computer, it should not matter which processor >is called. However, you can get different results on different >processors due to bugs in the basic input/output system (BIOS) or >the hardware abstraction layer (HAL). To specify processor >affinity for a thread, use the SetThreadAffinityMask function. That's an extremely arrogant statement on their part, because the fault here is entirely within Windows. Through Windows 2000, the operating system actually synchronized the cycle counters on the additional processors as they came out of reset at boot time. (The cycle counter is, after all, a writable register.) As a result, the cycle counters were rarely off by more than about 20 cycles. Beginning with XP, they stopped doing that. As a result, the cycle counters on multiprocessor machines can vary by millions or even tens of millions of cycles. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get full path to script?
On Jun 8, 12:52 pm, kj <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]> "Mark Tolonen" <[EMAIL PROTECTED]> writes: > > >import os > >print os.path.abspath(__file__) > > Great. Thanks! > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. Note that this doesn't quite work for symbolic links or compiled scripts, depending on your requirements. -- http://mail.python.org/mailman/listinfo/python-list
Re: Distributing applications that use 3rd party modules
On May 17, 11:42 am, eliben <[EMAIL PROTECTED]> wrote: > Hello, > > I'm getting into Python now after years of Perl, and as part of my > research I must understand how to do some common tasks I need. > > I have a bunch of Windows PCs at work to which I want to distribute an > application I've developed on my PC. All these PCs have Python 2.5 > installed. > > If my application contains only code I've developed, I simply zip its > directory with .py files and send it to everyone, who can then use it > by running the entry-point .py file. However, what if I've installed > some 3rd party modules on my PC, and my application uses them (for > example pyparsing, PiYAML and some others) ? I don't want to manually > install all these packages (there may be dozens of them) on all those > PCs (there may be dozens of those too). What is the best method I can > use ? Naturally, I want all the non-standard packages my app uses to > be detected automatically and collected into some kind of convenient > distributable that is easy to pass around and run. > > I'm aware of py2exe - tried it and it works fine. But it creates huge > executables, and I don't want to distribute those all the time. I much > prefer a zipped directory of .py scripts that takes some 10s of KBs. > > Thanks in advance, > Eli Hello, If anyone is interested, I've implemented such a utility - called libcollect.py, downloadable at: http://eli.thegreenplace.net/files/prog_code/libcollect.py.txt Here's its description from the embedded docstring: Motivation: Imagine that you've written a script that uses several libraries, some of which you've written and some you've downloaded and installed (for example PyYAML). You want to distribute the script to your friends and co- workers, who already have Python installed with all the standard library. But your script won't run on their machines, because they have neither your personal libraries, nor PyYAML installed. So what can you do ? * You can ask them to install PyYAML and other libraries your script uses, and send them your own libraries. This is a lengthy and inconvenient process. * You can use a tool like py2exe to package your delivery. This has a downside, however. py2exe produces large files (several MBs) and you may not want that. * You can painstakingly collect the libraries into a directory where your script can find them, and package the directory together with the script. LibCollect makes the third option trivial, by doing all the dirty work for you. Example: Suppose your script is named script.py, and is located in directory $DIR (although I'm using Unix-y notation here, it is for convenience only. LibCollect works similarly well on Windows platforms). Follow these steps to prepare a self-contained distribution with LibCollect: Create a distribution setup script in the same directory. Lets assume you call it distrib_script.py. You can easily place it in any directory you like, I'm using the same one to make the example simpler. Add the following to distrib_script.py (assuming that libcollect.py is in your sys.path): ** import libcollect # Create a LibCollect object lc = libcollect.LibCollect() # Prepare arguments for do_collect # # Path to the script (can be absolute or relative) scriptname = 'script.py' # Ask the resulting distribution to be placed in # directory distrib targetdir = 'distrib' # Specify which libraries to exclude from the # distribution (because you know they're installed # on the target machine) excludes = ["wx", "pywin", "win32api", "win32com"] # Zip the libraries used by the script to reduce # clutter and save space zip_lib = True # This does the actual work lc.do_collect( scriptname, targetdir, excludes, zip_lib=zip_lib) ** Now run distrib_script.py. When it finishes running, you will see that the distrib directory has been created in $DIR. In $DIR/distrib you will see two files, script.py and distlib.zip * script.py is a loader that replaces your original script.py - this is the program your users should run. All it does (look at the code, it's short!) is prepare the sys.path to include the packaged libraries, and runs your own script.py that was also packaged into the .zip file * distlib.zip is the distribution library, containing all the code your script needs to run on any machine with Python installed, and nothing else (except the modules you specified in the exclusion list). You may choose to pass on the zip file creation and leave your distribution library as a directory by providing False to the zip_lib argument of LibCollect.do_collect (take a look at its documentation, there are some other options there) How to use LibCollect: * It is most convenient to use LibCollect in the way demonstrated in the example above
Re: need help with timezone conversion (unexpected side effect of time.mktime ??)
Thanks Paul, I have identified the "problem" - because of daylight change this particular timesamp was observed twice in Europe/Sofia. Here is the GMT-to-local-time conversion: ++-+-+ | gmt_stamp | gmt_time| local_time | ++-+-+ | 1130631000 | 2005-10-30 00:10:00 | 2005-10-30 03:10:00 | ++-+-+ | 1130634600 | 2005-10-30 01:10:00 | 2005-10-30 03:10:00 | ++-+-+ | 1130638200 | 2005-10-30 02:10:00 | 2005-10-30 04:10:00 | ++-+-+ | 1130641800 | 2005-10-30 03:10:00 | 2005-10-30 05:10:00 | ++-+-+ When you do local-time-to-GMT conversion you can expect any of those two timestamps. I missed that initially :( (I was sure that local time has "one hour gap" and not "one hour of overlapping time") > and I'd recommend the datetime module for any serious work with dates and > times. Last time when I was playing with TZ conversions, I was not able to do anything using datetime module - it seems that one needs to define his own set of timezones (+ all the details) to get it working ... Am I wrong ? Can you show me how do accomplish the same conversion using datetime module ? Thanks again, Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Q re documentation Python style
On Jun 8, 2:17 pm, kj <[EMAIL PROTECTED]> wrote: > I'm a Perlhead trying to learn the Way of Python. I like Python > overall, but every once in a while I find myself trying to figure > out why Python does some things the way it does. At the moment > I'm scratching my head over Python's docstrings. As far as I > understand this is the standard way to document Python code. I > think that's fine for simple functions, but I have some functions > that require a very long docstring to document, and somehow I find > it a bit disconcerting to stick a few screenfuls of text between > the top line of a function definition and its body. I guess I'm > still a lot more comfortable with Perl's POD, which allows more > flexibility on the placement of the documentation relative to the > source code. > > I expect that the reply to this quibble about very long docstrings > will be something like: if your function requires several screenfuls > of text to document, then it is too complex or it is doing too > much; refactor it into a collection of simpler functions that will > have shorter docstrings. > > Fair enough. In general I agree with this sentiment, except that > I think that sometimes even simple functions require a lot of > documentation. For example, I want to document a function that > takes a dictionary as argument, and this dictionary is expected to > have 5 keys. (When the number of mandatory arguments gets above > 4, I find that it's too difficult to remember their order, so I > resort to using a dictionary as the single argument.) The semantics > for each of these keys needs to be described. Plus, of course, I > need to describe what the function returns. That's a few screenfuls > right there... > > I guess this is a rambling way to ask: are docstrings *it* as far > Python documentation goes? Or is there a second, more flexible > system? > > Then again, I suppose that Python's relative formal rigidity is > considered by many to be a strength. Which means that, to be > comfortable with Python, one has to learn to like this (relatively) > rigid structure... > > But I thought I'd ask. :) > > Kynn > > -- > NOTE: In my address everything before the first period is backwards; > and the last period, and everything after it, should be discarded. you can assign a documentation string to the function's .__doc__ attribute. This allows you to place your documentation lower in the script, or higher if you use an extra variable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help (TypeError: int argument required)
On Jun 8, 11:43 am, Iain Adams <[EMAIL PROTECTED]> wrote: > Hi, > > I am new to python. I have been having trouble using the MysqlDB. I > get an error pointing from the line > > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id = > %u", (self.title, self.text, self.id)) > > Here is the error: > > line 56, in save > cursor.execute("UPDATE article SET title = %s, text = %s WHERE id > = %u", (self.title, self.text, self.id)) > File "/var/lib/python-support/python2.5/MySQLdb/cursors.py", line > 151, in execute > query = query % db.literal(args) > TypeError: int argument required > > However when I print out type(self.id) I get . > > So surely I have provided an int argument. > > Any ideas anyone?? Change your u to an s and you'll be fine. If you want a specific format on the integer, format it first and pass in the string. -- http://mail.python.org/mailman/listinfo/python-list
Re: Do this as a list comprehension?
On Jun 8, 9:40 pm, John Salerno <[EMAIL PROTECTED]> wrote: > Mensanator wrote: > > On Jun 8, 3:19�am, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > >> "Mensanator" <[EMAIL PROTECTED]> wrote in message > > >>news:[EMAIL PROTECTED] > >> | On Jun 7, 6:43?pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote: > >> | > zip(range(9,20), iterable) > >> | > >> | Oh, dear. You didn't actually try this, did you? > > >> Works fine in Py3, which is what I use now. > > > You really ARE cruel to the newbies, aren't you? > > > Don't you think it would have been appropriate > > to attach a large red label: WARNING! PY3! > > Heh heh, don't worry. Every time I see a range function, I immediately > think "creates a list". Not sure how I got into that habit, but it > happens every time! :) You probably got into that habit because that's what it does in 2.x, create a list. Now, if you're expecting that to happen you'll in for a surprise when you switch to Py3, won't you? -- http://mail.python.org/mailman/listinfo/python-list