[Tutor] program-code dilemma

2006-07-05 Thread Damian
 Lately I've been researching about the general definitions of program
and code, and I've realized that the difference is not so convincent
(without mentioning simple and precise); that's why I'm sending this.

 My frame of reference has been very reliable (several programming
books, dictionaries, etc.), but I'll not mention it because it's not
so important for the objective of the post.

 Although, from what I've found I been able to get this conclusions.

   Program.-  A sequence of instructions that can be executed by the computer.

   Code.- Just the instructions of the program.

 Nevertheless for the few experience that I have, I know that a
program also have comments; wich at the same time could be what
differences a program from a code:

 Example:

   Program.- A sequence of instructions (with or without comments)
that can be executed
  by the computer.

 The problem is that it seems too complicated for a definition so
important and essential to start learning to program (that without
getting account of what is missing for the completeness of the
definition).

 Although, I have clear that a program is like a container, and the
code is like the internal structure that conform it. I think that a
good analogy would be: "a code is to a program, what a GUI design is
to a graphic application."

 Please, do not doubt in telling me your experiences and opinions,
preferably with different languages. Always they're well founded.

PD: This will help me to extend my frame of reference.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I Give Up. - Follow up post

2006-07-05 Thread Alan Gauld
>> 
>> ### machine_config.py
>> machines = { 'apache': ('http', 80),
>>  ## fill me in with the config of other machines
>> }
>> 
>>
>> could be used as your configuration file format.  The value portion 
>> of a

> Umm well it would work nicely . *if* the configuration never 
> changed- on the other hand, if it is to do as intended, the user of 
> the application needs to be able to add and edit the configuration.

Ok, would an XML format work better? There are several good XML
parsers available.






  etc...


or something similar?

> it is easier for a non programmer to edit a configuration that makes 
> some sort of logical sense and is easy to edit, without screwing up 
> (need to make it more "forgiving" of things like line endings, 
> spacing between name , = and value elements, etc)

The other alternative is to provide a tool for editing the file in 
which
case the format is less important sionce hiumans "never" need to
touch it.

>>> believe me I have tried dictionaries, Ive tried parsing the file 
>>> by other means, but the only way I could get results I needed was 
>>> through configparser

If you are using ini file format config parser is the right choice.
But there are other file formats and making the data match the
problem is usually the biggest breakthrough in creating clean code.
So although ini format might be simplest to maintain by non technical
users if it forces you to ju7mp through hoops mayber a slihghtly more
complex format would be better.
(An example is the XF86 setup file used in Linux which uses a
syntax somewhat like a Python dictionary mixed with an ini file)

> Another option I had was to do a web based interface for setting up 
> additional machines, etc, but web based is non-ideal for this 
> application.

How about command line tools?
Somewhat like the commonly found adduser command in Unix?

>>> Yeah, basically you carry values in a dictionary named by keyname 
>>> , but..  there have been situations where I need the key name as 
>>> the variable name , I.E. config_options[name] = value could become
>>>
>>> name = value as if it was explicitly defined that way

While I understand the usefulness of this in an interactive 
environment
I'm puzzled about how this would work in a pre-written script. If you 
are
creating variables from a config file how do you know what those 
variables
are called? If you don;lt know how can you reference them later in the
code? And if you don;t reference them of what value is the variable
name? Therefore the logical conclusion(to me!) is that you must
know what names you expect to read and therefore can use a dictionary?

Typically the examples I've seen are where people use a known
name as the root and append a sequence number:

foo1 = 43
foo2 = 45
etc

then they use a loop later in the code to reconstitute the variable 
names.

But if a list is used inside a dictionary the same effect is achieved 
with
about the  same or less work:

vars['port'].append(42)
vars['port'].append(45)
for port in vars['port']:
use port here.

The other scenario that often arises is that you know the variable 
names
you expect to find and only use those names, thus if a user causes
an unexpected name you just ignore it.

In this case you can create a dictionary of the known variable names
for validation purposes and link them to a set of helper functions 
(one
per variable) for storing the values in your variables:

Something like this:

machine = []  # list variable
port = None   # scalar value

def addMachine(value): machine.append(value)
def addPort(value):
 global port
 port = int(value)

vars = {'machine':addMachine,'port':addPort}

name = parseConfig()
if name in vars.keys():
vars[name](parseConfig())

And if you don't like the helper functions you could use lambdas:

vars = {'machine':  lambda val: machine.append(val),
   'port':lambda val: port = int(val)
  }

One you finish parsing the data you can now use machine and
port as normal variables, since that's what they are.
(Note: by converting the string value to an int I remove the issue
of extraneous spaces. Not a universal cure but a step forward)

>> Can you show us the situation you're talking about that requires 
>> this?

I'm not sure the stuff above actually addresses what you need,
but it might give some ideas? Like Danny I'd like to see an example
where the dictionary approach wouldn't work.

> Sure, I could also do this by reading a config file and parsing it , 
> but ..
>
> Say you split at the = , and the config file is like
>
> http = 80 #standard http port
>  https=443#https port
>
> Are you going to be 100% certain that when you call 
> watch_hosts[http], that you are gonna GET string "80"?
>  what about the space between http and =  ?

Yes, user errors like added spaces, mixed case, dropped or wrong
syntax(semi-colons/colons etc) are perenni

[Tutor] I Give Up. - Follow up post

2006-07-05 Thread János Juhász
Dear Brian,

The best parser is python itself :)

let's make ports.py with your original content:
http = 80
https = 443
http1 = 81
smtp = 25
smtp2 = 587

In this case, you can import ports.py with simple 
>>> import ports
>>> ports.http
80
>>> 

You don't need to define a new file format, just use the python syntax and 
it will work.
The only problem is that the format has to follow the python systax.
So the next wont work
## Ports.py
http = 80
https = 443
http1 = 81
  smtp = 25
smtp2 = 587

>>> import ports
Traceback (most recent call last):
  File "", line 1, in ?
  File "ports.py", line 5
smtp = 25
^
SyntaxError: invalid syntax
>>> 

The same method can be used for making more complex ini files.
I like it very much.
It is because Python is a dynamic language.


Yours sincerely, 
__
Janos Juhasz 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] program-code dilemma

2006-07-05 Thread Alan Gauld
> Lately I've been researching about the general definitions of 
> program
> and code, and I've realized that the difference is not so convincent
> (without mentioning simple and precise); that's why I'm sending 
> this.

It is very confusing especially for beginners, partly because both
words have multiple meanings dependant on context.

Thus:

>   Program.-  A sequence of instructions that can be executed by the 
> computer.

Is one definition. But program can have a wider application too,
as used by computer users. For example my "Word Processing
program" is actually a whole group of executable files and libraries.
All of which can be viewed as a program.

program is sometimes used to mean the end product of a programming
task, thus a DLL or other library once compiled into fina;l form might 
be
called a program.

>   Code.- Just the instructions of the program.

Usually code refers to the "source code", ie the program text
produced by a programmer or tool.

Code can also refer to "Object code" which is the preliminary output
from a compiler. This will be a binary format but one which is not
yet executable  - a link stage is needed for that to add in some
stanbdard header information and pointers to the standard libraries
used by the code - all of this extra stuff is used by the operating
system to create a running process.

And we can also get "Byte code" which is a kind of hybrid between
true object code and interpreted script. Python and Java use this
technique. The byte code for python is the compiled form found
in .pyc files.

And in a pure interpreted environment the difference between a program
and code is very hard to define since the interpreter executes the
code directly.

> Nevertheless for the few experience that I have, I know that a
> program also have comments; wich at the same time could be what
> differences a program from a code:

The comments are generally included in the definition of source code.
The compiler will remove comments so that they do not appear in the
object code (there are some exceptions to this). Comments are 
intrinsic
to an interpreted program so they a[popear inboth the code and the
program (it actually taleds the interprteter a small amount of effort
to throw away a comment. This is why modern interpreters
(Ruby, Python, Perl etc) usually compile the code into byte
code before executing it.

> The problem is that it seems too complicated for a definition so
> important and essential to start learning to program

Unfortunately computing has grown out of many different sciences
and engineering disciplines. Different terms arec used for the same
concept and the same term used for multiple concepts. It is a great
irony that a science which requires such preciusion of expression
as programming has not got a precisely defined set of terms to
describe itself!

> Although, I have clear that a program is like a container, and the
> code is like the internal structure that conform it. I think that a
> good analogy would be: "a code is to a program, what a GUI design is
> to a graphic application."

That depends on the GUI and the application environment.
Most GUIs are a combination of source code and graphical images,
its just that they use tools to generate it.

A better analogy might be that the source code is like the
sheet music that a musician processes to produce a tune.

This confusion of terminology is one of the reasons I spend a lot of
time in my tutorial attempting to clarify exactly what these different
terms mean in their various contexts.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two Newbile Questions: porting drawmap.c, & Python as a lifetime language

2006-07-05 Thread Alan Gauld
I missed the original post but I'll chip in anyway...

> [EMAIL PROTECTED] wrote:
>> 2. Seeing Python hailed as a good language for learning 
>> programming,  how do you rate it as a lifetime language? (I can 
>> imagine that many people have settled into one language for doing 
>> the remainder of their life's work.

There is no such thing as a lifetime language (unless maybe its COBOL
or Fortran) because lanmguages are conmstantly changing.

When I started programming in the mid 70's I was using BASIC and
Assembler. Then when I went to University (as an adult student) I was
tought Pascal and C. (While there I also came across Smalltalk and
OOP but they weren't part of the core curriculum) After some years
using C (and some Lisp) at work I needed to learn Objective C and
then C++ which became my prime language for about 5 years.
(During all this time my personal projects were being done in
Pascal or Lisp  -- or Tcl which I'd found by accident...).

Nowadays almost all my work is done in either Python,
Pascal (Windows GUIs), Objective C (for my Apple) or Java.
I only use Java while at work - I detest it as a language.
But I've used over 30 languages in total over the years,
some I've forgotten, others I still dabble with (such as Smalltalk
and Lisp).

The language is pretty well irrelevant, you can do almost
anything in almost any language. The important thing is to
understand how to structure code and to lay it out clearly
for ease of maintenance. You can learn almost any new
language in less than a week. Learning all the common idioms
may take a few months.

>> I am pressed, I will choose Perl at this point.)

Perl is just too lmited in scale for my purposes, it's great for
small scripts and up to a thousand lines or so of code.
But I had to maintain a 5000 line Perl program (ie quite small)
and it was not much fun - too many different styles used
and inconsistent design patterns, something Perl actively
encourages.

Once you get to large programs, say over 100,000 lines,
and certainly over a million you need a language with good
support for that kind of work. ADA, Eiffel, COBOL,
(and just maybe C++)  etc

The main reason COBOL has remained the most commonly
used language for large projects is its superlative support for
that kind of environment. Small COBOL programs are a pain
because you have to do so much to set it up, but on big projects
those very same constraints become a godsend. It's interesting
to note that most of the very big projects that fail have tried to use
other languages than COBOL and run into problems. COBOL isn't
necessary but it has a huge culture behind it for these kinds of
jobs - we have learned how to do it in COBOL, we are still
learing in Java, C++ etc.

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two Newbile Questions: porting drawmap.c, & Python as a lifetime language

2006-07-05 Thread Python
On Tue, 2006-07-04 at 16:37 -0500, [EMAIL PROTECTED] wrote:
> I am seeking opinions from seasoned veterans on the following two
> questions:
> 
You're getting plenty of replies.  Here's a bit more.

You're probably aware that ESRI has adopted Python for scripting with
their applications.

> 1. What's involved in a port of a C program into Python?  (drawmap is 
> offered in a number of linux distributions btw.)

http://ldots.org/pyrex-guide/
pyrex integrates Python and C into a hybrid language that might be
useful for porting existing C code.

> 
> 2. Seeing Python hailed as a good language for learning programming,  
> how do you rate it as a lifetime language? (I can imagine that many
> people have settled into one language for doing the remainder of their
> life's work. If I am pressed, I will choose Perl at this point.)

I think it is easier to learn to write complex applications in Python
than Perl.  Certainly Perl is rich in features and capabilities, but I
find the rules for keeping everything straight are more complex than
Python's and the possibility of uncaught errors in Perl seems much
higher than in Python.  My favorite example of this is:

cat test.pl
if ("abc" == "def") {print "all letters are =\n"};

perl test.pl
all letters are =

)

 
== is the numeric comparison.  The strings are evaluated to numbers and
both are treated as zero. 0 = 0 is true.
"abc" eq "def" will behave as expected.  Python has its own pitfalls,
but I find the Python pitfalls much easier to live with.

Python continues to evolve while preserving backwards compatibility.
Recent additions such as list comprehension, generators, generator
expressions, display a growth and dynamism that I think will continue to
make Python a great choice among programming languages into the future.

(You didn't really think you'd find people on this list urging you to
use Perl.)

-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] More assistance with queues and global variables

2006-07-05 Thread Tino Dai
Hi All, My project is almost working (and without global variables!), and there is one more hurdle that I want to jump. That is using the SocketServer module and passing a queue (or for that matter any kind of variable) to the handle method. I took a look at SocketServer to see what classes I need to override/extend, and see that I will be need to extending a couple of inits and methods out of the TCPServer and the BaseServer class. I don't see an easy way to do this [passing in a variable] , so I figured that I would extend the classes. I can to realize that I would be extending not only the base TCPServer class but also the BaseServer class. My question is: When I extend those classes, can I put all the methods from both of the classes into my own extended class or would I need to do something funky?
-TinoExample:class BaseServer:       def __init__(self, server_address, RequestHandlerClass):    """Constructor.  May be extended, do not override."""    
self.server_address = server_address    self.RequestHandlerClass = RequestHandlerClass   def handle_request(self):    """Handle one request, possibly blocking."""
    try:    request, client_address = self.get_request()    except socket.error:    return    if self.verify_request(request, client_address):    try:    
self.process_request(request, client_address)    except:    self.handle_error(request, client_address)    self.close_request(request)class TCPServer(BaseServer):
   address_family = socket.AF_INET    socket_type = socket.SOCK_STREAM    request_queue_size = 5    allow_reuse_address = False    def __init__(self, server_address, RequestHandlerClass):
    """Constructor.  May be extended, do not override."""    BaseServer.__init__(self, server_address, RequestHandlerClass)    self.socket = socket.socket(self.address_family
,    self.socket_type)    self.server_bind()    self.server_activate()""" Above are the classes that I will need to extend/overrideclass MyTCPServer (
SockertServer.TCPServer): """Would all the extended methods go in this class or would look different? And how would I get the queue up to BaseServer without overriding TCPServer's init?-Tino

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More assistance with queues and global variables

2006-07-05 Thread Kent Johnson
Tino Dai wrote:
> Hi All,
>
>  My project is almost working (and without global variables!), and 
> there is one more hurdle that I want to jump. That is using the 
> SocketServer module and passing a queue (or for that matter any kind 
> of variable) to the handle method. I took a look at SocketServer to 
> see what classes I need to override/extend, and see that I will be 
> need to extending a couple of inits and methods out of the TCPServer 
> and the BaseServer class. I don't see an easy way to do this [passing 
> in a variable] , so I figured that I would extend the classes. I can 
> to realize that I would be extending not only the base TCPServer class 
> but also the BaseServer class. My question is: When I extend those 
> classes, can I put all the methods from both of the classes into my 
> own extended class or would I need to do something funky?
If I understand correctly, you want the server to have a queue that is 
shared among requests. You can do this without replacing any of the 
functions below. I would pass the queue to the __init__() method of your 
server class, override finish_request() to pass the queue to the request 
handler, the request handler __init__() just saves the queue for access 
by the handle() method. Something like this:

class MyServer(TCPServer):
  def __init__(self, server_address, RequestHandlerClass, queue):
TCPServer.__init__(self, server_address, RequestHandlerClass)
self.queue = queue

  def finish_request(self, request, client_address):
"""Finish one request by instantiating RequestHandlerClass."""
self.RequestHandlerClass(request, client_address, self, self.queue)


class MyRequest(BaseRequestHandler):
  def __init__(self, request, client_address, server, queue):
BaseRequestHandler.__init__(self, request, client_address, server)
self.queue = queue

  def handle(self):
# do something with self.queue

Kent
>
> -Tino
>
> Example:
>
> class BaseServer:
>def __init__(self, server_address, RequestHandlerClass):
> """Constructor.  May be extended, do not override."""
> self.server_address = server_address
> self.RequestHandlerClass = RequestHandlerClass
>
>def handle_request(self):
> """Handle one request, possibly blocking."""
> try:
> request, client_address = self.get_request()
> except socket.error:
> return
> if self.verify_request(request, client_address):
> try:
> self.process_request(request, client_address)
> except:
> self.handle_error(request, client_address)
> self.close_request(request)
>
>
> class TCPServer(BaseServer):
>address_family = socket.AF_INET
>
> socket_type = socket.SOCK_STREAM
>
> request_queue_size = 5
>
> allow_reuse_address = False
>
> def __init__(self, server_address, RequestHandlerClass):
> """Constructor.  May be extended, do not override."""
> BaseServer.__init__(self, server_address, RequestHandlerClass)
> self.socket = socket.socket(self.address_family ,
> self.socket_type)
> self.server_bind()
> self.server_activate()
>
> """ Above are the classes that I will need to extend/override
>
> class MyTCPServer ( SockertServer.TCPServer):
>  """Would all the extended methods go in this class or would look 
> different? And how would I get the queue up to BaseServer without 
> overriding TCPServer's init?
>
> -Tino
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More assistance with queues and global variables

2006-07-05 Thread Tino Dai
On 7/5/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Tino Dai wrote:> Hi All,>>  My project is almost working (and without global variables!), and> there is one more hurdle that I want to jump. That is using the> SocketServer module and passing a queue (or for that matter any kind
> of variable) to the handle method. I took a look at SocketServer to> see what classes I need to override/extend, and see that I will be> need to extending a couple of inits and methods out of the TCPServer
> and the BaseServer class. I don't see an easy way to do this [passing> in a variable] , so I figured that I would extend the classes. I can> to realize that I would be extending not only the base TCPServer class
> but also the BaseServer class. My question is: When I extend those> classes, can I put all the methods from both of the classes into my> own extended class or would I need to do something funky?
If I understand correctly, you want the server to have a queue that isshared among requests. You can do this without replacing any of thefunctions below. I would pass the queue to the __init__() method of your
server class, override finish_request() to pass the queue to the requesthandler, the request handler __init__() just saves the queue for accessby the handle() method. Something like this:class MyServer(TCPServer):
  def __init__(self, server_address, RequestHandlerClass, queue):TCPServer.__init__(self, server_address, RequestHandlerClass)self.queue = queue  def finish_request(self, request, client_address):
"""Finish one request by instantiating RequestHandlerClass."""self.RequestHandlerClass(request, client_address, self, self.queue)class MyRequest(BaseRequestHandler):
  def __init__(self, request, client_address, server, queue):BaseRequestHandler.__init__(self, request, client_address, server)self.queue = queue  def handle(self):# do something with self.queue
KentDo you ever wish that you could pull back an email? This is one of those times. I got the same exact solution as you about 30 minutes ago. I did have to switch the lines in BaseRequestHandler and 
self.queue for it to work. Thanks!-Tino
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] modbus communication with python?

2006-07-05 Thread Jeff Peery
Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks.Jeff 
		Do you Yahoo!? Everyone is raving about the  all-new Yahoo! Mail Beta.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] modbus communication with python?

2006-07-05 Thread Jeff Peery
Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks.Jeff 
		How low will we go? Check out Yahoo! Messenger’s low  PC-to-Phone call rates.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] modbus communication with python?

2006-07-05 Thread Jason Massey
Googling for modbus python turned up:https://lintouch.org/repos/lintouch/lsp-modbus/trunk/tests/
On 7/5/06, Jeff Peery <[EMAIL PROTECTED]> wrote:
Hello, I need to talk read write to a modbus so that I can work with a PLC. I have not a clue how this all works. does python have a modbus module or where might I look to find how to do this? thanks.
Jeff 
		How low will we go? Check out Yahoo! Messenger's low 
 PC-to-Phone call rates.
___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I Give Up. - Follow up post

2006-07-05 Thread Brian Gustin

> 
> The other alternative is to provide a tool for editing the file in which
> case the format is less important sionce hiumans "never" need to
> touch it.
> 
Heh. good analysis.. now I feel a little dumb- I should have thought of 
this *LONG* ago. yeah I knew about the xml parser , and how to do xml 
markup (it's one of the methods we use on intranet communications 
channels for certain scriptable tasks) ...

My sticking point was, I wanted it to be super easy for a newbie or 
beginner or "sysadmin trainee" to install and set up the monitoring 
without needing to know much more than maybe basic command line..

That's when it finally hit me (thanks to your commentary below) , why 
use a config file at all? all I have to do is create a simple "setup" 
utility that will write the "configuration" data I need in *correct and 
perfect* python syntax, which I can simply reload, or re-import into the 
daemon ... no need to even have a text editor, all I need is a little 
shell script or python utility to ask for and wait for the user's input 
at each prompt, and check data at each step to get it right..

Yep, I think I was *absolutely* over-thinking the issue here. :)

> How about command line tools?
> Somewhat like the commonly found adduser command in Unix?
> 
 Yeah, basically you carry values in a dictionary named by keyname , 
 but..  there have been situations where I need the key name as the 
 variable name , I.E. config_options[name] = value could become

 name = value as if it was explicitly defined that way
> 
> 
> While I understand the usefulness of this in an interactive environment
> I'm puzzled about how this would work in a pre-written script. If you are
> creating variables from a config file how do you know what those variables
> are called? If you don;lt know how can you reference them later in the
> code? And if you don;t reference them of what value is the variable
> name? Therefore the logical conclusion(to me!) is that you must
> know what names you expect to read and therefore can use a dictionary?
> 
> I'm not sure I understand where exactly you are having the problems
> (other than the admnittedly poor configparser documentation! - the
> quality of python docs tends to be directly proportional to its frequency
> of use and inversely proportional to age - more recent modules tend to
> be better documented than ancient ones. Unfortunately for you config
> parser doesn't seem to be used that much and has been there for ever!)

Yeah this kind of confused the whole issue- and snowballed a little 
bit.. got off track ..

Point originally was, I wanted to be able to read in a config file as a 
name => value pair , and then actually have a variable named by name in 
the script, which you cannot do using a dictionary, you could use the 
key, yes, but at the time it didnt make sense to me to have 4 or 5 
dictionaries laying around in memory when they only have one or two keys 
, and I wanted to use single variables..

Comes from wanting to minimize how much stuff I have loaded into memory, 
and my impression is, a dictionary of 2 elements (name:value pairs)
takes up more space in memory than two single variables (name points to 
value in memory), and the conversation just ultimately got mixed up, and 
I couldnt even remember, in the end why I needed the variable names Vs. 
a dict, until I went back to SubVersion and dug out the first 2 versions 
of my code :)

(Got to love Revision control systems! )

Anyhow, that's now a moot point. :) I have no valid reason at this point 
to insist on knowing variable names.

However to make a point, my original thinking was along the lines of a 
way to do variable variables, (there are certain instances where they 
can be handy) , however since python has no $ to start a variable, I saw 
no way it was possible... Oh well

I have yet to get back in this project, it's working as needed in Perl 
(with a somewhat kludgy configuration, and really, IMHO, more code than 
is really necesary for something so simple as this) but it does the job, 
and I have other things I must do :)

> 
> HTH,
> 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 
> !DSPAM:44ab7d4d293088057919449!
> 
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ANN: (Intensive) Intro to Python course, Aug 16-18, San Francisco

2006-07-05 Thread w chun
Greetings!

Below is the announcement we've just made this morning to CLP about
our upcoming Python course.  Please forward this msg to anyone whom
you think would be interested or would benefit from Python training
courses.  This includes Plone, Zope, Django, TurboGears, and Mailman
groups as well.

http://mail.python.org/pipermail/python-list/2006-July/350187.html

Thanks for your time!
-Wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
   http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I Give Up. - Follow up post

2006-07-05 Thread Alan Gauld
> Comes from wanting to minimize how much stuff I have loaded into 
> memory, and my impression is, a dictionary of 2 elements (name:value 
> pairs)
> takes up more space in memory than two single variables (name points 
> to value in memory),

Dangerous assumption since Python ultimately uses dictionaries for 
*all*
its variables, its just that some of them are somewhat hidden from 
view...
So evern if you declare

foo = 42

it gets turned into

local_vars[foo'] = 42

or something similar

So by declaring your own dictionary the only overhead is the extra
dictionary entry to point at your explicit doictionary.

Dictionaries in Python are pretty efficient since they are
the bedrock of the interpreter.

HTH,

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] what %s=%s means?

2006-07-05 Thread 韩宪平
I realy new to python.I try on learning it by code examples.The
following one from "Dive into python":

def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.

Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)

Whant ";"means
%s=%s?
join?
>>>help(items) no matched.
Where can i find stuff helpful?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what %s=%s means?

2006-07-05 Thread Ismael Garrido
韩宪平 wrote:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
> """Build a connection string from a dictionary of parameters.
>
> Returns string."""
> return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
>
> if __name__ == "__main__":
> myParams = {"server":"mpilgrim", \
> "database":"master", \
> "uid":"sa", \
> "pwd":"secret" \
> }
> print buildConnectionString(myParams)
>
> Whant ";"means
> %s=%s?
> join?
>   
 help(items) no matched.
 
> Where can i find stuff helpful?

"%s" % (param) is called string formatting. It builds a new string from 
a format (the first part, that looks like a regular string with %s) and 
the arguments. The idea is that the %s get replaced with the value of 
the params.

String formatting allows many complex uses (for example, format decimal 
numbers with 3 digits before the . and 2 after). If you want to learn 
more about this you should look for the python docs or some tutorial 
(Google is your Friend). Alan Gauld's tutorial is really good :) 
http://www.freenetpages.co.uk/hp/alan.gauld/ (though it seems it doesn't 
cover this particular topic).

";".method is a string method. Strings ("") are objects, and as such 
they can be called (look for Object Oriented Programming if you don't 
know what an object is). -Alan's tutorial does have this topic :) -. The 
idea is basically that you ask a string to do something (in this case, 
join the elements in the list with itself in the middle).


Ismael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] program-code dilemma

2006-07-05 Thread Senthil_OR
-Original Message-
From:  Damian
Sent: Wednesday, July 05, 2006 12:36 PM
To: tutor@python.org
Subject: [Tutor] program-code dilemma

 Although, from what I've found I been able to get this conclusions.

   Program.-  A sequence of instructions that can be executed by the
computer.

   Code.- Just the instructions of the program.

 The problem is that it seems too complicated for a definition so
important and essential to start learning to program (that without
getting account of what is missing for the completeness of the
definition).
___

Damian:
I don't understand how much 'programming' will you learn by
understanding the difference between the terminologies of 'code' and
'program'.
My suggestion will be ignore that, see them as one and the same and
carry forward with learning other things and concepts. I doubt, you will
be confused with any concept which is exaplained using either of the
terminologies.

Frankly speaking, I don't know the difference between 'code' and the
'program'. For me,  its synonymous. I write Code. I do programming.I
program.

Do you get it?

-- 
Senthil

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what %s=%s means?

2006-07-05 Thread w chun

On 7/5/06, Ismael Garrido <[EMAIL PROTECTED]> wrote:

韩宪平 wrote:
>
> Returns string."""
> return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
>
> Whant ";"means
> %s=%s?
> join?
>
 help(items) no matched.

> Where can i find stuff helpful?

"%s" % (param) is called string formatting.



xian-ping,

what ismael says is correct... it means string formatting.  for
example %s means string, %d means integer, etc.  you use those format
strings, then give it real objects, for example, a string or an
integer, and it will format it all into one larger string.

for extra help in Chinese, you can refer to:

1. Chinese links from Python.org:
http://www.python.org/doc/nonenglish/#chinese

2. my book, "Core Python Programming" was translated into Chinese...
it is somewhat dated (until the new one comes out), but is relevant
for your question:

http://www.china-pub.com/computers/common/info.asp?id=3097

good luck!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
   http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] what %s=%s means?

2006-07-05 Thread Andre Engels
2006/7/6, 韩宪平 <[EMAIL PROTECTED]>:
> I realy new to python.I try on learning it by code examples.The
> following one from "Dive into python":
>
> def buildConnectionString(params):
> """Build a connection string from a dictionary of parameters.
>
> Returns string."""
> return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

> Whant ";"means

";" simply means the string consisting of the one character ;

> %s=%s?

You'll have to look at the more complete expression here:
"%s=%s" % (k, v)

%s then means, in this string replace me by the next element in the
tuple following the %. Thus, the above will evaluate to the string
consisting of the string representation of k followed by the character
= followed by the string representation of v.

Some examples to make it clearer:
"I am %s"%("John")
will evaluate to:
"I am John"

"%s is a number"%(7)
will evaluate to:
"7 is a number", because the stuff in the tuple doesn't need to be a string

If x equals 1 and y equals 2, "%s+%s=%s"%(x,y,x+y)
will evaluate to:
"1+2=3"

> join?

Join is a method of a string. Its syntax is:
x.join(y)
where x must be a string and y a sequence of strings. It denotes a
string, consisting of the strings in y, with x between each pair.
Again, a few examples will make it more clear:

" ".join(["I","am","a","boat"])
evaluates to:
"I am a boat"

"-abc-".join(["I","am","a","boat"])
evaluates to:
"I-abc-am-abc-a-abc-boat"

and
"".join(["I","am","a","boat"])
evaluates to:
"Iamaboat"

-- 
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] time(duration) formats & basic time math query

2006-07-05 Thread kevin parks
I have been handed a huge number of documents which have hundreds of  
pages of times and durations, all calculated and notated by several  
different people over the course of many years. Sadly, no made any  
guidelines at all about how this work would proceed and all the  
documenters had their own ideas about how times/durations would be  
specified so the doc are a mess. Furthermore the person i work for  
changes her mind every 15 minutes so i have no idea what she will  
want at any given moment. This sounds to me like a job for Python  


Essentially, I am trying to do 2 things:

move fluidly between different duration formats (take any, specify  
and display any). Such as:

pure miliseconds
seconds. msec
mm:ss.msec
hh:mm:ss.msec

So the input doc would be grepped for times and i could just  
uncomment the line i need and get he format my boss wants at this  
particular moment.
So a recording that is 71 minutes and 33 seconds could be printed as:
4293 seconds
71:33.
01:11.33.  or whatever

also i need to be able to adjust start times, durations, and end  
times which means doing a little time math.
Like if a recording is 71 minute and 33 seconds.. but there are  
several sonic events in that recording and i
need to specify the duration, or start time etc of those individual  
events... then i need to subtract... Additionally i
know that i will need to subtract pure minutes from an hh:mm format

I having a real hard time getting my head round the labyrinthian  
datetime module in the docs (i am guessing
that this is what i should use). I wonder if anyone could give me a  
hand and point me in the right direction.

cheers,

kevin


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] time(duration) formats & basic time math query

2006-07-05 Thread Dustin J. Mitchell
kevin parks wrote:
> I have been handed a huge number of documents which have hundreds of  
> pages of times and durations, all calculated and notated by several  
> different people over the course of many years. Sadly, no made any  
> guidelines at all about how this work would proceed and all the  
> documenters had their own ideas about how times/durations would be  
> specified so the doc are a mess. Furthermore the person i work for  
> changes her mind every 15 minutes so i have no idea what she will  
> want at any given moment. This sounds to me like a job for Python  
> 
> 
> Essentially, I am trying to do 2 things:
> 
> move fluidly between different duration formats (take any, specify  
> and display any). Such as:
> 
> pure miliseconds
> seconds. msec
> mm:ss.msec
> hh:mm:ss.msec
> 
> So the input doc would be grepped for times and i could just  
> uncomment the line i need and get he format my boss wants at this  
> particular moment.
> So a recording that is 71 minutes and 33 seconds could be printed as:
> 4293 seconds
> 71:33.
> 01:11.33.  or whatever
> 
> also i need to be able to adjust start times, durations, and end  
> times which means doing a little time math.
> Like if a recording is 71 minute and 33 seconds.. but there are  
> several sonic events in that recording and i
> need to specify the duration, or start time etc of those individual  
> events... then i need to subtract... Additionally i
> know that i will need to subtract pure minutes from an hh:mm format
> 
> I having a real hard time getting my head round the labyrinthian  
> datetime module in the docs (i am guessing
> that this is what i should use). I wonder if anyone could give me a  
> hand and point me in the right direction.

datetime may do the trick for you, but I would use it only for its
conversional abilities -- it sounds like this is a good time for you to
implement your own "Duration" class, with some kind of flexible system
for parsing (possibly even recognizing) different time formats, and
producing different time formats, e.g.,

class Duration:
  def __init__(self, duration_string, format='guess'):
if format == 'guess': format = self.guess_format(duration_string)
self.format = format

parse, output = self.format_fns[self.format]
self.seconds = parse(self, duration_string)

  def output(self, format='original'):
if format == 'original': format = self.format
parse, output = self.format_fns[format]
return output(self)

  def parse_milliseconds(self, duration_string): ...
  def output_milliseconds(self): ...
  def parse_fracseconds(self, duration_string): ...
  def output_fracseconds(self): ...

  format_fns = {
'milliseconds' : (parse_milliseconds, output_milliseconds),
'fracseconds' : (parse_fracseconds, ouput_fracseconds),
  }

Then you can just parse the thing up like this:

  durations = [ Duration(line.strip()) for line in f.xreadlines() ]

and print it out like this:

  for dur in durations:
print dur.output('milliseconds')

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor