Re: getmtime differs between Py2.5 and Py2.4
>> that you are mistaken: There is NO difference between the outcome >> of os.path.getmtime between Py2.5 and Py2.4. It always did return >> UTC, and always will. > > Different results are indeed obtained, as others have demonstrated > (other than the irrelevant float/int distinction). The following C > sample program illustrates: Right. However, contrary to what the OP claimed, 2.4 does *not* return local time - it still returns UTC. It may just return "a different" UTC. > A key fact here, I believe, is that in February (when temp.txt was > last modified), my local time was UTC-11. I expect this is the > suffering that your comment in posixmodule.c refers to (it looks to me > like Python 2.5 is correct). In case there was any doubt: your tests show that 2.4 does not return local time. The output of dir matches the results of the time.ctime output, that must meant that the ctime input was UTC. Now, that there is a one-hour difference is an inherent problem with the FAT file system (so I assume you use FAT on your disk drive). FAT has an inherent problem with UTC file stamps, as the time stamps are stored in local time. So if you have an old time, you can only interpret it in a meaningful way by assuming that the machine was in the same time zone when the file was created as it is now. The the DST issue come in: should one assume that the DST switched since when the time stamp was created; depending on what you assume here, a one-hour difference will occur. IIRC (and I clearly didn't at the beginning of the thread): The MS CRT tries to adjust time stamps because of these problems, but does so incorrectly. In particular, it adjusts time stamps on NTFS volumes as well, which *are* in UTC. So even though the system reports the correct time stamp, the CRT will return the wrong one. Python 2.5 fixes this, bypassing the CRT. So yes: the time stamps returned in 2.4 and 2.5 may differ. But still: they were always UTC, and always will be. It's just that 2.4 had a bug which 2.5 has fixed. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: getmtime differs between Py2.5 and Py2.4
> the difference (rounding to an int number of seconds) is just about one > hour; in certain parts of the world (Europe and Africa), that could > indeed be a timezone issue. With the help of Tony Meyer, we rediscovered the explanation: because of a bug in the Microsoft C run-time library, the UTC time reported by 2.4 may have been off by one hour (it wasn't local time - just off by one hour). This was due to DST issues. They have been fixed in 2.5, which now reports the correct UTC value. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, subprocess.Popen & encodage
> But, I don't found anything, in any documentations, on this. > > Sombody can confirm? Am I misled? Am I right? You are right, and you are misled. The encoding of the data that you get from Popen.read is not under the control of Python: i.e. not only you don't know, but Python doesn't know, either. The operating system simply has no mechanism of indicating what encoding is used on a pipe. So different processes may chose different encodings. Some may produce UTF-16, others may produce CP-850, yet others UTF-8, and so on. There really is no way to tell other than reading the documentation *of the program you run*, and, failing that, reading the source code of the program you run. On Windows, many programs will indeed use one of the two system code pages, or UTF-16. It's true that UTF-16 can be quite reliably detected by looking at the first two bytes. However, the two system code pages (OEM CP and ANSI CP) are not so easy to tell apart. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, subprocess.Popen & encodage
Thank you. -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Getting a function name from string
" It has been my experience that, more often than not, any time you think you want to evaluate strings, you don't need to. For instance, instead of passing around the name of the function as a string: s = "someFunction" eval(s)() you can pass around the function as an object: s = someFunction # note the lack of brackets s() -- Steven. " I want to read a module name and a function in that module from a ini-file and then run the function with some arguments also read from the ini-file. Is there a way to do this, still avoiding the eval()-method? example: module = modelParser.getModule() function = modelParser.getFunc() parms = modelParser.getParms() (modelParser just extracts string from the ini-file) I now have 'module' and 'function' as strings and 'parms' normally as a list of strings. I can import the module by __import__(module) but is there another way to call: module.function(parms) than using eval()? Thanks for any suggestions, Best Cesar -- http://mail.python.org/mailman/listinfo/python-list
Re: change of random state when pyc created??
On Tue, 08 May 2007 02:12:27 +, Alan Isaac wrote: > "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in > message > news:[EMAIL PROTECTED] >> If you want to send me the modules, I will have a look at them as well. >> Many eyes make for shallow bugs... > > Dustan and John Machin have confirmed the apparent bug, and I have sent > you the files. Explanation welcome!! My testing suggests the bug is *not* to do with pyc files at all. I'm getting different results when running the files, even when the directory is read-only (and therefore no pyc files can be created). My results suggest that setting the seed to the same value does NOT give identical results, *even though* the random number generator is giving the same results. So I think we can discount the issue being anything to do with either the .pyc files or the random number generator. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Download FireFox with the New Google Toolbar
http://www.mysearchenginewatch.com/ - Bookmark us for your search needs and keep informed on all the new occurances in the Search Industry Updated Daily. Try the new Google Firefox with Google PageRank toolbar. -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you implement a reactor without a select?
On 2007-05-08, Michele Simionato <[EMAIL PROTECTED]> wrote: > On May 8, 4:53 am, [EMAIL PROTECTED] (Alex Martelli) wrote: >> What do you expect from "timers on Linux" that you could not get with a >> simple "sleep for the next N milliseconds"? A timer (on Linux or >> elsewhere) can jog your process N milliseconds from now, e.g. with a >> SIGALRM or SIGPROF, and you can set one with the setitimer syscall >> (presumably accessible via ctypes, worst case -- I've never used it from >> Python, yet), but how would that help you (compared to plain sleep, >> select, poll, or whatever else best fits your need)? > > I hoped there was a library such thay I could register a Python > callable (say > a thunk) and having it called by the linux timer at time t without > blocking I once played with the following module to do something similar. Maybe it is usefull to you as is, or can give you an idea on how to proceed. I only tested it on linux. alarm.py m signal import signal, SIG_IGN, SIGALRM from time import time from thread import allocate_lock from heapq import heappush, heappop from os import kill, getpid import errno from select import select, error as SelectException from ctypes import * libc = cdll.LoadLibrary("/lib/libc.so.6") class _timeval(Structure): _fields_ = [("tv_sec" , c_long), ("tv_usec", c_long)] def timeval(tm): sec = int(tm) usec = int(100 * (tm - sec)) return _timeval(sec, usec) class itimerval(Structure): _fields_ = [("it_interval", _timeval), ("it_value", _timeval)] def alarm(tm): tv = timeval(tm) ti = timeval(0.0) ntv = itimerval(ti, tv) otv = itimerval(timeval(0.0), timeval(0.0)) rt = libc.setitimer(0, byref(ntv), byref(otv)) #print otv.it_value.tv_sec , otv.it_value.tv_usec if rt: raise ValueError else: return otv.it_value.tv_sec + otv.it_value.tv_usec / 100.0 def sleep(tm): wakeup = time() + tm while tm >= 0: try: select([],[],[],tm) except SelectException , Err_Info: #print dir(Err_Info) if Err_Info[0] != errno.EINTR: raise tm = wakeup - time() alarms = [] alarm_lock = allocate_lock() def AlarmHandler(sgnr, frame): alarm_lock.acquire() now = time() while alarms and alarms[0].moment <= now: current = heappop(alarms) if not current.canceled: current.func(*current.args, **current.kwds) current.executed = True now = time() alarm_lock.release() if alarms: #print alarms[0].moment - now, alarms alarm(alarms[0].moment - now) signal(SIGALRM, AlarmHandler) class Alarm(object): def __init__(self, tp, func, *args, **kwds): alarm(0) try: alarm_lock.acquire() self.canceled = False self.executed = False self.func = func self.args = args self.kwds = kwds self.moment = tp heappush(alarms, self) now = time() delta = alarms[0].moment - now #print alarms finally: alarm_lock.release() if delta <= 0: pass kill(getpid(), SIGALRM) else: alarm(delta) def __cmp__(self, other): return cmp(self.moment, other.moment) def __str__(self): return "" % self.moment __repr__ = __str__ def Cancel(self): try: alarm_lock.acquire() if self.executed: raise ValueError, "Cancelation was too late" else: self.canceled = True except: alarm_lock.release() --- You use it as follows: from alarm import Alarm alert = Alarm(exucutemoment, function, positionalarguments, keywordarguments) # unless alert.Cancel is called before the alert went off, the function # with its arguments will be called at the specified time. # If you are using threads, you are advised to do most of the work in a # different thread and leave the main thread to only treat the alarms. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simulating simple electric circuits
In article <[EMAIL PROTECTED]>, Bjoern Schliessmann <[EMAIL PROTECTED]> wrote: > Hello all, > > I'm trying to simulate simple electric logic (asynchronous) > circuits. By "simple" I mean that I only want to know if I > have "current" or "no current" (it's quite digital) and the only > elements need to be (with some level of abstraction to my specific > problem) > > - sources (here begin currents) > - ground (here end currents) > - joints > - switches (which are able to let current pass or not, depending on > outside influence) > - loads (which can signal change in current flow to the outside -- > just like a light bulb) Are you trying to do logic simulation (digital) or analog circuit simulation? The only reason I ask is that the simulation techniques are very different, and you used both "logic" and "current" in your description, so I'm not quite sure which direction you are heading. For analog: If you are ignoring time related effects (no inductance or capacitance), then the system is solvable as a set of linear equations. Basically your circuit consists of a set of nodes and edges. Wires are edges, joints are nodes. An open switch is nothing, a closed switch is an edge. A load is an edge. You'll have to assign resistances to the edges (anything non-zero will do) in order for the equations to make sense. Then you can use Kirchoff's laws to analyze the circuit and construct the equations to solve. A good linear algebra library (numpy) will help in solving the equations. Opening or closing a switch would result in a new set of equations, and thus a new solution. You might be able to get clever and model open switches as edges with infinite resistance, which would allow you to skip the Kirchoff stuff each time a switch is flipped. You'd only have to change coefficients and solve the system of equations. However, the system of equations would be singular, so you'd have to do something like an SVD rather than an inverse. I don't want to go into too much more detail about this one because I have a hunch you are really looking at digital, but if you're interested in the analog approach let me know and I'll fill in more of the details. For digital: Event based simulation is typical here. These simulations generally are concerned with voltage, not current. A circuit consists of signals and devices. At any given time, each signal has a certain state (high/low, on/off, 9 level logic, whatever). Devices are connected to one another by signals. You'll also need events (a signal, a time, and a new state), and an event queue (events sorted by time). This is easier if each signal is driven by at most one device: 1) pop the next event off the queue 2) if the event's signal's state is the same as the new state, go to 1 3) set the event's signal's state to the new state 4) for each device that is attached to the signal, run the device's code, which should look at all of its inputs, and post new events to the queue for any outputs (do this even if the computed output is the same as the current output). These events are usually posted for some time in the future (1 simulation 'tick' is fine). 5) go to 1 This approach is pretty simple to do in Python. I wrote a sample digital simulator a while back and the core of the simulator was around 50 lines of code. Rounded out with some basic logic gates and helper functions to probe the simulation, it was around 150 lines. It was only 2 level logic and signals could only be driven by a single device. The devices that you want to model (switches, loads, etc) don't have explicit inputs and outputs, and you'll need to deal with a signal being driven from multiple sources, so it will get a bit more complicated. You will probably also need 9 level logic (or something equivalent) to deal with the fact that ground beats a source through a load when determining a node's state. The basic idea is that each signal has multiple drivers, each of which has an internal state. When a device wants to set an output, it only changes its driver's state. The signal then has code that looks at the state of all drivers and combines them in some way (this is called a resolution function). That combined state is what devices see when they read the signal. It isn't *that* complicated to implement, but if you can turn your problem into one with 2 level logic and no multiple drivers, then it will be easier to write and debug. Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: how do you implement a reactor without a select?
On May 8, 11:23 am, Antoon Pardon <[EMAIL PROTECTED]> wrote: > I once played with the following module to do something similar. That looks interesting, I will have a look at it. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Binding
Hello, I've basically had plans on just extending python for the wrapper. That basically works fine, i just don't get along by the types provided (http://docs.python.org/ext/ext.html). Anyway, i want to extend python for types. The problem i currently experience is the following. Guess what - i have a base class, doing some wrapping. Currently, called pybtest (just testing around though). Now, i'd need a configuration object, accessable in python. By using the library, it should be possible to access it using pybtest.config.insertValue('xyz') as an example, but i havn't found any way to archive this yet. If i write config as an own (external) type, i can't get it into the pybtest object for some reason. It's compiled as an extra "config.so", and with the test script i need to do import config. Anyway, it's not in the pybtest object., i've to build up a config and pass it by to the pybtest binding, so it can set it's internal configuration structures. If i try to compile it within the pybtest, i can't use ext_modules, and as expected, i can't do another pybtestinit function, so it's quite useless, at least with the knowledge i could get out of the documentation. By just making a include file of the type, including the type definition adding up some functions to pybtest, i actually can access it, without the wanted functionality of pybtest.config. Why do you all suggest other things than the way suggested by python? I havn't got a real problem writing the code in C, actually, it looked as if it would give me several possibilities i wouldn't have with pyrex (like binding more library functions to one provided python function and so on). I havn't had a closer look to SWIG yet. It looks as if i could just provide single objects or modules, and no additional object into a module. Does anyone have closer knowledge on this? Btw: Sorry for the long delay time, i had to describe the things closer, and had to take a deeper look into the bindings than i had before. Kind regards, Georg -- http://mail.python.org/mailman/listinfo/python-list
Re: Specification for win32com.client package
Peter Fischer wrote: > Hello, (sorry, the first message bounced; because it is urgent and I wait > since > yesterday, here it's again): > > > I am searching for documentation about the interface the win32com > package > provides, especially win32com.client. I searched the web and Mark Hammond’s > homepage but only found example code using Dispatch() and DispatchEx() etc. > Isn’t there a full list of the functions win32.com.client provides? Or do I > have to > use makepy to somehow generate documentation (how)? > I would be thankful if someone could give me a hook about that. > > Best regards,Peter. I'm afraid you're pretty much out of luck on full documentation, Peter. Mark Hammond & Andy Robinson's book (of several years ago) is still being published: http://www.amazon.com/exec/obidos/tg/detail/-/1565926218?v=glance and certainly contains quite a bit of information on the subject. The .chm which comes with the pywin32 extensions has some information (although not much). Examples from the python-win32 list and this mailing list plus examples from around the web, plus finally the source code itself are pretty much staple fare for people working in the Win32 area under Python. Obviously, what it needs is someone or someones with the energy to get that Python Win32 wiki underway, but at the moment all my energies are devoted elsewhere, I'm afraid. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Can Python Parse an MS SQL Trace?
[EMAIL PROTECTED] wrote: > On May 7, 8:34 am, Tim Golden <[EMAIL PROTECTED]> wrote: >> [EMAIL PROTECTED] wrote: >>> Can Python parse a trace file created with MS SQL's profiler? There >>> are a few thousand lines in the trace file and I need to find the >>> insert statements and the stored procedures. Unfortunately, I am not >>> an SQL guru and was hoping Python could help. >>> Mike >> Mike, >> >> Can I suggest that, since the answer is more to >> do with parsing and less to do with MSSQL (which >> simply generated the output) that you post an example >> of a trace file to some web location to see if anyone >> wants to pick up the challenge? >> >> I'm not at work so I don't have access to MSSQL, but >> I seem to remember that you can output/save as XML, >> which may make things easier (or at least interest a >> different group of people in having a look). >> >> I'm quite certain it can by done by Python; I did >> consider it myself a couple of months back, but my >> colleague spotted the problem before I'd really got >> into the code! >> >> TJG > > Good point. Unfortunately, I think our SQL Server must be too old for > xml (we have version 8). The only save options I see is Trace > Template, Trace File, Trace Table and SQL Script. Yes, you're right; I have clients installed for SQL 2000 & 2005 and it's only under 2005 that I have the XML output option. The .trc file format is pretty much opaque binary, and the .sql output only gives you the SQL statements issued - not the events they're associated with. One obvious way is to save it to a table and to interrogate that table. I find that kind of thing a bit cumbersome, but if XML's not an option, it might be the only way. (FWIW, I find XML cumbersome too, but that might just be lack of practice ;) Running a standard trace and saving to a table, this is the structure which resulted: CREATE TABLE [trace_output] ( [RowNumber] [int] IDENTITY (1, 1) NOT NULL , [EventClass] [int] NULL , [TextData] [ntext] COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [NTUserName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [ClientProcessID] [int] NULL , [ApplicationName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [LoginName] [nvarchar] (128) COLLATE SQL_Latin1_General_CP1_CS_AS NULL , [SPID] [int] NULL , [Duration] [bigint] NULL , [StartTime] [datetime] NULL , [Reads] [bigint] NULL , [Writes] [bigint] NULL , [CPU] [int] NULL , PRIMARY KEY CLUSTERED ( [RowNumber] ) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO Seems like you might be able to do something with it. (Possibly just dumping it straight back out to CSV or XML if that's easier for you than db querying) TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: msbin to ieee
On 7 mai, 23:38, John Machin <[EMAIL PROTECTED]> wrote: > On May 7, 11:37 pm, revuesbio <[EMAIL PROTECTED]> wrote: > > > > > On 7 mai, 14:56, John Machin <[EMAIL PROTECTED]> wrote: > > > > On May 7, 10:00 pm, revuesbio <[EMAIL PROTECTED]> wrote: > > > > > On 7 mai, 13:21, John Machin <[EMAIL PROTECTED]> wrote: > > > > > > On May 7, 6:18 pm, revuesbio <[EMAIL PROTECTED]> wrote: > > > > > > > On 7 mai, 03:52, John Machin <[EMAIL PROTECTED]> wrote: > > > > > > > > On May 7, 7:44 am, revuesbio <[EMAIL PROTECTED]> wrote: > > > > > > > > > Hi > > > > > > > > Does anyone have the python version of the conversion from > > > > > > > > msbin to > > > > > > > > ieee? > > > > > > > > Thank u > > > > > > > > Yes, Google has it. Google is your friend. Ask Google. It will > > > > > > > lead > > > > > > > you to such as: > > > > > > > >http://mail.python.org/pipermail/python-list/2005-August/337817.html > > > > > > > > HTH, > > > > > > > John > > > > > > > Thank you, > > > > > > > I've already read it but the problem is always present. this script > > > > > > is > > > > > > for double precision MBF format ( 8 bytes). > > > > > > It would have been somewhat more helpful had you said what you had > > > > > done so far, even posted your code ... > > > > > > > I try to adapt this script for single precision MBF format ( 4 > > > > > > bytes) > > > > > > but i don't find the right float value. > > > > > > > for example : 'P\xad\x02\x95' will return '0.00024924660101532936' > > > > > > If you know what the *correct* value is, you might like to consider > > > > > shifting left by log2(correct_value/erroneous_value) :-) > > > > > > Do you have any known correct pairs of (mbf4 string, decimal_float > > > > > value)? My attempt is below -- this is based on a couple of > > > > > descriptive sources that my friend Google found, with no test data. I > > > > > believe the correct answer for the above input is 1070506.0 i.e. you > > > > > are out by a factor of 2 ** 32 > > > > > > def mbf4_as_float(s): > > > > > m0, m1, m2, m3 = [ord(c) for c in s] > > > > > exponent = m3 > > > > > if not exponent: > > > > > return 0.0 > > > > > sign = m2 & 0x80 > > > > > m2 |= 0x80 > > > > > mant = (((m2 << 8) | m1) << 8) | m0 > > > > > adj = 24 + 128 > > > > > num = mant * 2.0 ** (exponent - adj) > > > > > if sign: > > > > > return -num > > > > > return num > > > > > > HTH, > > > > > John > > > > > well done ! it's exactly what i'm waiting for !! > > > > > my code was:>>> from struct import * > > > > >>> x = list(unpack('','P\xad\x02\x95')) > > > > >>> x > > > > [80, 173, 2, 149] > > > > >>> def conversion1(bytes): > > > > > b=bytes[:] > > > > sign = bytes[-2] & 0x80 > > > > b[-2] |= 0x80 > > > > exp = bytes[-1] - 0x80 - 56 > > > > acc = 0L > > > > for i,byte in enumerate(b[:-1]): > > > > acc |= (long(byte)<<(i*8)) > > > > return (float(acc)*2.0**exp)*((1.,-1.)[sign!=0]) > > > > Apart from the 2**32 problem, the above doesn't handle *any* of the > > > 2**24 different representations of zero. Try feeding \0\0\0\0' to it > > > and see what you get. > > > > > >>> conversion1(x) > > > > > 0.00024924660101532936 > > > > > this script come from google groups but i don't understand bit-string > > > > manipulation (I'm a newbie). informations about bit-string > > > > manipulation with python is too poor on the net. > > > > The basic operations (and, or, exclusive-or, shift) are not specific > > > to any language. Several languages share the same notation (& | ^ << > > > > >>), having inherited it from C. > > > > > thank you very much for your script. > > > > Don't thank me, publish some known correct pairs of values so that we > > > can verify that it's not just accidentally correct for 1 pair of > > > values. > > > pairs of values : > > (bytes string, mbf4_as_float(s) result)right > > float value > > ('P\xad\x02\x95', 1070506.0) > > 1070506.0 > > ('\x00\x00\x00\x02', 5.8774717541114375e-039) 0.0 > > There is no way that \x00\x00\x00\x02' could represent exactly zero. > What makes you think it does? Rounding? > > > ('\x00\x00\x00\x81', 1.0) > > 1.0 > > ('\x00\x00\x00\x82', 2.0) > > 2.0 > > ('[EMAIL PROTECTED]', 3.0) > > 3.0 > > ('\x00\x00\x00\x83', 4.0) > > 4.0 > > ('\x00\x00 \x83', 5.0) > > 5.0 > > ('\xcd\xcc\x0c\x81', 1.100238418579) 1.1 > > ('\xcd\xcc\x0c\x82', 2.200476837158) 2.2 > > ('33S\x82', 3.299523162842) 3.3 > > ('\xcd\xcc\x0c\x83', 4.400953674316) 4.4 > > It is not apparent whether you regard the output from the function as > correct or not. > > 4.4 "converted" to mbf4 format is '\xcd\xcc\x0c\x83' which is > 4.400953674316 which is the closest possible mbf4 representation > of 4.4 (difference is 9.5e-008). > > The next lower mbf4 value '\xcc\xcc\x0c\x83' is 4.396185302734 > (difference is -3.8e-007). > > Note that floating-point representation of m
Designing a graph study program
I'm studying some graphs algorithm (minumum spanning tree, breath search first topological sort etc etc...) and to understand better the theory I'm implementing them with python... I made my own graph class, the constructor is simply this: class graph: "in forma di matrice e' una matrice normale, in forma di lista uso un dizionario" def __init__(self,nodes,edges,dir=False,weight=[]): # inizializzatore dell'oggetto, di default in forma di lista di adiacenza e undirected # il grafo puo' essere anche pesato "di default uso la lista di adiacenza per rappresentare il grafo, usare set" self.adj_list = {} self.nodes = nodes self.edges = edges # in modo da avere comodi questi dati, se bidirezionale non ci sono tutti self.weight = weight self.dir = dir # anche questo deve essere raggiungibile for n in nodes: self.adj_list[n] = [] for n in nodes: for e in edges: if dir: # se ho la direzione guardo l'ordine dei vertici nel lato if n == e[0]: self.adj_list[n].append(e[1]) elif n in e: other = e[((e.index(n))+1) % 2] self.adj_list[n].append(other) if weight: self.w = {} for idx in range(len(edges)): self.w[edges[idx]] = weight[idx] # assegno in corrispondenza Well then I wanted to draw graphs and I found that pydot is working really nicely. BUT I'd like to do this, an interactive program to see ho the algorithms works... For example in the breath search first, every time the algorithm colors a node, the program should redraw the graphs. Which modules should I use for graphics (I use macosX and I'd like something cross platforms). Now I'm doing something like this def draw_graph(self): """disegna un grafo con pydot""" import os output = 'graph.png' self.dot_graph.write_png(output) com = 'open '+output os.popen(com) which I think is very ugly and not fitting very well for my purpose. I also created a class to represent matrix (for the matrix view of the graph) but I found that numpy has a very complete implementation, I think I'll go with it. Thank you very much, if you have any kind of suggestions/links please write it :) -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting exercise
sherry wrote: > On May 8, 9:31 am, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: >> On Mon, 07 May 2007 20:45:52 -0700, Michael Tobis wrote: >>> I have a reasonably elegant solution but it's a bit verbose (a couple >>> dozen lines which I'll post later if there is interest). Is there some >>> clever Pythonism I didn't spot? >> Peering into my crystal ball, I see that your algorithm does the wrong >> thing, and contains bugs too. You certainly don't need to partion the >> sequence into three sub-sequences, or do that trick with the metaclass, >> and it is more efficient to use list.extend() than sum. >> >> Hang on... stupid crystal ball... that's somebody else's code. Maybe you >> should just post your code here, so we can look at it? >> >> In the meantime, here's a simple generator to do permutations with >> repetition: >> >> def permute_with_repetitions(seq): >> if len(seq) <= 1: >> yield list(seq) >> else: >> for i, item in enumerate(seq): >> for tail in permute_with_repetitions(seq[:i] + seq[i+1:]): >> yield [item] + tail >> >> It doesn't do a test for the sequence containing duplicates, and I leave >> it as anexerciseto do selections of fewer items. >> >> -- >> Steven. > > Dear Steven > I ran into your message quite accidentally while researching about > some details on 'Exercise' and thought of sharing some of my > findings. > I've read at 'http://www.medical-health-care-information.com/Health- > living/exercise/index.asp > that Swimming, cycling, jogging, skiing, aerobic dancing, walking or > any of dozens of other activities can help your heart. Whether it's > included in a structured exercise program or just part of your daily > routine, all physical activity adds up to a healthier heart. > I hope the above is of some help to you as well. Regards, Sherrybove. > This takes annoying past annoying to some new level of hell to which even satan himself wouldn't venture. -- http://mail.python.org/mailman/listinfo/python-list
File Name Format
Greetings, How do I convert programmatically the file names from WIN32 to UNIX format? A code snippet would be of great help. We are new to python! :) Thanks. Best regards, Anand -- http://mail.python.org/mailman/listinfo/python-list
Re: File Name Format
Anand wrote: > Greetings, > > How do I convert programmatically the file names from WIN32 to UNIX > format? > > A code snippet would be of great help. > We are new to python! :) unix_name = win_name.replace("\\", "/") But this of course won't work for anything that starts with a drive letter for example. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: File Name Format
One thing you could do is to create assign dir for c drive d drive etc as /c , /d etc then this would work unix_name = win_name.replace("\\","/").replace("c:","/c").replace("d:","/d") On 5/8/07, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: Anand wrote: > Greetings, > > How do I convert programmatically the file names from WIN32 to UNIX > format? > > A code snippet would be of great help. > We are new to python! :) unix_name = win_name.replace("\\", "/") But this of course won't work for anything that starts with a drive letter for example. Diez -- http://mail.python.org/mailman/listinfo/python-list -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -- http://mail.python.org/mailman/listinfo/python-list
Re: long lists
On May 7, 10:21 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Mon, 07 May 2007 09:14:34 -0300, Merrigan <[EMAIL PROTECTED]> > escribió: > > > The Script it available at this url : > >http://www.lewendewoord.co.za/theScript.py > > I understand this as a learning exercise, since there are lot of utilities > for remote syncing. > > Some comments: > - use os.path.join to build file paths, instead of concatenating strings. > - instead of reassigning sys.stdout before the call to retrlines, use the > callback: > > saveinfo = sys.stdout > fsock = open(tempDir + "remotelist.txt", "a") > sys.stdout = fsock > ftpconn.cwd(remotedir) #This changes to the remote directory > ftpconn.retrlines("LIST") #This gets a complete list of everything in > the directory > sys.stdout = saveinfo > fsock.close() > > becomes: > > fsock = open(os.path.join(tempDir,"remotelist.txt"), "a") > ftpconn.cwd(remotedir) #This changes to the remote directory > ftpconn.retrlines("LIST", fsock.write) #This gets a complete list of > everything in the directory > fsock.close() > (Why mode="a"? Shouldn't it be "w"? Isn't the listing for a single > directory?) > > - Saving both file lists may be useful, but why do you read them again? If > you already have a list of local filenames and remote filenames, why read > them from the saved copy? > - It's very confusing having "filenames" ending with "\n" - strip that as > you read it. You can use fname = fname.rstrip() > - If you are interested on filenames with a certain extension, only > process those files. That is, filter them *before* the processing begins. > > - The time-consuming part appears to be this: > > def comp_are(): > global toup > temptoup = [] > for file1 in remotefiles: > a = file1 > for file2 in localfiles: > b = file2 > if str(a) == str(b): > pass > if str(b) != str(a): > temptoup.append(str(str(b))) > toup = list(sets.Set(temptoup)) > for filename in remotefiles: > fn2up = filename > for item in toup: > if fn2up == item: > toup.remove(item) > else: > pass > toup.sort() > > (It's mostly nonsense... what do you expect from str(str(b)) different > from str(b)? and the next line is just a waste of time, can you see why?) > I think you want to compare two lists of filenames, and keep the elements > that are on one "localfiles" list but not on the other. As you appear to > know about sets: it's the set difference between "localfiles" and > "remotefiles". Keeping the same "globalish" thing: > > def comp_are(): > global toup > toup = list(sets.Set(localfiles) - sets.Set(remotefiles)) > toup.sort() > > Since Python 2.4, set is a builtin type, and you have sorted(), so you > could write: > > def comp_are(): > global toup > toup = sorted(set(localfiles) - set(remotefiles)) > > - Functions may have parameters and return useful things :) > That is, you may write, by example: > >remotefiles = getRemoteFiles(host, remotedir) >localfiles = getLocalFiles(localdir) >newfiles = findNewFiles(localfiles, remotefiles) >uploadFiles(host, newfiles) > > -- > Gabriel Genellina Hmmm, thanks a lot. This has really been helpful. I have tried putting it in the set, and whoops, it workes. Now, I think I need to start learning some more. now the script is running a lot slower... Now to get the rest of it up and running... Thanx for the help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie prob: How to write a file with 3 threads?
On May 8, 2:13 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On 7 May 2007 18:22:07 -0700, est <[EMAIL PROTECTED]> declaimed > the following in comp.lang.python: > > > > > I guess I will write multiple files, one thread one file, and after > > all threads terminates, I combine the files. That's a cheaper > > solution, I think. > > Given your first description: > > > I need to write a file using 3 threads simutaniously, e.g. Thread 1 > > write the first byte of test.bin with an "a", second thread write the > > second byte "b", third thread write the third byte "c". Anyone could > > give a little example on how to do that? > > ... any other solution may not have worked anyway. That is, if you > really expect the three threads to interleave their output as > abcabcabcabc. If threading, you have no assurance that any single thread > will follow any other during a task switch. It all depends upon where a > task switch takes place. > > But then, your example isn't too clear of what you really are > producing for output. If, instead of "bytes", you meant that each thread > was writing logging information, the solution would be to use the > logging module -- so far as I know, the logging module /does/ perform > the needed access locking. > > OTOH, if you really mean to have three separate byte producers, > interleaving output, the only safe way would be to have /each/ have an > output Queue, and a fourth thread doing the writing using a loop of the > form: > > while True: > a = aQueue.get() > fout.write(a) > b = bQueue.get() > fout.write(b) > c = cQueue.get() > fout.write(c) > > Using the separate queues means that the writer WILL wait until the > next producer in the interleave has produced its data. Of course, this > structure has the drawback that all producers must produce the same > amount of data -- otherwise it blocks forever on the queue from the > producer has stopped generating data. > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ I'd like to say VERY VERY VERY thank you for your detailed information, that's a lot encourage for a beginner. In fact I am writing a multi thread download ultility, and I found that very hard for me. Can you recommand any sample code where I can start with? I hope I can catch up with everyone here, I'll try my best learning python. Thank you again. -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
> > Well then I wanted to draw graphs and I found that pydot is working > really nicely. > BUT I'd like to do this, an interactive program to see ho the > algorithms works... > For example in the breath search first, every time the algorithm > colors a node, the program should redraw the graphs. Which modules > should I use for graphics (I use macosX and I'd like something cross > platforms). Use the bundled Tkinter. I've implemented a similar thing back in my under graduation days using TCL/Tk, and Tk is perfectly suited for that task. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
On 8 Mag, 13:02, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > Well then I wanted to draw graphs and I found that pydot is working > > really nicely. > > BUT I'd like to do this, an interactive program to see ho the > > algorithms works... > > For example in the breath search first, every time the algorithm > > colors a node, the program should redraw the graphs. Which modules > > should I use for graphics (I use macosX and I'd like something cross > > platforms). > > Use the bundled Tkinter. I've implemented a similar thing back in my under > graduation days using TCL/Tk, and Tk is perfectly suited for that task. > > Diez Ok thank you very much I'll try with that. But I have some design doubts, I'd like to keep the algorithm (for example bfs) as clean as possible, being independent from the drawing methods. And how could I make it step through algorithms without having a more complicated code? Maybe using threads? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Specification for win32com.client package?
Hello, I am searching for documentation about the interface the win32com package provides, especially win32com.client. I searched the web and Mark Hammonds homepage but only found example code using Dispatch() and DispatchEx() etc. Isnt there a full list of the functions win32.com.client provides? Or do I have to use makepy to somehow generate documentation (how)? I would be thankful if someone could give me a hook about that. Best regards,Peter. - Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.-- http://mail.python.org/mailman/listinfo/python-list
Specification for win32com.client package
Hello, (sorry, the first message bounced; because it is urgent and I wait since yesterday, here it's again): I am searching for documentation about the interface the win32com package provides, especially win32com.client. I searched the web and Mark Hammonds homepage but only found example code using Dispatch() and DispatchEx() etc. Isnt there a full list of the functions win32.com.client provides? Or do I have to use makepy to somehow generate documentation (how)? I would be thankful if someone could give me a hook about that. Best regards,Peter. - Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos.-- http://mail.python.org/mailman/listinfo/python-list
Re: Muzzle Velocity (was: High resolution sleep (Linux)
"Dennis Lee Bieber" <[EMAIL PROTECTED],..m.com> wrote: > On Sun, 6 May 2007 10:15:26 +0200, "Hendrik van Rooyen" > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > > A rifle bullet can travel at around 5000 feet per second. > > You've got some fast rifles over there... LOL - true - I stand corrected - I was aware that: 1) All the animals were slaughtered, and the American Civil War fought with rifles of muzzle velocity around 1800 fps. This was before bullets were jacketed - if you try to push a lead slug through a rifled barrel faster than this, it strips and fouls the barrel 2) That the old NATO round (.308 Winchester) travels at around 2500 fps. - and this was some forty years ago, when I did my stint of military duty. So being an idle bugger, I just naturally assumed that the speed would have doubled in the intervening time since I was last involved in this subject. - hence the 5000. Did you know that the first military smokeless powder round was for the French Lebel? - It threw a bronze ball, and could punch through a single brick wall. Battlefields were suddenly far more dangerous places. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
__getattr__ and __getattribute__
Hi all, i find it difficult to understand the difference between the magic methods __getattr__ and __getattribute__ and so donot know when to use former or later. can someone brief me on it ? regards, KM -- http://mail.python.org/mailman/listinfo/python-list
replacing string in xml file
Hi, I need to replace a string in xml file with something else.Ex - rate rate - Here i have opened an xml file(small part is pasted here).I want to replace the word 'localId' with 'dataPackageID' wherever it comes in xml file.I tried this but didnt work: import sys file_input = raw_input("Enter The ODX File Path:") input_xml = open(file_input,'r') input_xml.replace('localId','dataPackageId') This gives error ---> AttributeError: 'file' object has no attribute 'replace' Can someone help me . Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
In <[EMAIL PROTECTED]>, andrea wrote: > But I have some design doubts, I'd like to keep the algorithm (for > example bfs) as clean as possible, being independent from the drawing > methods. > And how could I make it step through algorithms without having a more > complicated code? Maybe using threads? Create an API that informs some "observer" about actions like visiting a node, traversing or adding an egde and so on. This way you can register callbacks that translate between the graph and the GUI. If you don't want to change the algorithm or graph and node classes this notification can be injected by wrapper classes to some degree. For very fine grained observation of an algorithm you might try to implement a step by step debugger. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file
[EMAIL PROTECTED] schrieb: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I tried this but > didnt work: > > import sys > > file_input = raw_input("Enter The ODX File Path:") > input_xml = open(file_input,'r') This should say input_xml = open(file_input,'r').read() > input_xml.replace('localId','dataPackageId') > This gives error ---> AttributeError: 'file' > object has no attribute 'replace' > Can someone help me . > Thanks > Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file
On Tue, 08 May 2007 13:30:59 +0200, Stefan Behnel wrote > [EMAIL PROTECTED] schrieb: > [...] > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > This should say > > input_xml = open(file_input,'r').read() ...and then it still won't work because the OP's replace call assumes in-place operation despite the fact that strings aren't mutable. The OP needs something following this pattern: input_file = open(filename) xmlcontents = input_file.read() input_file.close() xmlcontents = xmlcontents.replace("spam", "eggs") output_file = open(filename,"w") output_file.write(xmlcontents) output_file.close() For extra credit, use a different file name for writing out the result and rename the file after it's written. That way you don't lose your file contents if a meteor hits your CPU just after it started to overwrite the file. Best regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file
On May 8, 4:30 pm, Stefan Behnel <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] schrieb: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I tried this but > > didnt work: > > > import sys > > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > This should say > > input_xml = open(file_input,'r').read() > > > input_xml.replace('localId','dataPackageId') > > This gives error ---> AttributeError: 'file' > > object has no attribute 'replace' > > Can someone help me . > > Thanks > > Stefan- Hide quoted text - > > - Show quoted text - There is no error now,but the string is not being replaced,It remains the same,should we save the opened file or something -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting a function name from string
On Tue, 8 May 2007 09:38:48 +0200, Cesar Härdfeldt wrote > [...] > I now have 'module' and 'function' as strings and 'parms' normally as a list > of strings. I can import the module by __import__(module) but is there > another way to call: > module.function(parms) than using eval()? function_to_call = getattr(__import__(module), function) function_to_call(parms) Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
> Ok thank you very much I'll try with that. > But I have some design doubts, I'd like to keep the algorithm (for > example bfs) as clean as possible, being independent from the drawing > methods. > And how could I make it step through algorithms without having a more > complicated code? Maybe using threads? Along the lines of what Marc said: Use two graph-implementations that share the same interface regarding the algorithms, but one will emit events to some observer for each operation on the graph - edge/node adding/removal, attribute changing and so forth. Thus the algorithm is kept clean, and all that you can visualize anyway is available to you. diez -- http://mail.python.org/mailman/listinfo/python-list
changing a var by reference of a list
Hi, I am trying to simplify my code, and want to automate the assigning of variables I get back from a set. I was thinking of putting the variables I want changed in a list: L = [self._varA, self._varB ] self._varA is a variable I want to change when I pass L to a function. I know doing this; L[0] = 12 Will replace the entry self._varA with 12, but is there a way to indirectly change the value of self._varA, through the list, something like a by-reference in C++ or a pointer-pointer? With regards, - Jorgen -- http://mail.python.org/mailman/listinfo/python-list
Re: Specification for win32com.client package
Hello Tim, thank you for your answer and sorry for the multiple e-mails. Thank you also for the hint on the book. I already read into it in our local library. Its good, but a little outdated (Jan. 2000) as I mentioned in http://mail.python.org/pipermail/python-list/2007-May/438800.html Do you know, whether something has changed, since the book was written, in the use of the dcomcnfg tool? I heard that DCOM is included in COM since some time. I am not clear what steps are necessary under today's WinXP Professional to get DCOM run. But it is said that it shouldn't be difficult. However, I yet didn't manage to get it run. If you could give me a hint that would be helpful. One short question back to the documentation: I read that 'makepy' could be helpful to generate documentation to the package? Okay, thank you again so much for your great help so far, best regards, Peter. Tim Golden <[EMAIL PROTECTED]> wrote: Peter Fischer wrote: > Hello, (sorry, the first message bounced; because it is urgent and I wait > since > yesterday, here it's again): > > > I am searching for documentation about the interface the win32com > package > provides, especially win32com.client. I searched the web and Mark Hammonds > homepage but only found example code using Dispatch() and DispatchEx() etc. > Isnt there a full list of the functions win32.com.client provides? Or do I > have to > use makepy to somehow generate documentation (how)? > I would be thankful if someone could give me a hook about that. > > Best regards,Peter. I'm afraid you're pretty much out of luck on full documentation, Peter. Mark Hammond & Andy Robinson's book (of several years ago) is still being published: http://www.amazon.com/exec/obidos/tg/detail/-/1565926218?v=glance and certainly contains quite a bit of information on the subject. The .chm which comes with the pywin32 extensions has some information (although not much). Examples from the python-win32 list and this mailing list plus examples from around the web, plus finally the source code itself are pretty much staple fare for people working in the Win32 area under Python. Obviously, what it needs is someone or someones with the energy to get that Python Win32 wiki underway, but at the moment all my energies are devoted elsewhere, I'm afraid. TJG - Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos.-- http://mail.python.org/mailman/listinfo/python-list
Re: Specification for win32com.client package
Peter Fischer wrote: > Hello Tim, > > thank you for your answer and sorry for the multiple e-mails. Thank you also > for > the hint on the book. I already read into it in our local library. Its good, > but a > little outdated (Jan. 2000) as I mentioned in > > http://mail.python.org/pipermail/python-list/2007-May/438800.html Ah, yes. Didn't spot that. Although the book is outdated, so is COM! It's been around in pretty much its present format for wasily as long as that. > Do you know, whether something has changed, since the book was written, in > the use of the dcomcnfg tool? I wouldn't know, but I doubt it; it looks pretty old-fashioned to me. Worth checking some microsoft newsgroups. > I am not clear what steps are necessary under today's WinXP Professional > to get DCOM run. But it is said that it shouldn't be difficult. Certainly I've got no problem running simple stuff. My main area of expertise - WMI - uses it under the covers and it only gives me problems when there's security involved. > One short question back to the documentation: I read that 'makepy' could be > helpful to generate documentation to the package? AFAIK, makepy's got nothing to do with the pywin32 docs. It can be used to generate a proxy Python module for an existing COM package, eg: from win32com.client import gencache xl = gencache.EnsureDispatch ("Excel.Application") # # Behind the scenes this has called makepy to generate # a module which on my machine is under # c:\python24\lib\site-packages\win32com\gen_py # help (xl.__class__) Sorry I can't be more help. I know Mark Hammond follows the python-win32 list; I don't know if he follows the main Python list, so it might be worth posting to python-win32. TJG -- http://mail.python.org/mailman/listinfo/python-list
Gui thread and async jobs.
Hi, i am reading the book "Python Cookbook, 2nd edition" and i encountered a very handy recipe, the one that is called "Combining GUIs and Asynchronous I/O with Threads" It is talking about retain a main GUI thread, doing async work with worker threads and have both talk through a Queue object to dispatch their messages, so the main (GUI) thread remain responsive. It has a very good example by using Tkinter and Qt that is indeed working. The only point that make me wonder is that the QUI thread has to use some polling to check for messages in the Queue. Author said that another alternatives exists (by not doing polling) but the complexity makes them non-practical for the 90% of ocassions. I remember in C# we deal with that sort of things with events/ delegates. Hos the same thing is possible in Python, has anyone any link(s) to have a look ? -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting exercise
On Mon, 2007-05-07 at 22:20 -0700, sherry wrote: > On May 8, 9:31 am, Steven D'Aprano > <[EMAIL PROTECTED]> wrote: > > [snip Steven's response about a programming exercise...] > > [snip Sherrybove's spam about physical exercise...] And today's award for the most conspicuous failure of the Turing test goes to the Spambot posting as Sherrybove! (*applause*) Fortunately, it's not programmed to deliver acceptance speeches, so it will accept the award silently. I-know-this-isn't-on-topic-either-but-I-couldn't-resist'ly yours, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Gui thread and async jobs.
king kikapu wrote: > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > encountered a very handy recipe, the one that is called "Combining > GUIs and Asynchronous I/O with Threads" > > It is talking about retain a main GUI thread, doing async work with > worker threads and have both talk through a Queue object to dispatch > their messages, so the main (GUI) thread remain responsive. > It has a very good example by using Tkinter and Qt that is indeed > working. The only point that make me wonder is that the QUI thread has > to use some polling to check for messages in the Queue. > > Author said that another alternatives exists (by not doing polling) > but the complexity makes them non-practical for the 90% of ocassions. > I remember in C# we deal with that sort of things with events/ > delegates. > Hos the same thing is possible in Python, has anyone any link(s) to > have a look ? It depends on the toolkit you use. Qt has thread-safe custom events in 3.x, and afaik signal/slots (and thus events) are generally thread-safe in 4.x. So, no problems there. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: No module named urllib
On May 7, 6:54 pm, Carsten Haese <[EMAIL PROTECTED]> wrote: > On Mon, 2007-05-07 at 16:24 -0700, HMS Surprise wrote: > > Since sys.path = ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] I > > copied urllib to c:\maxq\lib\Lib. > > > Now I get the error - > > > Traceback (innermost last): > > File "", line 5, in ? > > File "C:\maxq\lib\Lib\urllib.py", line 1148 > >_hextochr = dict(('%02x' % i, chr(i)) for i in range(256)) > > ^ > > SyntaxError: invalid syntax > > The urllib.py you're using is not compatible with the Python you're > using. The snippet above uses Python 2.4+ syntax, and Jython's syntax is > at 2.1 (stable) or 2.2 (beta). > > -- > Carsten Haesehttp://informixdb.sourceforge.net Thanks for posting. How does one ensure (or even detect) that their libraries are compatible? I loaded this library as part of Python 2.5. Thanks, jh -- http://mail.python.org/mailman/listinfo/python-list
Re: changing a var by reference of a list
Jorgen Bodde wrote: > Hi, > > I am trying to simplify my code, and want to automate the assigning of > variables I get back from a set. I was thinking of putting the > variables I want changed in a list: > > L = [self._varA, self._varB ] > > self._varA is a variable I want to change when I pass L to a function. > I know doing this; > > L[0] = 12 > > Will replace the entry self._varA with 12, but is there a way to > indirectly change the value of self._varA, through the list, something > like a by-reference in C++ or a pointer-pointer? > > With regards, > - Jorgen You can make self._varA and self._varB instances of a class and assign a value. Not tested. class _var: pass self._varA=_var() self._varB=_var() L=[self._varA, self._varB] then in function (or method of a class instance): L[0].value=12 Another way is to use a class to pass everything: class _vars: def __init__(self, vars=None): if vars is not None: for varname, value in vars.items(): setattr(self, varname, value) return vars=_vars({'_varA': 0, '_varB': 0}) Then you can access: vars._varA vars._varB -Larry l -- http://mail.python.org/mailman/listinfo/python-list
Re: changing a var by reference of a list
Jorgen Bodde wrote: > Hi, > > I am trying to simplify my code, and want to automate the assigning of > variables I get back from a set. I was thinking of putting the > variables I want changed in a list: > > L = [self._varA, self._varB ] > > self._varA is a variable I want to change when I pass L to a function. > I know doing this; > > L[0] = 12 > > Will replace the entry self._varA with 12, but is there a way to > indirectly change the value of self._varA, through the list, something > like a by-reference in C++ or a pointer-pointer? No, there isn't. But you could do L = ['_varA'] for v in L: setattr(self, v, value) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: changing a var by reference of a list
Ok thanks, I will try this approach. The idea was that I could give a list to the SQL execute command, so that the results coming back would automatically be assigned to variables. With regards, - Jorgen On 5/8/07, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > Jorgen Bodde wrote: > > > Hi, > > > > I am trying to simplify my code, and want to automate the assigning of > > variables I get back from a set. I was thinking of putting the > > variables I want changed in a list: > > > > L = [self._varA, self._varB ] > > > > self._varA is a variable I want to change when I pass L to a function. > > I know doing this; > > > > L[0] = 12 > > > > Will replace the entry self._varA with 12, but is there a way to > > indirectly change the value of self._varA, through the list, something > > like a by-reference in C++ or a pointer-pointer? > > No, there isn't. > > But you could do > > L = ['_varA'] > > for v in L: > setattr(self, v, value) > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
CPU usage
Dear All, I want to get the CPU usage in my code. Is there any module in Python to get it? Would you please help me? Thank you in advance. Navid - Bored stiff? Loosen up... Download and play hundreds of games for free on Yahoo! Games.-- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
In article <[EMAIL PROTECTED]>, James Stroud <[EMAIL PROTECTED]> wrote: [...] > >Conspiracy theorists at least have thought behind their crazy ideas--but >you just come up with monkey talk insults. Good job monkey. > >Monkey can't think of something to say but monkey talk? That's ok, >here's a banana, monkey. Waiting for monkey response, monkey. Conspiracy buffs won't accept anything that contradicts their conclusions, so there's no sense discussing things with them. If there is no evidence proving their point, that in itself is evidence of a cover-up, and proof that they are right. There is no thought, only belief. And I'm glad you made logical arguments, instead of just hurling insults. -- http://mail.python.org/mailman/listinfo/python-list
Re: No module named urllib
On Tue, 2007-05-08 at 06:19 -0700, HMS Surprise wrote: > Thanks for posting. How does one ensure (or even detect) that their > libraries are compatible? You ensure that by taking the library from the version of Python that you're running. > I loaded this library as part of Python 2.5. That's too new. Since you're using Jython, you're running either 2.1 or 2.2 depending on whether you've installed the stable version or the beta version. Go grab a Python distribution of the correct version and get the modules you need from there. Note this, though: http://www.jython.org/Project/installation.html#can-t-access-standard-python-modules : "Not all the modules form CPython is available in Jython. Some modules require a C language dynamic link library that doesn't exists in java. Other modules are missing from Jython just because nobody have had a need for it before and no-one have tested the CPython module with Jython. If you discover that you are missing a module, try to copy the .py file from a CPython distribution to a directory on your Jython sys.path. If that works you are set. If it doesn't work, try asking on jython-users mailing list." To summarize, you could be looking at a rather deep rabbit hole of possibly unsatisfiable dependencies. To summarize the summary, are you sure you need to use Jython instead of standard CPython? Good luck, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Gui thread and async jobs.
On May 8, 4:00 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > king kikapu wrote: > > Hi, i am reading the book "Python Cookbook, 2nd edition" and i > > encountered a very handy recipe, the one that is called "Combining > > GUIs and Asynchronous I/O with Threads" > > > It is talking about retain a main GUI thread, doing async work with > > worker threads and have both talk through a Queue object to dispatch > > their messages, so the main (GUI) thread remain responsive. > > It has a very good example by using Tkinter and Qt that is indeed > > working. The only point that make me wonder is that the QUI thread has > > to use some polling to check for messages in the Queue. > > > Author said that another alternatives exists (by not doing polling) > > but the complexity makes them non-practical for the 90% of ocassions. > > I remember in C# we deal with that sort of things with events/ > > delegates. > > Hos the same thing is possible in Python, has anyone any link(s) to > > have a look ? > > It depends on the toolkit you use. Qt has thread-safe custom events in 3.x, > and afaik signal/slots (and thus events) are generally thread-safe in 4.x. > So, no problems there. > > Diez Aha...So you do not use polling there (in Qt), correct ? -- http://mail.python.org/mailman/listinfo/python-list
Setting up python socket server with non-standard termination string.
Hi, I'm trying to create a tcp/ip port listening socket server for various cellular devices that don't use the standard "\r\n" termination string at the end of their message. Instead, they use "-ND-". Do you know how I can setup such a server, preferably using either 'socket.py', 'serversocket.py' or 'twisted.py'? Many thanks, David Jones -- http://mail.python.org/mailman/listinfo/python-list
Re: getmtime differs between Py2.5 and Py2.4
Martin v. Löwis wrote: >> the difference (rounding to an int number of seconds) is just about one >> hour; in certain parts of the world (Europe and Africa), that could >> indeed be a timezone issue. > > With the help of Tony Meyer, we rediscovered the explanation: because > of a bug in the Microsoft C run-time library, the UTC time reported by > 2.4 may have been off by one hour (it wasn't local time - just off > by one hour). This was due to DST issues. They have been fixed in 2.5, > which now reports the correct UTC value. > > Regards, > Martin Well, indeed I got only a 1 hour difference, on my machine (local time here is +1 hour). But when I temporarily set the local time of my machine to GMT I the difference became 0, therefore I assumed wrongly it had something to do with the local time difference. Thanks to everyone helping to clarify this. My response was slow, because I have been experiencing problems with my newsreader setup. - Josef -- http://mail.python.org/mailman/listinfo/python-list
Re: No module named urllib
> To summarize the summary, are you sure you need to use Jython instead of > standard CPython? > Thanks for all your help Carsten, you have been more than patient with me. To answer your question I must admit I do not know. I am trying to use a tool called maxq (maxq.tigris.org) that has limited documentation, or limited in the depth needed by a python/jython neophyte such as me. Maxq acts an http proxy and generates jython scripts for playback testing of web apps. So far I have gained a lot of ground referring to python documentation and even testing code snippets in python shells. So lacking the knowledge of what is jython/maxq/python and being of at best moderate intellect I find myself easily overwhelmed and generally not sure what must be used where. Maxq does not have a tool for parsing the web pages, therefore I wanted to add some library calls to pick off some timestamps I must have. Perhaps I should start looking for another tool, such as twill maybe. I will fetch an older python and see if that helps. Thanks again, jh -- http://mail.python.org/mailman/listinfo/python-list
Re: changing a var by reference of a list
On Tue, 2007-05-08 at 15:40 +0200, Jorgen Bodde wrote: > Ok thanks, > > I will try this approach. The idea was that I could give a list to the > SQL execute command, so that the results coming back would > automatically be assigned to variables. It's not possible to do that exactly as stated. A function can not modify its caller's namespace. (There is probably some dirty trick that can do this anyway, but you don't want to use dirty tricks.) Also, I'm not sure I'd want a function to pollute my local namespace with any variables of its choice. How would I know that it won't overwrite any variable whose contents I need? (Don't try to answer, this is a rhetorical question!) Most DB-API implementations have a facility to return query results as dictionaries or "a bag full of attributes"-type objects. The syntax for achieving this varies between implementations, because this is a non-standard addition outside the DB-API spec. With InformixDB for example, it would look something like this: import informixdb conn = informixdb.connect("stores_demo") cur = conn.cursor(rowformat=informixdb.ROW_AS_OBJECT) cur.execute("select * from customer") for row in cur: print row.customer_num, row.company This allows accessing the result columns as attributes of a row object, which is 99% as convenient as having local variables assigned to the results, and its 15000% cleaner. I strongly suggest you find an equivalent mechanism to use with whatever database module you're using, since it's a fairly safe bet that you're not using Informix. We could help you find that mechanism if you told us what database and what DB-API module you're using. Best regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
ipython environment question
""" I'm trying to import ipython shell (which works great!) to set some variables and then run a function (which doesn't work). It seems like such a simple thing. Here's an example script to show what I'm trying to do. Run the script and then try to change the variable project_name from the ipython prompt and then type create() and the new value you assigned will *not* be used. I tried to use "def create(project_name = project_name):" Even that didn't work. What slight of hand is necessary? import os, sys project_name = 'python_packages' group_name = 'sgeiger' repo = '/var/svn' def create(repo=repo,group_name=group_name,project_name=project_name): #def create(): #os.system("sudo mkdir -p " + repo ) #os.system("sudo svnadmin create " + repo) #os.system("sudo chown -R " + group_name + " " + repo) print "sudo mkdir -p " + repo + '/' + project_name print "sudo svnadmin create " + repo + '/' + project_name print "sudo chown -R " + group_name + " " + repo + '/' + project_name if __name__ == '__main__': sys.argv.append('-cl') from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() print "Please set these variables: project_name, group_name ...and then type create()" ### I even tried to put all my ipshell() # this call anywhere in your program will start IPython -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy begin:vcard fn:Shane Geiger n:Geiger;Shane org:National Council on Economic Education (NCEE) adr:Suite 215;;201 N. 8th Street;Lincoln;NE;68508;United States email;internet:[EMAIL PROTECTED] title:IT Director tel;work:402-438-8958 x-mozilla-html:FALSE url:http://www.ncee.net version:2.1 end:vcard -- http://mail.python.org/mailman/listinfo/python-list
Re: No module named urllib
On May 8, 9:13 am, HMS Surprise <[EMAIL PROTECTED]> wrote: > > To summarize the summary, are you sure you need to use Jython instead of > > standard CPython? > > Thanks for all your help Carsten, you have been more than patient with > me. > > To answer your question I must admit I do not know. I am trying to use > a tool called maxq (maxq.tigris.org) that has limited documentation, > or limited in the depth needed by a python/jython neophyte such as me. > Maxq acts an http proxy and generates jython scripts for playback > testing of web apps. So far I have gained a lot of ground referring to > python documentation and even testing code snippets in python shells. > So lacking the knowledge of what is jython/maxq/python and being of at > best moderate intellect I find myself easily overwhelmed and > generally not sure what must be used where. Maxq does not have a tool > for parsing the web pages, therefore I wanted to add some library > calls to pick off some timestamps I must have. Perhaps I should start > looking for another tool, such as twill maybe. > > I will fetch an older python and see if that helps. > > Thanks again, > > jh Thanks again, Carsten. Using v2.2.3 got me past the urllib error. jh -- http://mail.python.org/mailman/listinfo/python-list
Re: Gui thread and async jobs.
>> It depends on the toolkit you use. Qt has thread-safe custom events in >> 3.x, and afaik signal/slots (and thus events) are generally thread-safe >> in 4.x. So, no problems there. >> >> Diez > > Aha...So you do not use polling there (in Qt), correct ? You don't need to, no. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: CPU usage
Navid Parvini wrote: > I want to get the CPU usage in my code. > Is there any module in Python to get it? What Operating System are you on? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Gui thread and async jobs.
On May 8, 5:52 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > >> It depends on the toolkit you use. Qt has thread-safe custom events in > >> 3.x, and afaik signal/slots (and thus events) are generally thread-safe > >> in 4.x. So, no problems there. > > >> Diez > > > Aha...So you do not use polling there (in Qt), correct ? > > You don't need to, no. > > Diez Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: ipython environment question
In <[EMAIL PROTECTED]>, Shane Geiger wrote: > Run the script and then try to change the variable project_name from the > ipython prompt and then type create() > and the new value you assigned will *not* be used. I tried to use "def > create(project_name = project_name):" Even that didn't work. > > What slight of hand is necessary? > > import os, sys > > project_name = 'python_packages' > group_name = 'sgeiger' > repo = '/var/svn' > > def create(repo=repo,group_name=group_name,project_name=project_name): > #def create(): >#os.system("sudo mkdir -p " + repo ) >#os.system("sudo svnadmin create " + repo) >#os.system("sudo chown -R " + group_name + " " + repo) >print "sudo mkdir -p " + repo + '/' + project_name >print "sudo svnadmin create " + repo + '/' + project_name >print "sudo chown -R " + group_name + " " + repo + '/' + project_name > > if __name__ == '__main__': >sys.argv.append('-cl') >from IPython.Shell import IPShellEmbed >ipshell = IPShellEmbed() >print "Please set these variables: project_name, group_name ...and > then type create()" >### I even tried to put all my >ipshell() # this call anywhere in your program will start IPython You have to call the function with arguments. The default values are only evaluated once when the ``def`` statement is executed, not every time the function is called. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: File Name Format
On 2007-05-08, Anand <[EMAIL PROTECTED]> wrote: > How do I convert programmatically the file names from WIN32 to UNIX format? You don't need to. AFAIK, all legal WIN32 filenames are legal UNIX file names. > A code snippet would be of great help. As would an example of what you're trying to do. -- Grant Edwards grante Yow! JAPAN is a WONDERFUL at planet -- I wonder if we'll visi.comever reach their level of COMPARATIVE SHOPPING ... -- http://mail.python.org/mailman/listinfo/python-list
pymacs
Hi there. Does anyone out there know what's going on with pymacs currently? Thanks, Grant. -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting exercise
On Tue, 08 May 2007 10:22:05 +, James Stroud wrote: > This takes annoying past annoying to some new level of hell to which > even satan himself wouldn't venture. And thank you for sharing that piece of spam with us again. It was so much less enjoyable to see it the second time. Seriously James, with more and more people using automated spam filters, it might not be such a wise idea to keep having your name associated with spam content. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
XLRD Python 2.51 Question
I am trying to read an Excel book with XLRD and I am getting the following error Traceback (most recent call last): File "C:\temp\ReadGoldmanExcelFiles.py", line 62, in startRow = 0, sh_idx = 0, path2 = '//otaam.com/root/SharedFiles/ GlobeOp/Risk/Cal Projects/temp/') File "C:\temp\ReadGoldmanExcelFiles.py", line 36, in excelTocsv book = xlrd.open_workbook(infile) File "C:\Python25\lib\site-packages\xlrd\__init__.py", line 362, in open_workbook formatting_info=formatting_info, File "C:\Python25\lib\site-packages\xlrd\__init__.py", line 791, in __init__ cd = compdoc.CompDoc(filestr) File "C:\Python25\lib\site-packages\xlrd\compdoc.py", line 122, in __init__ "MSAT extension: accessing sector %d but only %d in file" % (sid, mem_data_secs) CompDocError: MSAT extension: accessing sector 1717046 but only 2887 in file I am not sure what this means at all, can anyone help here? Thanks alot -- http://mail.python.org/mailman/listinfo/python-list
Re: Emacs and pdb after upgrading to Ubuntu Feisty
Okay, thanks Alexander and Bernstein. I'll lookinto Emacs 23, but I'm worried about compatibility with modes. Does all the stuff that works in Emacs 21 work in 23? Like even that ipython.el file, does it work in Emacs 23? And, I probably will report a bug to either Ubuntu's Launchpad or to Debian's package maintainer for pdb mode (which apparently has been integrated into just the gud mode stuff, at least that's how it looks from looking around on my system). Does Debian have a web site for reporting bugs like Ubuntu does? Or, do I just email the package maintainer? I'm messing around with ipython.el and ipython now. It looks like if you just want to step through some code that isn't throwing any execption, you have to modify the source code of your script to tell ipython to stop on this line and start debugging here? With all the raving about ipython, I'm sure it's a great product. But, this thing about having to modify your source code really sounds like it sucks. I'd be surprised if it were difficult to implement a command line option for ipython that tells it to open this file and then start debugging it from the top. And, have the emacs mode operate much like it does with pdb, where emacs remembers your command line when you invoked pdb, so you just hit "M-x pdb RET RET RET ..." to open up your file. But, maybe I just haven't foud it yet? -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter - label widget text selection
On May 6, 2:24 pm, Rob Wolfe <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] writes: > > Hi, > > I guess this is a very trivial question -- > > I am using a label widget to display text (black font in a white > > background color). I am trying to use my mouse to scroll over the > > displayed text to select it, buttkinterdoes not allow me to do it. > > Is there a method/option to do this. > > Try to use an entry widget in read-only state: > > > importTkinteras Tk > root = Tk.Tk() > > ent = Tk.Entry(root, state='readonly', readonlybackground='white', fg='black') > var = Tk.StringVar() > var.set('Some text') > ent.config(textvariable=var, relief='flat') > ent.pack() > root.mainloop() > > > -- > HTH, > Rob Thanks Rob I will try it out...Rahul -- http://mail.python.org/mailman/listinfo/python-list
Re: XLRD Python 2.51 Question
On Tue, 2007-05-08 at 08:26 -0700, [EMAIL PROTECTED] wrote: > CompDocError: MSAT extension: accessing sector 1717046 but only 2887 > in file > > I am not sure what this means at all At least superficially that sounds like the file you're trying to open is truncated or otherwise corrupted to the point where xlrd doesn't know what to do with it. What happens if you try to open the file with Excel? If Excel manages to open the file, maybe the file is using a storage format that's newer than what xlrd is prepared to handle. In that case, try saving the file to a different file name as another format (such as Excel 97) that xlrd should be able to handle. HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
sys.path
Is sys.path setup differnently in jython vs python? I have environment variables pythonpath and jythonpath set to include C:\python22 but the initial printout indicates it is being ignored. Also when I used sys.path.extend, the added pathname shows up as a series of single characters. Have I misused .extend? Thanks, jh import sys print sys.path sys.path.extend("c:\python22") print sys.path import urllib ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython'] ['.', 'C:\\maxq\\lib\\Lib', 'C:\\maxq\\jython', 'c', ':', '\\', 'p', 'y', 't', 'h', 'o', 'n', '2', '2'] Traceback (innermost last): File "", line 9, in ? ImportError: no module named urllib -- http://mail.python.org/mailman/listinfo/python-list
Re: Can Python Parse an MS SQL Trace?
On May 8, 5:18 am, Tim Golden <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > On May 7, 8:34 am, Tim Golden <[EMAIL PROTECTED]> wrote: > >> [EMAIL PROTECTED] wrote: > >>> Can Python parse a trace file created with MS SQL's profiler? There > >>> are a few thousand lines in the trace file and I need to find the > >>> insert statements and the stored procedures. Unfortunately, I am not > >>> an SQL guru and was hoping Python could help. > >>> Mike > >> Mike, > > >> Can I suggest that, since the answer is more to > >> do with parsing and less to do with MSSQL (which > >> simply generated the output) that you post an example > >> of a trace file to some web location to see if anyone > >> wants to pick up the challenge? > > >> I'm not at work so I don't have access to MSSQL, but > >> I seem to remember that you can output/save as XML, > >> which may make things easier (or at least interest a > >> different group of people in having a look). > > >> I'm quite certain it can by done by Python; I did > >> consider it myself a couple of months back, but my > >> colleague spotted the problem before I'd really got > >> into the code! > > >> TJG > > > Good point. Unfortunately, I think our SQL Server must be too old for > > xml (we have version 8). The only save options I see is Trace > > Template, Trace File, Trace Table and SQL Script. > > Yes, you're right; I have clients installed for SQL 2000 & > 2005 and it's only under 2005 that I have the XML output > option. The .trc file format is pretty much opaque binary, > and the .sql output only gives you the SQL statements > issued - not the events they're associated with. > > One obvious way is to save it to a table and to interrogate > that table. I find that kind of thing a bit cumbersome, but > if XML's not an option, it might be the only way. (FWIW, > I find XML cumbersome too, but that might just be lack > of practice ;) > > Running a standard trace and saving to a table, this is > the structure which resulted: > > CREATE TABLE [trace_output] ( > [RowNumber] [int] IDENTITY (1, 1) NOT NULL , > [EventClass] [int] NULL , > [TextData] [ntext] COLLATE SQL_Latin1_General_CP1_CS_AS NULL , > [NTUserName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [ClientProcessID] [int] NULL , > [ApplicationName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [LoginName] [nvarchar] (128) COLLATE > SQL_Latin1_General_CP1_CS_AS NULL , > [SPID] [int] NULL , > [Duration] [bigint] NULL , > [StartTime] [datetime] NULL , > [Reads] [bigint] NULL , > [Writes] [bigint] NULL , > [CPU] [int] NULL , > PRIMARY KEY CLUSTERED > ( > [RowNumber] > ) ON [PRIMARY] > ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] > GO > > Seems like you might be able to do something with it. > (Possibly just dumping it straight back out to CSV > or XML if that's easier for you than db querying) > > TJG Thanks for the advice. I did the one that had to be done now by hand. However, I know I'll need to do more of these in the future, so I'll try it then. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.path
HMS Surprise wrote: > Have I misused .extend? The .extend() method expects an iterable, try .append() instead. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ -- http://mail.python.org/mailman/listinfo/python-list
Towards faster Python implementations - theory
Some faster Python implementations are under development. JPython has been around for a while, and PyPy and ShedSkin continue to move forward. It's worth thinking about what slows down Python implementations. It isn't the dynamism, really. As others have pointed out in the Python literature, most of the time, the more elaborate dynamic features aren't being used for any given variable or object. If code has something like "x = 1.0", the odds are that "x" is going to stay a floating point number, and not suddenly turn into a list or an object reference. The type inference of Shed Skin builds on that assumption, adding some restrictions about changing of variable types. The Shed Skin effort indicates that explicit typing, via 'decorators' or otherwise, isn't really necessary. What's necessary is the avoidance of "surprises" in the language. In this context, a "surprise" is the use of a dynamic feature in a way that can't be seen at compile time. A typical "surprise" would be the use of "setattr" on an object from outside the compilation unit that defines the object. Within a module, "setattr" on an object in that module is no problem; the compiler can see it and generate the extra machinery needed to make an object dynamically alterable at run time. But if an object doesn't need that extra machinery and associated dictionary, it's a big win to discard the excess baggage and use a simpler fixed-size representation, comparable to a C struct, for the object. On the typing front, the neatest way to express typing is via initialization. With the Shed Skin restrictions, if all variables are initialized before use (preferably in __init__), there's no need to maintain an "undefined" flag for a variable. And, of course, if the type of a varaible is simple and can't change, it doesn't have to be "boxed", (enclosed in an object) which is a big win. The point here is that we don't need language changes or declarations to make Python much faster. All we need are a few restrictions that insure that, when you're doing something unusual, the compiler can tell. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
On 8th May, 17:53, John Nagle <[EMAIL PROTECTED]> wrote: > Some faster Python implementations are under development. > JPython Ahem: Jython! > has been around for a while, and PyPy and ShedSkin > continue to move forward. It's worth thinking about what slows > down Python implementations. It's the dynamicity! ;-) But things like clever memory allocation can pay dividends, too, and I wouldn't be surprised if this explained Python's better-than-expected showing when compared to other languages - such as that comparison you provoked with those claims of superior JavaScript performance. ;-) > It isn't the dynamism, really. In theory, no, but in practice CPython doesn't optimise away the dynamism. Recent experiments with method caches seem to have shown modest performance improvements, and I'd guess that such things are fairly established in other dynamic language implementations. > As others have pointed out > in the Python literature, most of the time, the more elaborate > dynamic features aren't being used for any given variable or > object. If code has something like "x = 1.0", the odds are that > "x" is going to stay a floating point number, and not suddenly turn > into a list or an object reference. The type inference of Shed Skin > builds on that assumption, adding some restrictions about changing of > variable types. The problem here, amongst many others, is knowing for sure whether the more elaborate features have been avoided. Approaches which attempt to avoid knowing such things include just-in-time compilation (you avoid knowing in advance) and type declarations (you give up thinking about whether it's possible and have the programmer do all the work). > The Shed Skin effort indicates that explicit typing, via 'decorators' > or otherwise, isn't really necessary. What's necessary is the avoidance > of "surprises" in the language. In this context, a "surprise" is > the use of a dynamic feature in a way that can't be seen at compile time. I concur with your assessment of the supposed necessity of explicit typing. However, you might be surprised as to what constitutes a "surprise" in Python... > A typical "surprise" would be the use of "setattr" on an object from > outside the compilation unit that defines the object. Within a module, > "setattr" on an object in that module is no problem; the compiler can see > it and generate the extra machinery needed to make an object dynamically > alterable at run time. But if an object doesn't need that extra machinery > and associated dictionary, it's a big win to discard the excess baggage > and use a simpler fixed-size representation, comparable to a C struct, > for the object. You don't even need to bring out setattr to make the inference activity a difficult one. Even straightforward attribute access needs to be repeatedly checked to see if the target of a normal attribute assignment or query has changed. Traditionally, people have shown some trivial function in isolation... def f(x): return x.a ...and said, "We don't know anything! It's all impossible!" But context is everything, as you know, and whole program analysis is the only way to go with the aforementioned goals in mind. What if the parameter to the above itself comes from attribute access? def g(y): return f(y.b) You can descend into some fairly demanding situations with respect to keeping track of all the possibilities. > On the typing front, the neatest way to express typing is via > initialization. With the Shed Skin restrictions, if all variables are > initialized before use (preferably in __init__), there's no need to > maintain an "undefined" flag for a variable. And, of course, if > the type of a varaible is simple and can't change, it doesn't have to > be "boxed", (enclosed in an object) which is a big win. I'm fairly sure, although my intuition unfortunately doesn't provide a ready example right now, that typing via initialisation, whilst an important tool, may either impose unacceptable restrictions if enforced too rigidly or limit the precision that one might desire in determining type information in the resulting system. But it is a worthwhile objective to identify fixed-size structures and unboxed values, in my opinion. > The point here is that we don't need language changes or declarations > to make Python much faster. All we need are a few restrictions that > insure that, when you're doing something unusual, the compiler can > tell. Agreed. And I don't buy into the negative "lesser Python" labelling of such work, either. People seem to have forgotten how to use older, conservative Python features, preferring to show off with metaclasses and closures even for problems that could be solved using simple classes and objects. If that's "greater Python" then call me a minimalist! Paul -- http://mail.python.org/mailman/listinfo/python-list
Atttribute error
The snippet below causes an attribute error. AttributeError: module 'urllib' has no attribute 'urlopen' I am using python 2.2.3. According to the documentation at C: \Python22\Doc\lib urllib has a function called urlopen. #~~~ import urllib class login(CompactTest): # Recorded test actions. def runTest(self): f = urllib.urlopen("http://www.python.org/";) f.read() -- http://mail.python.org/mailman/listinfo/python-list
Re: Atttribute error
In <[EMAIL PROTECTED]>, HMS Surprise wrote: > The snippet below causes an attribute error. > > AttributeError: module 'urllib' has no attribute 'urlopen' > > I am using python 2.2.3. According to the documentation at C: > \Python22\Doc\lib urllib has a function called urlopen. Do you have a file called `urllib.py` in the current directory? Then this gets imported instead of the module in the standard library. Add this directly after the ``import`` to see what's happening: print urllib.__file__ print dir(urllib) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.path
On May 8, 10:40 am, Klaus Alexander Seistrup <[EMAIL PROTECTED]> wrote: > HMS Surprise wrote: > > Have I misused .extend? > > The .extend() method expects an iterable, try .append() instead. > > Cheers, > > -- > Klaus Alexander Seistruphttp://klaus.seistrup.dk/ Thanks Klaus. That certainly cleaned up sys.path. Now if I can get the system to search there for my lib file. -- http://mail.python.org/mailman/listinfo/python-list
Re: Atttribute error
On May 8, 11:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, HMS Surprise > wrote: > > > The snippet below causes an attribute error. > > > AttributeError: module 'urllib' has no attribute 'urlopen' > > > I am using python 2.2.3. According to the documentation at C: > > \Python22\Doc\lib urllib has a function called urlopen. > > Do you have a file called `urllib.py` in the current directory? Then this > gets imported instead of the module in the standard library. > > Add this directly after the ``import`` to see what's happening: > > print urllib.__file__ > print dir(urllib) > > Ciao, > Marc 'BlackJack' Rintsch Thanks for posting Marc. I do have a file named `urllib.py` in the current directory. I copied it from 'C:\Python22\Lib' as I could not get rid of the 'no module named urllib' error message, even though I appended 'C:\Python22\Lib to sys.path'. This changed the error from module not found to a no attribute msg. The maxq program (IDE?, runtime enviroment? , shell?) apparently uses jython so maybe sys.path is not the problem. This is the reason for my thread 'sys.path'. Thanks again, jh -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] says... > On Mon, 7 May 2007 10:55:55 -0400, James Beck > <[EMAIL PROTECTED]> wrote: > > >In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] > >says... > >> On Sat, 05 May 2007 07:54:50 +0100, Eeyore > >> <[EMAIL PROTECTED]> wrote: > >> > >> > > >> > > >> >quasi wrote: > >> > > >> >> Gib Bogle wrote: > >> >> > >> >> >Ah, so the firefighters were in on the conspiracy! > >> >> > >> >> No, but the firefighters are very much aware that there is more to > >> >> 9/11 than has been officially revealed. > >> >> > >> >> This is even more true at Pentagon. The firefighters there brought > >> >> dogs trained to search for survivors and/or remains > >> > > >> >Sounds like good practice. > >> > > >> > > >> >> and found nothing. > >> > > >> >And the significance of this is ? > >> > >> The plane was supposed to have passengers. > >> > >> quasi > >> > >Yep, and they found them all, therefore, there were none for the dogs to > >find. > > You pretty much made that up. > Yep, you must have access to better drugs than I do. You get to hallucinate your stuff up. Don't forget to adjust your tin beanie! Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: changing a var by reference of a list
"Jorgen Bodde" <[EMAIL PROTECTED]> wrote: > I will try this approach. The idea was that I could give a list to the > SQL execute command, so that the results coming back would > automatically be assigned to variables. > Don't forget that in Python a function can return multiple results (or rather can return a sequence). That means you can do something like: varA, varB = doSomething() where doSomething would execute your SQL and return two results. -- http://mail.python.org/mailman/listinfo/python-list
Re: Atttribute error
PS > Add this directly after the ``import`` to see what's happening: > > print urllib.__file__ > print dir(urllib) > C:\maxq\bin\testScripts\.\urllib.py ['__doc__', '__file__', '__name__', 'string'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
In <[EMAIL PROTECTED]>, Paul Boddie wrote: >> On the typing front, the neatest way to express typing is via >> initialization. With the Shed Skin restrictions, if all variables are >> initialized before use (preferably in __init__), there's no need to >> maintain an "undefined" flag for a variable. And, of course, if >> the type of a varaible is simple and can't change, it doesn't have to >> be "boxed", (enclosed in an object) which is a big win. A variable? :-) Maybe that last sentence should start with: And, of course, if the type of objects bound to a name won't change… > I'm fairly sure, although my intuition unfortunately doesn't provide a > ready example right now, that typing via initialisation, whilst an > important tool, may either impose unacceptable restrictions if > enforced too rigidly or limit the precision that one might desire in > determining type information in the resulting system. I often bind a name to `None` first if it is going to be bound to it's "real" value later on. So this initialization doesn't say anything about the type(s) that will be bound to it later. I don't see how this type inference for static types will work unless some of the dynamism of the language will get restricted. But is this really necessary? Isn't a JIT compiler and maybe type hinting good enough? By type hinting I really mean just recommendations from the programmer. So you can say this name should be an `int` and the JIT compiler produces code in advance, but it's okay to pass another object instead. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: File Name Format
In <[EMAIL PROTECTED]>, Grant Edwards wrote: > On 2007-05-08, Anand <[EMAIL PROTECTED]> wrote: > >> How do I convert programmatically the file names from WIN32 to UNIX format? > > You don't need to. AFAIK, all legal WIN32 filenames are legal > UNIX file names. Doesn't this depend more on the file system than the operating system? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Crypto plaintext padding (SOLVED)
On Sun, 2007-05-06 at 11:39 -0400, David Clymer wrote: > I'm using pycrypto's AES module, and am attempting to automate the > padding of the plaintext (the size of the text to be encrypted must be a > multiple of 16). However, my padding scheme sometimes fails to calculate > the necessary padding correctly, and I'm not sure why. > > Using the text 'foo bar', it fails, but if I do 'foo bars' it works. > Randomized testing fails sometimes and not others. > > Any pointers as to what I might be doing wrong (code attached)? Nevermind. After I walked away from it for a bit, the mistake was obvious. I was using the modulus of the text length by the block size directly, rather than the block size minus that number: --- /home/david/Desktop/test.py 2007-05-06 13:38:52.0 -0400 +++ test.py 2007-05-06 13:39:38.0 -0400 @@ -9,12 +9,12 @@ def __init__(self, text, key_phrase): key = SHA256.new(key_phrase) self.aes = AES.new(key.digest()) -#self.encrypted_text = self.aes.encrypt(self._pad(text)) +self.encrypted_text = self.aes.encrypt(self._pad(text)) def _unpad(self, txt): """Remove padding from the given text""" for x in xrange(len(txt) - self.aes.block_size,len(txt)): -if x == ord(txt[x]): +if len(txt[x:]) == ord(txt[x]): if txt[x-1:] + self._gen_pad(txt[x-1:]): return txt[:x] return txt @@ -25,7 +25,7 @@ def _gen_pad(self, txt): """Generate padding for the given plaintext""" -pad_len = (len(txt)) % self.aes.block_size +pad_len = self.aes.block_size - (len(txt) % self.aes.block_size) if pad_len > 0: return chr(pad_len) * pad_len return chr(self.aes.block_size) * self.aes.block_size -- gpg-key: http://www.zettazebra.com/files/key.gpg signature.asc Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Crypto plaintext padding
I'm using pycrypto's AES module, and am attempting to automate the padding of the plaintext (the size of the text to be encrypted must be a multiple of 16). However, my padding scheme sometimes fails to calculate the necessary padding correctly, and I'm not sure why. Using the text 'foo bar', it fails, but if I do 'foo bars' it works. Randomized testing fails sometimes and not others. Any pointers as to what I might be doing wrong (code attached)? -davidc -- gpg-key: http://www.zettazebra.com/files/key.gpg from Crypto import Hash, Cipher from Crypto.Cipher import AES from Crypto.Hash import SHA256 class EncryptedText: """A class to hide the details of encryption and decryption""" def __init__(self, text, key_phrase): key = SHA256.new(key_phrase) self.aes = AES.new(key.digest()) #self.encrypted_text = self.aes.encrypt(self._pad(text)) def _unpad(self, txt): """Remove padding from the given text""" for x in xrange(len(txt) - self.aes.block_size,len(txt)): if x == ord(txt[x]): if txt[x-1:] + self._gen_pad(txt[x-1:]): return txt[:x] return txt def _pad(self, txt): """Pad the given plaintext""" return txt + self._gen_pad(txt) def _gen_pad(self, txt): """Generate padding for the given plaintext""" pad_len = (len(txt)) % self.aes.block_size if pad_len > 0: return chr(pad_len) * pad_len return chr(self.aes.block_size) * self.aes.block_size def __repr__(self): return self.encrypted_text ## testing ## if __name__ == "__main__": import sys import random randomize = True text = 'foo bars' # if available, only test the text supplied by the user if len(sys.argv) > 1: randomize = False text = sys.argv[1] print 'plaintext: "%s"' % (text,) r = random.Random() cycles = 1 # pick a random number of test cycles if randomize: cycles = r.randrange(20) for testcycle in xrange(0, cycles): try: # generate a plaintext of random length and content if randomize: print print 'Test #%i' % testcycle text='' for x in xrange(0, r.randrange(1000)): text += chr(r.randrange(256)) # check to see if padding & unpadding yield appropriate results e = EncryptedText(text, 'blah') bs = e.aes.block_size p = e._pad(text) pd = SHA256.new(p).hexdigest() unp = e._unpad(p) unpd = SHA256.new(unp).hexdigest() print 'cipher block size: %i' % (bs,) print 'padded: "%s"' % (p,) print 'padded len: "%i"' % (len(p),) print 'unpadded: "%s"' % (unp,) print 'unpadded len: "%i"' % (len(unp),) print # ensure that original an unpadded text match, and that padded # text is completely divisible by the cipher block size if SHA256.new(text).digest() == SHA256.new(unp).digest() and \ len(p) % bs == 0: print "Test succeeded." else: print "Unpadded text does not match original plaintext, or " print "padded text is not divisible by the cipher block size: " print "Test failed." except Exception, e: print "Program error: " print "Test failed." print e signature.asc Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Binding
STiAT wrote: > Why do you all suggest other things than the way suggested by python? Because going to Paris is not the only way to get french bread? Why would you want to write all that ugly glue code by hand that Pyrex generates for free? Module descriptors? Class descriptors? Method descriptors? Reference counting? That's what Pyrex saves you from. Honestly. >From what I read in your mail, that's exactly the kind of thing you're having trouble with. Wouldn't you prefer concentrating on your real code instead? > I havn't got a real problem writing the code in C, actually, it looked > as if it would give me several possibilities i wouldn't have with > pyrex (like binding more library functions to one provided python > function and so on). No idea what you mean in your parentheses, but I don't think there are many "possibilities" you "wouldn't have with Pyrex". We used Pyrex to write lxml, a wrapper around the huge API of libxml2 and libxslt. It's some 11000 lines of Pyrex code by now, but the generated C code is some 67000 lines in total. Even if it's somewhat verbose and generic in places, I wouldn't have wanted to write that by hand. Stefan -- http://mail.python.org/mailman/listinfo/python-list
1.#QNAN Solution
Hello all, I'm running descriptive stats on mileages from a database (float numbers, about a million records). My sum returns 1.#QNAN, which I understand from searching this forum is an error. While I'm looking for help in solving this problem, I'm more interested in a general explanation about the cause of this problem. Any ideas? Thanks Greg Corradini -- View this message in context: http://www.nabble.com/1.-QNAN-Solution-tf3710941.html#a1037 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: File Name Format
On 2007-05-08, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > In <[EMAIL PROTECTED]>, Grant Edwards wrote: > >> On 2007-05-08, Anand <[EMAIL PROTECTED]> wrote: >> >>> How do I convert programmatically the file names from WIN32 to UNIX format? >> >> You don't need to. AFAIK, all legal WIN32 filenames are legal >> UNIX file names. > > Doesn't this depend more on the file system than the operating system? Sort of. AFAIK, no matter which "Windows" filesystem you pick, the set of allowed filenames are legal for all of the common "Unix" filesystems (EXT3, XFS, Reiser, etc.). However, the OP hasn't offered any details about what it is he's actually wanting to do, so this is all just idle speculation... -- Grant Edwards grante Yow! I know how to do at SPECIAL EFFECTS!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.#QNAN Solution
On 2007-05-08, Greg Corradini <[EMAIL PROTECTED]> wrote: > I'm running descriptive stats on mileages from a database > (float numbers, about a million records). My sum returns > 1.#QNAN, which I understand from searching this forum is an > error. Not necessarily. You've ended up with a floating point "not a number" value (AKA a NaN). That might or might not be an error. Whether it's an error not not depends on your input data and your algorithm. > While I'm looking for help in solving this problem, I'm more > interested in a general explanation about the cause of this > problem. If you're asking how you end up with a NaN, there are several ways to generate a NaN: 0/0 Inf*0 Inf/Inf Inf-Inf Almost any operation on a NaN http://en.wikipedia.org/wiki/NaN http://steve.hollasch.net/cgindex/coding/ieeefloat.html -- Grant Edwards grante Yow! Spreading peanut at butter reminds me of visi.comopera!! I wonder why? -- http://mail.python.org/mailman/listinfo/python-list
Re: change of random state when pyc created??
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > My testing suggests the bug is *not* to do with pyc files at all. I'm > getting different results when running the files, even when the directory > is read-only (and therefore no pyc files can be created). > > My results suggest that setting the seed to the same value does NOT give > identical results, *even though* the random number generator is giving > the same results. > > So I think we can discount the issue being anything to do with either > the .pyc files or the random number generator. I do not know how Python handles your use of a readonly directory. What I have seen is: - when a test1.pyc file is present, I always get the same outcome (result1) - when a test1.pyc file is NOT present, I always get the same outcome (result2) - the two outcomes are different (result1 != result2) Do you see something different than this if you run the test as I suggested? If not, how can in not involve the .pyc file (in some sense)? Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Emacs and pdb after upgrading to Ubuntu Feisty
levander <[EMAIL PROTECTED]> writes: > Okay, thanks Alexander and Bernstein. I'll lookinto Emacs 23, but I'm > worried about compatibility with modes. Does all the stuff that works > in Emacs 21 work in 23? I've switched from 21 to 23 a few weeks ago and don't recall any particular issues (and I'm a fairly hardcore emacs user with pretty complex configuration and many third-party packages -- my emacs config has 182 matches for require\|autoload). > Like even that ipython.el file, does it work in Emacs 23? I think as the author I would have noticed by now if it didn't :) > And, I probably will report a bug to either Ubuntu's Launchpad or to > Debian's package maintainer for pdb mode (which apparently has been > integrated into just the gud mode stuff, at least that's how it looks from > looking around on my system). Does Debian have a web site for reporting bugs > like Ubuntu does? Or, do I just email the package maintainer? > > I'm messing around with ipython.el and ipython now. It looks like if > you just want to step through some code that isn't throwing any > execption, you have to modify the source code of your script to tell > ipython to stop on this line and start debugging here? Nope. Try ``run -d myscript`` (and ``?run`` for more info). I must admit that this doesn't work properly for me though -- I don't get stepping through the corresponding source in emacs. ``M-x pdb`` works with pdb as debugger but not with pydb; maybe the problem is missing pydb support in the relevant regexps? I can't devote any time to this at the moment, but I'd be pretty interested in having this working -- so I'd appreciate a note if someone figures out what's going on (and if a change to ipython.el is needed I'll make sure it gets in). > With all the raving about ipython, I'm sure it's a great product. But, this > thing about having to modify your source code really sounds like it sucks. > I'd be surprised if it were difficult to implement a command line option for > ipython that tells it to open this file and then start debugging it from the > top. It's already there -- I'm using 0.7.4 svn (which is the ubuntu feisty package), so I think it should also work for you. > And, have the emacs mode operate much like it does with pdb, where emacs > remembers your command line when you invoked pdb, so you just hit "M-x pdb > RET RET RET ..." to open up your file. But, maybe I just haven't foud it > yet? I'd type something like ``run -+`` (with M-p bound to `comint-previous-matching-input-from-input') or M-r, which is even fewer keystrokes. 'as -- http://mail.python.org/mailman/listinfo/python-list
Re: No module named urllib
Great idea Dennis, I will look into that. Thanks, jh -- http://mail.python.org/mailman/listinfo/python-list
fminbound
Hello everyone: I'm new using scipy, so I'm sorry if any of my questions are silly. I'm trying to find the maxima, absolut and local, of a function, in order to fit an exponencial curve and get de exponecial argument. My function if the soluction of a couple equations system: def derivs3(x,t,gamma,omega,dl): d1 = omega*x[2] - gamma *x[0] d2 = dl*x[2] - (gamma/2.)* x[1] d3 = -omega *x[0] - dl*x[1] - (gamma/2.)* x[2] + (omega/2.) return d1,d2,d3 def solucion(a,t,gamma, omega, dl): sol=odeint(derivs3,a,t,(gamma,omega,dl)) return sol The case I'm interesting in, the soluction have the form of a sin*exp, so I want to find the function that envolves it, a exponencial function. To do this, I can find the maximas, and fit them, so I use: def g4(t1): sol2=odes.solucion((0.5,0,0),t1,0.5,5,0) return sol2[:,0] x_max = optimize.fminbound(g4,0,2) To use fminbound, I need a function that returns only a single array, so I use de g4 function. I use (0,2) as bounds. The problem I have is that the return is: x_max 1.959949686341 That aren't the maximas in the interval. If I change the interval: x_max = optimize.fminbound(g4,0.1,4) x_max 3.945129622403 And so on. I don't know what I'm doing wrong, so if everyone can help, I'm going to be really happy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Setting up python socket server with non-standard termination string.
On 8 May 2007 06:59:26 -0700, [EMAIL PROTECTED] wrote: >Hi, > >I'm trying to create a tcp/ip port listening socket server for various >cellular devices that don't use the standard "\r\n" termination string >at the end of their message. Instead, they use "-ND-". Do you know >how I can setup such a server, preferably using either 'socket.py', >'serversocket.py' or 'twisted.py'? You can use the LineReceiver (or LineOnlyReceiver) from Twisted to do this quite easily: from twisted.internet import reactor from twisted.internet.protocol import ServerFactory from twisted.protocols.basic import LineOnlyReceiver class CellProtocol(LineOnlyReceiver): delimiter = '-ND-' def lineReceived(self, line): print 'got a line' f = ServerFactory() f.protocol = CellProtocol reactor.listenTCP(12345, f) reactor.run() Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
tkinter get widget option value
Hi, If I have a button widget w = Button(root, text = "Button", state = 'disabled') How can I get the value of option 'state' from the widget 'w'. I want something like -- print w.state >> to print out >> 'disabled' Thanks Rahul -- http://mail.python.org/mailman/listinfo/python-list
Suggestions for how to approach this problem?
I figured I might give myself a little project to make my life at work easier, so here's what I want to do: I have a large list of publication citations that are numbered. The numbers are simply typed in with the rest of the text. What I want to do is remove the numbers and then put bullets instead. Now, this alone would be easy enough, with a little Python and a little work by hand, but the real issue is that because of the way these citations were typed, there are often line breaks at the end of each line -- in other words, the person didn't just let the line flow to the next line, they manually pressed Enter. So inserting bullets at this point would put a bullet at each line break. So I need to remove the line breaks too, but of course not *all* of them because each reference still needs a line break between it. So I'm hoping I could get an idea or two for approaching this. I figure regular expressions will be needed, and maybe it would be good to remove the line breaks first and *not* remove a line break that comes before the numbers (because that would be the proper place for one), and then finally remove the numbers. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?
James Beck wrote: > > Yep, you must have access to better drugs than I do. > You get to hallucinate your stuff up. > Don't forget to adjust your tin beanie! Its not a beanie. He had his head tin plated. :( -- Service to my country? Been there, Done that, and I've got my DD214 to prove it. Member of DAV #85. Michael A. Terrell Central Florida -- http://mail.python.org/mailman/listinfo/python-list
Re: 1.#QNAN Solution
Thanks for you help Grant Grant Edwards wrote: > > On 2007-05-08, Greg Corradini <[EMAIL PROTECTED]> wrote: > >> I'm running descriptive stats on mileages from a database >> (float numbers, about a million records). My sum returns >> 1.#QNAN, which I understand from searching this forum is an >> error. > > Not necessarily. You've ended up with a floating point "not a > number" value (AKA a NaN). That might or might not be an > error. Whether it's an error not not depends on your input > data and your algorithm. > >> While I'm looking for help in solving this problem, I'm more >> interested in a general explanation about the cause of this >> problem. > > If you're asking how you end up with a NaN, there are several > ways to generate a NaN: > > 0/0 > > Inf*0 > > Inf/Inf > > Inf-Inf > > Almost any operation on a NaN > > http://en.wikipedia.org/wiki/NaN > http://steve.hollasch.net/cgindex/coding/ieeefloat.html > > -- > Grant Edwards grante Yow! Spreading peanut > at butter reminds me of >visi.comopera!! I wonder why? > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/1.-QNAN-Solution-tf3710941.html#a10382201 Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for how to approach this problem?
John Salerno wrote: > typed, there are often line breaks at the end of each line Also, there are sometimes tabs used to indent the subsequent lines of citation, but I assume with that I can just replace the tab with a space. -- http://mail.python.org/mailman/listinfo/python-list
Re: After the Deletion of Google Answers, . U Got Questions Fills the Gap Answering and Asking the Tough Questions
On 7 May 2007 10:45:51 -0700, [EMAIL PROTECTED] wrote: >My friend asked some tough questions >http://ugotquestions.blogspot.com/2007_05_01_archive.html >unlike yahoo answers ( Which Generates Content with Answers ) U got >questions picks only the best, Real Person Questions.,yeah so there is >this second book called E.T. and the BOOK OF THE GREEN PLANET... yeah, >what happens in it... i heard he dies, and what happend to elliot >this has been bugging me for years...so someone please tell >mehttp://ugotquestions.blogspot.com/2007_04_01_archive.html - i start >my car and shut it off 4 to 5 times it starts fine but when i continue >repeat this procedure for another 2 to 3 times then it dies. it doesnt >start at all. the headlights and all other lights dont go dim so might >not be the battery. then i have to wait for 3 to 5 minutes for it to >start again. it does crank slowly sometime then start. the alternator >was replaced 2 years ago so was the battery. the car has 129000miles >its 01 maxima. automatic. as far as i think it could be the >starter...http://ugotquestions.blogspot.com/2007/05/y-alert-yahoo- >answers_7473.html 1- if you ask anyone in the town that: Are you a >wise human? and he says yes, what you can say about him? 2- tree >mathematicians are talking about their trip to this town: 1st man >says: in my trip to the town, I ask John (a people of the town) are >you a wise human? and with his reply, I could not rcognize what is he. >2nd man says: I also ask John are you a loony human? and with his >reply, I could not recognize what is he too. 3rd man says: I also ask >John are you a wise devil? and with his...http:// >ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_7075.html >Which major should I choose before law school if I want to practice >criminal and civil law and I also want in the future be a judge.The >majors that I like are criminal justice,politcal science and >finance.But I don't know which should I choose.I already know the >speech that law schools don't care about your mayor but I want to know >which one of those three could help me more in my goals fo practice >criminal and civil law and be a judge.Thanks a lothttp:// >ugotquestions.blogspot.com/2007/05/y-alert-yahoo-answers_6058.html >Everyday I wake up to my mom yelling about something I did. All she >does is come home from work sit on the couch and watch a movie she >gets from blockbuster everyday while we are suppose to be doing >chores. She dosnt let us watch her movies becuase she pays for them,. >we dont have cable and we havnt gone grocery shopping in two months >becuase she says we dont hav the money.( while she gets take out >everyday at work and a blockbuster movie everyday to. )She told me i >cant wash my clothes for... shaw loves this. Kill the DVD player -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for how to approach this problem?
In <[EMAIL PROTECTED]>, John Salerno wrote: > I have a large list of publication citations that are numbered. The > numbers are simply typed in with the rest of the text. What I want to do > is remove the numbers and then put bullets instead. Now, this alone > would be easy enough, with a little Python and a little work by hand, > but the real issue is that because of the way these citations were > typed, there are often line breaks at the end of each line -- in other > words, the person didn't just let the line flow to the next line, they > manually pressed Enter. So inserting bullets at this point would put a > bullet at each line break. > > So I need to remove the line breaks too, but of course not *all* of them > because each reference still needs a line break between it. So I'm > hoping I could get an idea or two for approaching this. I figure regular > expressions will be needed, and maybe it would be good to remove the > line breaks first and *not* remove a line break that comes before the > numbers (because that would be the proper place for one), and then > finally remove the numbers. I think I have vague idea how the input looks like, but it would be helpful if you show some example input and wanted output. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
chdir()
Tried executing os.chdir("c:\twill") from a python Tk shell and got the error message: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'c:\twill'. I have the directory exists as I copied the name from the explorer window that was open to it. What is wrong with the syntax? thanks, jh -- http://mail.python.org/mailman/listinfo/python-list
Re: chdir()
On Tuesday 08 May 2007 22:54:39 HMS Surprise wrote: > WindowsError: [Error 123] The filename, directory name, or volume > label syntax is incorrect: 'c:\twill'. > > What is wrong with the syntax? Try 'c:\\twill' because the '\' character is the escape character. Eg: \n is new-line (aka crlf) \t is tab etc. To understand how these work, try this: print 'hello\nworld' and you get: hello world -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for how to approach this problem?
Marc 'BlackJack' Rintsch wrote: > I think I have vague idea how the input looks like, but it would be > helpful if you show some example input and wanted output. Good idea. Here's what it looks like now: 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338. 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R factor. Lancet 2:1138. 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic resistance factors in Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA synthesis on the transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician 16:50-54. 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of diverticular disease of the colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955. As you can see, any single citation is broken over several lines as a result of a line break. I want it to look like this: 1. Levy, S.B. (1964) Isologous interference with ultraviolet and X-ray irradiated bacteriophage T2. J. Bacteriol. 87:1330-1338. 2. Levy, S.B. and T. Watanabe (1966) Mepacrine and transfer of R factor. Lancet 2:1138. 3. Takano, I., S. Sato, S.B. Levy and T. Watanabe (1966) Episomic resistance factors in Enterobacteriaceae. 34. The specific effects of the inhibitors of DNA synthesis on the transfer of R factor and F factor. Med. Biol. (Tokyo) 73:79-83. 4. Levy, S.B. (1967) Blood safari into Kenya. The New Physician 16:50-54. 5. Levy, S.B., W.T. Fitts and J.B. Leach (1967) Surgical treatment of diverticular disease of the colon: Evaluation of an eleven-year period. Annals Surg. 166:947-955. Now, since this is pasted, it might not even look good to you. But in the second example, the numbers are meant to be bullets and so the indentation would happen automatically (in Word). But for now they are just typed. -- http://mail.python.org/mailman/listinfo/python-list