Re: weird embedding problem

2007-12-07 Thread grbgooglefan
On Dec 7, 2:01 pm, DavidM <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm embedding python in a C prog which is built as a linux shared lib.
>
> The prog is linked against libpython, and on startup, it calls
> Py_Initialize().
>
> The prog imports a pure-python script. The script starts up ok, but when
> it imports the 'math' module, the import fails with:
>
> Traceback (most recent call last):
>   File "/home/david/work/video/myprogs/dvedit/test/frei0rfx1.py", line 10, in 
> 
> import math
> ImportError: /usr/lib/python2.5/lib-dynload/math.so: undefined symbol: 
> PyExc_ValueError
> Failed to import math
>
> Any ideas of how to work around this?
>
> Please note - the program I'm writing *must* be built as a shared lib, so
> the usual practice of 'extend, don't embed' is just not an option here.
>
> Thoughts?
>
> Cheers
> D

the math module above is failing to load because of: "undefined
symbol: PyExc_ValueError"
You may have to import some other module before loading math.
Try doing nm on libraries in /usr/lib/python2.5/lib-dynload & see
which one has this symbol (a function) in defined state ("T").

Also, verify if your script works fine out of the C program - may be
at python prompt.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I embed Windows Python in C# or VC++?

2007-12-07 Thread grbgooglefan
On Dec 7, 3:07 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Fri, 07 Dec 2007 01:24:57 -0300, grbgooglefan <[EMAIL PROTECTED]>  
> escribió:
>
>
>
>
>
> > On Dec 7, 12:17 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
> >> En Thu, 06 Dec 2007 23:27:15 -0300, grbgooglefan <[EMAIL PROTECTED]>
> >> escribió:
>
> >> > I want to use Python's Windows (python25.dll) version to embed in my
> >> > C# (or atleast VC++) program for performing syntax checks on the
> >> > Python expressions which are later supposed to be evaluated at runtime
> >> > by another C++ program [...]> Can I start doing the development using  
> >> the include, lib & the
> >> > python25.dll files availale after installing this MSI?
>
> >> Yes. You don't require the source package to embed Python and use the  
> >> API in your programs.
>
> > Does it mean, I can embed Python in C# as well with the same APIs?
>
> No; you can use the Python API in a native C++ application (the Python  
> code is plain C, but all the include files have the 'extern "C" {}'  
> declarations). For .NET there are IronPython and PythonNet, but I cannot  
> comment on them, surely someone else may help. See  
> http://www.python.org/about/
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -

Hello, Anybody else out there has used Python from C#?
-- 
http://mail.python.org/mailman/listinfo/python-list


Any simpler way to do this

2007-12-07 Thread Lars Johansen
I have a function that looks like this:

def Chooser(color):

if color == "RED":
x = term.RED
elif color == "BLUE":
x = term.BLUE
elif color == "GREEN":
x = term.GREEN
elif color == "YELLOW":
x = term.YELLOW
elif color == "CYAN":
x = term.CYAN
elif color == "MAGENTA":
x = term.MAGENTA
return x


Wouldn there been easier if I could just skip all the "*if's" and just
"return term.color", however this gives a syntax error, are there any
clever way to do this ?
-- 
Lars Johansen <[EMAIL PROTECTED]>

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird embedding problem

2007-12-07 Thread Graham Dumpleton
On Dec 7, 5:01 pm, DavidM <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I'm embedding python in a C prog which is built as a linux shared lib.
>
> The prog is linked against libpython, and on startup, it calls
> Py_Initialize().
>
> The prog imports a pure-python script. The script starts up ok, but when
> it imports the 'math' module, the import fails with:
>
> Traceback (most recent call last):
>   File "/home/david/work/video/myprogs/dvedit/test/frei0rfx1.py", line 10, in 
> 
> import math
> ImportError: /usr/lib/python2.5/lib-dynload/math.so: undefined symbol: 
> PyExc_ValueError
> Failed to import math
>
> Any ideas of how to work around this?
>
> Please note - the program I'm writing *must* be built as a shared lib, so
> the usual practice of 'extend, don't embed' is just not an option here.
>
> Thoughts?

Are you actually linking your C program against the Python library?

Graham

-- 
http://mail.python.org/mailman/listinfo/python-list


[NEWB] Dictionary instantiation?

2007-12-07 Thread Matt_D
Hello there, this is my first post to the list. Only been working with
Python for a few days. Basically a complete newbie to programming.

I'm working with csv module as an exercise to parse out a spreadsheet
I use for work.(I am an editor for a military journalism unit) Not
trying to do anything useful, just trying to manipulate the data.
Anyway, here's the code I've got so far:

import csv
import string
import os

#Open the appropriate .csv file
csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))

#Create blank dictionary to hold {[author]:[no. of stories]} data
story_per_author = {}

def author_to_dict(): #Function to add each author to the dictionary
once to get initial entry for that author
for row in csv_file:
author_count = row[-1]
story_per_author[author_count] = 1

#Fetch author names
def rem_blank_authors(): #Function to remove entries with '' in the
AUTHOR field of the .csv
csv_list = list(csv_file) #Convert the open file to list format
for e-z mode editing
for row in csv_list:
author_name = row[-1]
if author_name == '': #Find entries where no author is listed
csv_list.remove(row) #Remove those entries from the list

def assign_author_to_title(): #Assign an author to every title
author_of_title = {}
for row in csv_file:
title = row[3]
author = row[-1]
author_of_title[title] = author


assign_author_to_title()
print author_of_title

--

Ok, the last two lines are kind of my "test the last function" test.
Now when I run these two lines I get the error:

Traceback (most recent call last):
  File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
  File "D:\Python25\csv_read.py", line 33, in 
print author_of_title
NameError: name 'author_of_title' is not defined

I am guessing that the author_of_title dict does not exist outside of
the function in which it is created? The concept of instantiation is
sort of foreign to me so I'm having some trouble predicting when it
happens.

If I call the assign_author_to_title function later, am I going to be
able to work with the author_of_title dictionary? Or is it best if I
create author_of_title outside of my function definitions?

Clearly I'm just stepping through my thought process right now,
creating functions as I see a need for them. I'm sure the code is
sloppy and terrible but please be gentle!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any simpler way to do this

2007-12-07 Thread Christian Heimes
Lars Johansen wrote:
> I have a function that looks like this:
> 
> def Chooser(color):
> 
> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x

return getattr(term, color, color)

:)

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any simpler way to do this

2007-12-07 Thread Bruno Desthuilliers
Lars Johansen a écrit :
> I have a function that looks like this:
> 
> def Chooser(color):


Bad naming (noun instead of a verb) and not conformant to PEP 08 
(function names should be all_lower)


> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x


What do you think will happen if I call it like this:
Chooser(42)

(if you answered 'will raise a NameError', then you're correct).

> 
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?

getattr(obj, name) is your friend.
-- 
http://mail.python.org/mailman/listinfo/python-list


ftplib.nlst gives error on empty directory

2007-12-07 Thread loial
Trying to use ftplib.FTP.nlst()  method to list the files in
a directory on a FTP server.

It works fine except when there are no files in the directory. Then it
gives the error

ftplib.error_perm: 550 No files found.

How can I handle this cleanly?



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I embed Windows Python in C# or VC++?

2007-12-07 Thread sturlamolden
On 7 Des, 08:07, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> > Does it mean, I can embed Python in C# as well with the same APIs?
>
> No; you can use the Python API in a native C++ application (the Python
> code is plain C, but all the include files have the 'extern "C" {}'
> declarations). For .NET there are IronPython and PythonNet, but I cannot
> comment on them, surely someone else may help. See  
> http://www.python.org/about/

The answer is YES. C# can access C functions exported by any DLL with
platform invoke. Since the Python C API is plain C and not C++ you can
gain access to it from C#. Import System.Runtime.InteropServices and
write wrappers like

[DllImport("Python25.dll"), CallingConvention=CallingConvention.Cdecl]
public static void Py_Initialize();

etc.


You can also combine C++ and C# in a project in MS Visual Studio, if
you prefer to access Python from C++. That way you don't have to write
platform invoke wrappers for the Python C API.




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Bruno Desthuilliers
Matt_D a écrit :
(snip whole posts)

Please Matt do the world a favour : don't repost the whole damn think 
just to add a couple lines !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Bruno Desthuilliers
Matt_D a écrit :
(snip)
> Another newb question, same project:
> 
> #Fetch author names
> def rem_blank_authors(): #Function to remove entries with '' in the
> AUTHOR field of the .csv
> csv_list = list(csv_file) #Convert the open file to list format
> for e-z mode editing
> for row in csv_list:
> author_name = row[-1]
> if author_name == '': #Find entries where no author is listed
> csv_list.remove(row) #Remove those entries from the list
> return csv_list

The return statement being in the for block, this will always return at 
the end of the first iteration. Which is obviously not what you want !-)

Hint : the return statement should be at the same indentation level as 
the for statement.

Also, modifying a sequence in place while iterating over it is a *very* 
bad idea. The canonical solution is to build a new sequence based on the 
original. or, if working on an iterator, to write a filtering iterator, ie:

def rem_blank_authors(csv_file):
 for row in csv_list:
 author_name = row[-1]
 if author_name.strip() != '':
yield row


Now you can use it as:

for row in rem_blank_authors(csv_file)):
   assert(row[-1].strip() != '')


> def author_to_dict():

def author_to_dict(csv_file):

> for row in csv_file:

for row in rem_blank_authors(csv_file)):
> author_count = row[-1]

Why naming it 'author_count' when it's the author name ?

   author_name = row[-1]

You're inside a fonction, which has it's own namespace, so this won't 
clash with local names of other functions !-)

> if author_count in story_per_author:
> story_per_author[author_count] += 1
> else:
> story_per_author[author_count] = 1

  if author_name in story_per_author:
  story_per_author[author_name] += 1
  else:
  story_per_author[author_name] = 1

Not very important but might be good to know: if the general case is 
that each author is found several times in a csv file, you might get 
better results using a try/except block:

  try:
  story_per_author[author_name] += 1
  except KeyError:
  story_per_author[author_name] = 1


> return story_per_author

> 
> The solution provided for my previous post worked out. Now I'm testing
> the author_to_dict function, modified to get an accurate count of
> stories each author has written. Now, if I call rem_blank_authors,
> story_per_author == {}. But if I #comment out that line, it returns
> the expected key values in story_per_author. What is happening in
> rem_blank_authors that is returning no keys in the dictionary?
> 

You already consumed the whole csv_file iterator.

> I'm afraid I don't really understand the mechanics of "return" 

It's an entirely different problem.

> and
> searching the docs hasn't yielded too much help since "return" is such
> a common word (in both the Python 2.5 docs and Dive Into Python).

heck, not only in Python - this is really CS101.

For short: the return statemement terminates the function execution. 
Also, the object (if any) following the return statement will be the 
"return value" of the function, that is the value returned to the 
caller. If no value is given, the return value will be the None object 
(which is Python's generic 'null' value). If the function ends without a 
n explicit return, it's return value will also be None.

> I
> realize I should probably RTFM, but honestly, I have tried and can't
> find a good answer. Can I get a down and dirty explanation of exactly
> what "return" does? And why it's sometimes "return" and sometimes it
> has an argument? (i.e. "return" vs. "return author_of_title")

cf above.

Dummy exemples:

def add(num1, num2):
   return num1 + num2

x = add(1, 2)
print x

def say_hello_to_jim(name):
if name == 'jim':
  return "Hello Jim"
# implicit 'return None' here

names = ['bob', 'will', 'jim', 'al']
for name in names:
   print say_hello_to_jim(name)

HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> def lookupdmo(domain):
> lines = open('/etc/virtual/domainowners','r').readlines()
> lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
> lines]
> lines = [ x for x in lines if len(x) == 2 ]
> d = dict()
> for line in lines:
> d[line[0]]=line[1]
> return d[domain]

Just some minor points without changing the basis of what you have done 
here:

Don't bother with 'readlines', file objects are directly iterable.
Why are you calling both lstrip and rstrip? The strip method strips 
whitespace from both ends for you.

It is usually a good idea with code like this to limit the split method to 
a single split in case there is more than one colon on the line: i.e. 
x.split(':',1)

When you have a sequence whose elements are sequences with two elements 
(which is what you have here), you can construct a dict directly from the 
sequence.

But why do you construct a dict from that input data simply to throw it 
away? If you only want 1 domain from the file just pick it out of the list. 
If you want to do multiple lookups build the dict once and keep it around.

So something like the following (untested code):

from __future__ import with_statement

def loaddomainowners(domain):
with open('/etc/virtual/domainowners','r') as infile:
pairs = [ line.split(':',1) for line in infile if ':' in line ]
pairs = [ (domain.strip(), owner.strip())
for (domain,owner) in pairs ]
return dict(lines)

DOMAINOWNERS = loaddomainowners()

def lookupdmo(domain):
return DOMAINOWNERS[domain]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-12-07 Thread BlueBird
On Dec 2, 4:27 pm, BlueBird <[EMAIL PROTECTED]> wrote:
> On Nov 26, 5:07 pm, "Sergio Correia" <[EMAIL PROTECTED]> wrote:
>
> >Bluebird:
>
> > If you are using python 2.5, relative imports are no longer an
> > issue:http://docs.python.org/whatsnew/pep-328.html
>
> It does not solve my problem, or I missed something:
>

Any idea what could be wrong in my code (in the previous message). Or
did I misunderstand relative import seriously ?

Philippe
-- 
http://mail.python.org/mailman/listinfo/python-list


File to dict

2007-12-07 Thread mrkafk
Hello everyone,

I have written this small utility function for transforming legacy
file to Python dict:


def lookupdmo(domain):
lines = open('/etc/virtual/domainowners','r').readlines()
lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
lines]
lines = [ x for x in lines if len(x) == 2 ]
d = dict()
for line in lines:
d[line[0]]=line[1]
return d[domain]

The /etc/virtual/domainowners file contains double-colon separated
entries:
domain1.tld: owner1
domain2.tld: own2
domain3.another: somebody
...

Now, the above lookupdmo function works. However, it's rather tedious
to transform files into dicts this way and I have quite a lot of such
files to transform (like custom 'passwd' files for virtual email
accounts etc).

Is there any more clever / more pythonic way of parsing files like
this? Say, I would like to transform a file containing entries like
the following into a list of lists with doublecolon treated as
separators, i.e. this:

tm:$1$$:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin

would get transformed into this:

[ ['tm', '$1$$', '1010', '6', , '/home/owner1/imap/domain1.tld/
tm', '/sbin/nologin'] [...] [...] ]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I embed Windows Python in C# or VC++?

2007-12-07 Thread Christian Heimes
sturlamolden wrote:
> The answer is YES. C# can access C functions exported by any DLL with
> platform invoke. Since the Python C API is plain C and not C++ you can
> gain access to it from C#. Import System.Runtime.InteropServices and
> write wrappers like
> 
> [DllImport("Python25.dll"), CallingConvention=CallingConvention.Cdecl]
> public static void Py_Initialize();

There is no need for that. PythonDotNET wraps the P/Invokes and internal
C API of CPython in a nice .NET API.

Christian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Erros when compiling a CPP program which uses CPython API functions

2007-12-07 Thread Christian Heimes
grbgooglefan wrote:
 > How do we resolve this error?

The easiest way to solve all your problems is: make altinstall.

It installs Python in PREFIX (usually /usr/local). Although it is
possible to run Python in a build directory it is tricky and may not
work for your own program.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Tim Golden
Matt_D wrote:

[... snip loads ...]

> Wow, list spam.

Indeed.

> Sorry about this.

Good.

> Anyway, disregard my last two. I get it now. 

Glad to hear it.


Might I suggest, though, that it's not necessary to repeat
the entire history of the thread on every email. Unless
you have reason to reproduce the older code and comments,
just elide them, optionally using some kind of [snip] marker
as I have above to indicate that something's been left out.


TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New subclass vs option in __init__

2007-12-07 Thread Carl Banks
On Dec 6, 11:56 am, "Kurt Smith" <[EMAIL PROTECTED]> wrote:
> It would seem that there are cases where one would be preferable over
> the other: a) when the new behavior would modify a large portion of
> the existing subclass, making a new subclass would be ideal; b) when
> the new behavior changes only slightly the existing subclass, perhaps
> a simple default option in the subclass's __init__ method would be
> best.  Where is the tipping point?


Good question.


Carl Banks

-- 
http://mail.python.org/mailman/listinfo/python-list


python and a 2 gigs Usb Stick (pure pythonic stick)

2007-12-07 Thread bussiere maillist
Hi,
i've received for my birthday two usb key, and i had the idea to make
the 2GB one a special python usb key.
So far i've put on it :
Movable Python
My Python directory
Iron Python
Jython
Instant django

the file installation for :
Python , iron python , jython , PIL , Pygame , Pywin32

The pdf in a doc_programmation :
dive into python , programmting python

What else should i add in this key in your opinion ?


Regards and thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread Spindle
On Dec 7, 3:59 pm, Tim Golden <[EMAIL PROTECTED]> wrote:
> gurkan wrote:
> > i have treid the script :
>
> > #import active_directory
> > import win32com.client
>
> > win32com.client.Dispatch ("ADODB.Command")
> > #me = active_directory.find_user ()
>
> > #print me
>
> > again i got the error :
>
> > Traceback (most recent call last):
> >   File "H:\dev\eclipse\workspace\pyProject\src\pyPackage
> > \adDeneme3.py", line 4, in 
> > win32com.client.Dispatch ("ADODB.Command")
> >   File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
> > line 95, in Dispatch
> > dispatch, userName =
> > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
> >   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> > line 98, in _GetGoodDispatchAndUserName
> > return (_GetGoodDispatch(IDispatch, clsctx), userName)
> >   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> > line 78, in _GetGoodDispatch
> > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
> > pythoncom.IID_IDispatch)
> > pywintypes.com_error: (-2147024770, 'The specified module could not be
> > found.', None, None)
>
> I don't think it's that the CoCreateInstance can't be found:
> that's a COM error you're seeing and it means that the
> IDispatch mechanism can't find the "ADODB.Command" you're
> looking for. If I get the chance I'll try to find a Vista
> machine to find out what the equivalent is. If anyone on
> the list has Vista and/or knows what the score is here,
> please let me know.
>
> To double-check, Gurkan, could you open the Registry and
> browse to HKEY_CLASSES_ROOT and look for a key ADODB.Command.
> I presume it's not present.
>
> TJG

I checked the key,and it was found under HKEY_CLASSES_ROOT.And as i
mentioned before,
the problem happens only with eclipse and pydev,on the same machine i
can run the script from command line or with IDLE without any errors.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread gurkan
On 7 Aralık, 15:59, Tim Golden <[EMAIL PROTECTED]> wrote:
> gurkan wrote:
> > i have treid the script :
>
> > #import active_directory
> > import win32com.client
>
> > win32com.client.Dispatch ("ADODB.Command")
> > #me = active_directory.find_user ()
>
> > #print me
>
> > again i got the error :
>
> > Traceback (most recent call last):
> >   File "H:\dev\eclipse\workspace\pyProject\src\pyPackage
> > \adDeneme3.py", line 4, in 
> > win32com.client.Dispatch ("ADODB.Command")
> >   File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
> > line 95, in Dispatch
> > dispatch, userName =
> > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
> >   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> > line 98, in _GetGoodDispatchAndUserName
> > return (_GetGoodDispatch(IDispatch, clsctx), userName)
> >   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> > line 78, in _GetGoodDispatch
> > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
> > pythoncom.IID_IDispatch)
> > pywintypes.com_error: (-2147024770, 'The specified module could not be
> > found.', None, None)
>
> I don't think it's that the CoCreateInstance can't be found:
> that's a COM error you're seeing and it means that the
> IDispatch mechanism can't find the "ADODB.Command" you're
> looking for. If I get the chance I'll try to find a Vista
> machine to find out what the equivalent is. If anyone on
> the list has Vista and/or knows what the score is here,
> please let me know.
>
> To double-check, Gurkan, could you open the Registry and
> browse to HKEY_CLASSES_ROOT and look for a key ADODB.Command.
> I presume it's not present.
>
> TJG- Alıntıyı gizle -
>
> - Alıntıyı göster -

I checked the key,and it was found under HKEY_CLASSES_ROOT.And as i
mentioned before,
the problem happens only with eclipse and pydev,on the same machine i
can run the script from command line or with IDLE without any errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: splitting a words of a line

2007-12-07 Thread Paul McGuire
On Dec 6, 9:21 am, Sumit <[EMAIL PROTECTED]> wrote:
> Hi ,
>I am trying to splitt  a Line whihc is below of format ,
>
> AzAccept PLYSSTM01 [23/Sep/2005:16:14:28 -0500] "162.44.245.32 CN=
> cojack (890),OU=1,OU=Customers,OU=ISM-Users,OU=kkk
> Secure,DC=customer,DC=rxcorp,DC=com" "plysmhc03zp GET /mci/performance/
> SelectProducts.aspx?
> p=0&V=C&a=29&menu=adhoc" [d4b62ca2-09a0-4334622b-0e1c-03c42ba5] [0]
>

As John Machin mentioned, pyparsing may be helpful to you.  Here is a
simple version:

data = """AzAccept PLYSSTM01 [23/Sep/2005:16:14:28 -0500]
"162.44.245.32 CN= cojack (890),OU=1,OU=Customers,OU=ISM-
Users,OU=kkk Secure,DC=customer,DC=rxcorp,DC=com" "plysmhc03zp GET /
mci/performance/SelectProducts.aspx?
p=0&V=C&a=29&menu=adhoc" [d4b62ca2-09a0-4334622b-0e1c-03c42ba5] [0]"""

# Version 1 - simple
from pyparsing import *
LBRACK,RBRACK,COMMA = map(Suppress,"[],")
num = Word(nums)
date = Combine(num+"/"+Word(alphas)+"/"+num+":"+num+":"+num+":"+num) +
\
oneOf("+ -") + num
date.setParseAction(keepOriginalText)
uuid = delimitedList(Word(hexnums),"-",combine=True)
logString = Word(alphas,alphanums) + Word(alphas,alphanums) + \
LBRACK + date + RBRACK + quotedString + quotedString + \
LBRACK + uuid + RBRACK + LBRACK + Word(nums) + RBRACK

print logString.parseString(data)

Prints out:
['AzAccept', 'PLYSSTM01', '23/Sep/2005:16:14:28 -0500',
'"162.44.245.32 CN= cojack (890),OU=1,OU=Customers,OU=ISM-
Users,OU=kkk Secure,DC=customer,DC=rxcorp,DC=com"', '"plysmhc03zp GET /
mci/performance/SelectProducts.aspx?p=0&V=C&a=29&menu=adhoc"',
'd4b62ca2-09a0-4334622b-0e1c-03c42ba5', '0']


And here is a slightly fancier version, which parses the quoted
strings (uses the pprint pretty-printing module to show structure of
the parsed results):

# Version 2 - fancy
from pyparsing import *
LBRACK,RBRACK,COMMA = map(Suppress,"[],")
num = Word(nums)
date = Combine(num+"/"+Word(alphas)+"/"+num+":"+num+":"+num+":"+num) +
\
oneOf("+ -") + num
date.setParseAction(keepOriginalText)
uuid = delimitedList(Word(hexnums),"-",combine=True)

ipAddr = delimitedList(Word(nums),".",combine=True)
keyExpr=Word(alphas.upper())
valExpr=CharsNotIn(',')
qs1Expr = ipAddr + Group(delimitedList(Combine(keyExpr + '=' +
valExpr)))
def parseQS1(t):
return qs1Expr.parseString(t[0])
def parseQS2(t):
return t[0].split()

qs1 = quotedString.copy().setParseAction(removeQuotes, parseQS1)
qs2 = quotedString.copy().setParseAction(removeQuotes, parseQS2)

logString = Word(alphas,alphanums) + Word(alphas,alphanums) + \
LBRACK + date + RBRACK + qs1 + qs2 + \
LBRACK + uuid + RBRACK + LBRACK + Word(nums) + RBRACK

from pprint import pprint
pprint(logString.parseString(data).asList())

Prints:
['AzAccept',
 'PLYSSTM01',
 '23/Sep/2005:16:14:28 -0500',
 '162.44.245.32',
 ['CN= cojack (890)',
  'OU=1',
  'OU=Customers',
  'OU=ISM-Users',
  'OU=kkk Secure',
  'DC=customer',
  'DC=rxcorp',
  'DC=com'],
 'plysmhc03zp',
 'GET',
 '/mci/performance/SelectProducts.aspx?p=0&V=C&a=29&menu=adhoc',
 'd4b62ca2-09a0-4334622b-0e1c-03c42ba5',
 '0']

Find more about pyparsing at http://pyparsing.wikispaces.com.

-- Paul


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Neil Cerutti
On 2007-12-07, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] a écrit :
>> 
>>> The csv module is your friend.
>> 
>> (slapping forehead) why the Holy Grail didn't I think about this? 
>
> If that can make you feel better, a few years ago, I spent two
> days writing my own (SquaredWheel(tm) of course) csv
> reader/writer... before realizing there was such a thing as the
> csv module :-/
>
> Should have known better...

But probably it has made you a better person. ;)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


How does python build its AST

2007-12-07 Thread MonkeeSage
A quick question about how python parses a file into compiled
bytecode. Does it parse the whole file into AST first and then compile
the AST, or does it build and compile the AST on the fly as it reads
expressions? (If the former case, why can't functions be called before
their definitions?)

Thanks,
Jordan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Dirk Hagemann
On 7 Dez., 14:34, supercooper <[EMAIL PROTECTED]> wrote:
> On Dec 7, 7:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello,
>
> > From a zone-file of a Microsoft Active Directory integrated DNS server
> > I get the date/time of the dynamic update entries in a format, which
> > is as far as I know the hours since january 1st 1901.
> > For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
> > Excel I use this:
> > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> > 3566839 in field A1 and switch the format of the result-field to the
> > corresponding date-time format).
>
> > You might guess what I need now: I want to calculate this somehow in
> > python.
>
> > Sorry, but I couldn't find anything in the module time or something
> > else to get this calculated.
>
> > Does anyone know how to convert this time in python to something
> > usable or how to convert this formula in python?
>
> > Thanks a lot and regards
> > Dirk
>
> I think you want the xldate_as_tuple function in the xlrd module:
>
> http://www.lexicon.net/sjmachin/xlrd.htm
>
> It works like a champ for me:
>
> >>> import xlrd
> >>> xlrd.xldate.xldate_as_tuple(38980,0)
>
> (2006, 9, 20, 0, 0, 0)
>
>
>
> chad!

Thanks so far, that comes close to a solution I think, BUT when I
enter 3566985 instead of 38980 I get the following error:
Traceback (most recent call last):
  File "test.py", line 20, in 
print xlrd.xldate.xldate_as_tuple(3566985,0)
  File "C:\Python25\lib\site-packages\xlrd\xldate.py", line 75, in
xldate_as_tuple
raise XLDateTooLarge(xldate)
xlrd.xldate.XLDateTooLarge: 3566985

Do I have to use another function of this module? My number is 2
digits shorter than yours. What is 38980 representing?

Dirk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread mrkafk

> >>> def shelper(line):
> ... return x.replace(' ','').strip('\n').split(':',1)

Argh, typo, should be def shelper(x) of course.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread mrkafk

> I guess Duncan's point wasn't the construction of the dictionary but the
> throw it away part.  If you don't keep it, the loop above is even more
> efficient than building a dictionary with *all* lines of the file, just to
> pick one value afterwards.

Sure, but I have two options here, none of them nice: either "write C
in Python" or do it inefficient and still elaborate way.

Anyway, I found my nirvana at last:

>>> def shelper(line):
... return x.replace(' ','').strip('\n').split(':',1)
...

>>> ownerslist = [ shelper(x)[1] for x in it if len(shelper(x)) == 2 and 
>>> shelper(x)[0] == domain ]

>>> ownerslist
['da2']


Python rulez. :-)




-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread gurkan
On 7 Aralık, 15:40, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > i want to use active directory of my firm to user authentication.i am
> > using active_directory module
>
> By the way, if what you want to do is user *authentication* (as
> opposed to authorisation) then the active_directory module won't
> be any good to you. You want to use either the SSPI functionality
> or the LogonUser API. There's a toy example of the latter here:
>
> http://timgolden.me.uk/python/win32_how_do_i/check-a-users-credential...
>
> TJG

i have treid the script :

#import active_directory
import win32com.client

win32com.client.Dispatch ("ADODB.Command")
#me = active_directory.find_user ()

#print me

again i got the error :

Traceback (most recent call last):
  File "H:\dev\eclipse\workspace\pyProject\src\pyPackage
\adDeneme3.py", line 4, in 
win32com.client.Dispatch ("ADODB.Command")
  File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
line 95, in Dispatch
dispatch, userName =
dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
line 78, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147024770, 'The specified module could not be
found.', None, None)


as i said before the problem is related with pydev-eclipse-pywin
dynamic module loading in vista i think,because CoCreateInstance
function could not be found.

i am not using python module for authentication,i do it with apache.i
am using python for subversion hook scripts written in python for AD
user-email mapping


ps : Thanks Tim for ur nice active_directory module...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Duncan Booth
Matt Nordhoff <[EMAIL PROTECTED]> wrote:

> Using two list comprehensions mean you construct two lists, which sucks
> if it's a large file.

Only if it is very large. You aren't duplicating the data except for 
entries with whitespace round them. If there isn't a lot of whitespace then 
the extra overhead for duplicating the list is unlikely to be significant.

> 
> Also, you could pass the list comprehension (or better yet a generator
> expression) directly to dict() without saving it to a variable:
> 
> with open('/etc/virtual/domainowners','r') as fh:
> return dict(line.strip().split(':', 1) for line in fh)
> 
> (Argh, that doesn't .strip() the key and value, which means it won't
> work, but it's so simple and elegant and I'm tired enough that I'm not
> going to add that. :-P Just use another genexp. Makes for a line
> complicated enough that it could be turned into a for loop, though.)

It isn't hard to convert my lists to generators keeping the structure 
exactly the same (and fixing the typo):

def loaddomainowners(domain):
with open('/etc/virtual/domainowners','r') as infile:
pairs = (line.split(':',1) for line in infile if ':' in line)
pairs = ((domain.strip(), owner.strip())
for (domain,owner) in pairs)
return dict(pairs)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> i want to use active directory of my firm to user authentication.i am
> using active_directory module

By the way, if what you want to do is user *authentication* (as
opposed to authorisation) then the active_directory module won't
be any good to you. You want to use either the SSPI functionality
or the LogonUser API. There's a toy example of the latter here:

http://timgolden.me.uk/python/win32_how_do_i/check-a-users-credentials.html

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> i want to use active directory of my firm to user authentication.i am
> using active_directory module(Tim Golden's module -
> http://tgolden.sc.sabren.com/python/active_directory.html).
> 
> i am using windows vista with an administrative account,python
> 2.5 ,eclipse 3.2 and pydev plugin,and here is my problem :

[...]

>   File "E:\Python25\lib\active_directory.py", line 294, in query
> command = Dispatch ("ADODB.Command")
>   File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
> line 95, in Dispatch
> dispatch, userName =
> dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
>   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> line 98, in _GetGoodDispatchAndUserName
> return (_GetGoodDispatch(IDispatch, clsctx), userName)
>   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> line 78, in _GetGoodDispatch
> IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
> pythoncom.IID_IDispatch)
> pywintypes.com_error: (-2147024770, 'The specified module could not be
> found.', None, None)


Not sure (I don't use Vista) but can you try this:


import win32com.client
win32com.client.Dispatch ("ADODB.Command")


TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some python syntax that I'm not getting

2007-12-07 Thread Laurent Pointal
Chris a écrit :
> On Dec 7, 2:31 pm, waltbrad <[EMAIL PROTECTED]> wrote:
>> I understand how D['say'] gets you 5,  But I still don't understand
>> the line after the 5.
>>
>> How is the character 's' some special code?  And I don't get what is
>> going on with the % character.  I'm used to it's use in c-style
>> formatting, but this just seems so bizarre.  I can tell that the key
>> is being replaced by it's value in the string, but I don't know how
>> that is being done.
>>
>> TIA
> 
> http://docs.python.org/lib/typesseq-strings.html
> 
> The '%' invokes the formatter, the 's' specifies string type.

And the (name) specify to find the value to format (following %s rules) 
in a dictionnary given as % operator parameter, under the name key.

-- 
http://mail.python.org/mailman/listinfo/python-list


eclipse pywintypes.com_error

2007-12-07 Thread gurkanserin
Hello everybody,

i want to use active directory of my firm to user authentication.i am
using active_directory module(Tim Golden's module -
http://tgolden.sc.sabren.com/python/active_directory.html).

i am using windows vista with an administrative account,python
2.5 ,eclipse 3.2 and pydev plugin,and here is my problem :

i am using the script :

-
import active_directory

me = active_directory.find_user ()

print me
-


when i run this script from idle or command line everything goes
fine , but when i want to run it from eclipse i get the followinr
error :


Traceback (most recent call last):
  File "H:\dev\eclipse\workspace\pyProject\src\pyPackage
\adDeneme3.py", line 3, in 
me = active_directory.find_user ()
  File "E:\Python25\lib\active_directory.py", line 721, in find_user
return root ().find_user (name)
  File "E:\Python25\lib\active_directory.py", line 539, in find_user
for user in self.search ("sAMAccountName='%s' OR displayName='%s'
OR cn='%s'" % (name, name, name), objectCategory='Person',
objectClass='User'):
  File "E:\Python25\lib\active_directory.py", line 572, in search
for result in query ("\n".join (sql_string), Page_size=50):
  File "E:\Python25\lib\active_directory.py", line 294, in query
command = Dispatch ("ADODB.Command")
  File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
line 95, in Dispatch
dispatch, userName =
dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
line 78, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147024770, 'The specified module could not be
found.', None, None)

i think the problem may be related with windows vista and pydev...

thanks for your help...

ps : i also tried this with Windows XP,in that OS both the idle and
eclipse woeks fine,i had no problem





-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code Management

2007-12-07 Thread Marc Christiansen
BlueBird <[EMAIL PROTECTED]> wrote:
> On Dec 2, 4:27 pm, BlueBird <[EMAIL PROTECTED]> wrote:
>> On Nov 26, 5:07 pm, "Sergio Correia" <[EMAIL PROTECTED]> wrote:
>>
>> >Bluebird:
>>
>> > If you are using python 2.5, relative imports are no longer an
>> > issue:http://docs.python.org/whatsnew/pep-328.html
>>
>> It does not solve my problem, or I missed something:
>>
> 
> Any idea what could be wrong in my code (in the previous message). Or
> did I misunderstand relative import seriously ?

Does this give you an idea?

0:tolot:/tmp> mkdir t1 
0:tolot:/tmp> touch t1/__init__.py
0:tolot:/tmp> echo print __name__ >t1/test.py
0:tolot:/tmp> python t1/test.py
__main__
0:tolot:/tmp> python -c "import t1.test"
t1.test

Marc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JSON

2007-12-07 Thread Sion Arrowsmith
Joshua Kugler  <[EMAIL PROTECTED]> wrote:
>Known issue.  See:
>http://blog.extracheese.org/2007/07/when-json-isnt-json.html
>
>Neither project has fixed it it seems.  Not sure which is actually
>the "correct" way to do it, but it would be nice if they would agree.

I think it's pretty clear (not just from that blog entry, but from
the grammar at http://json.org/) that cjson is incorrectly decoding
"\/". Whether it's sensible for simplejson to be encoding '/' as "\/"
is up for grabs, but it's perfectly correct for it to do so, so one
shouldn't expect it to be "fixed".

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: File to dict

2007-12-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Dec 2007 04:44:25 -0800, mrkafk wrote:

> Duncan Booth wrote:
>> But why do you construct a dict from that input data simply to throw it
>> away?
> 
> Because comparing strings for equality in a loop is writing C in
> Python, and that's exactly what I'm trying to unlearn.
> 
> The proper way to do it is to produce a dictionary and look up a value
> using a key.
> 
>>If you only want 1 domain from the file just pick it out of the list.
> 
> for item in list:
> if item == 'searched.domain':
> return item...
> 
> Yuck.

I guess Duncan's point wasn't the construction of the dictionary but the
throw it away part.  If you don't keep it, the loop above is even more
efficient than building a dictionary with *all* lines of the file, just to
pick one value afterwards.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread mrkafk


> The csv module is your friend.

(slapping forehead) why the Holy Grail didn't I think about this? That
should be much simpler than using SimpleParse or SPARK.

Thx Bruno & everyone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> On Dec 7, 7:20�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> From a zone-file of a Microsoft Active Directory integrated DNS server
>> I get the date/time of the dynamic update entries in a format, which
>> is as far as I know the hours since january 1st 1901.

If it *is* then the easiest way is this:


import datetime
print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839)



But, as someone pointed out, that puts you somewhere in 2300.
Where are you getting the 1901 from (and the hours, for that
matter). If it's based, as AD dates are, for example, from 1601,
then the calc becomes:


import datetime
print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839)



which looks more realistic. But frankly I'm guessing.

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list

Some python syntax that I'm not getting

2007-12-07 Thread waltbrad
Hello. Been studying Python for about a week now. I did a quick read
of the tutorial in the manual and I'm reading Programming Python by
Mark Lutz.   I'm still getting used to the Python syntax, but I'm able
to pretty much follow what is being said.  But tonight Lutz was
talking about implementing a database on a website and threw out this
piece in his code:

key

That last bit is the bit that throws me: %(keys)s

He explains this so:

"The only feat of semimagic it relies on is using a record's attribute
dictionary (__dict__) as the source of values when applying string
formatting to the HTML reply template string in the last line of the
script. Recall that a %(key)code replacement target fetches a value by
key from a dictionary:

>>> D = {'say': 5, 'get': 'shrubbery'}
>>> D['say']
5
>>> S = '%(say)s => %(get)s' % D
>>> S
'5 => shrubbery'   "

Hm...

I understand how D['say'] gets you 5,  But I still don't understand
the line after the 5.

How is the character 's' some special code?  And I don't get what is
going on with the % character.  I'm used to it's use in c-style
formatting, but this just seems so bizarre.  I can tell that the key
is being replaced by it's value in the string, but I don't know how
that is being done.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Duncan Booth
Neil Cerutti <[EMAIL PROTECTED]> wrote:

> On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote:
>> from __future__ import with_statement
>>
>> def loaddomainowners(domain):
>> with open('/etc/virtual/domainowners','r') as infile:
> 
> I've been thinking I have to use contextlib.closing for
> auto-closing files. Is that not so?
> 
That is not so.

Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import with_statement
>>> with open('diffs.txt') as f:
...print len(list(f))
...
40
>>> f

>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread [EMAIL PROTECTED]
On Dec 7, 7:20�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> Hello,
>
> From a zone-file of a Microsoft Active Directory integrated DNS server
> I get the date/time of the dynamic update entries in a format, which
> is as far as I know the hours since january 1st 1901.

Your guess appears to be off by a couple centuries.

(3566839/24)/365 = 407

> For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
> Excel I use this:
> ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) �(put
> 3566839 in field A1 and switch the format of the result-field to the
> corresponding date-time format).
>
> You might guess what I need now: I want to calculate this somehow in
> python.
>
> Sorry, but I couldn't find anything in the module time or something
> else to get this calculated.
>
> Does anyone know how to convert this time in python to something
> usable or how to convert this formula in python?
>
> Thanks a lot and regards
> Dirk

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Dirk Hagemann
On 7 Dez., 16:50, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> On 7 Dez., 16:21, Tim Golden <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > On Dec 7, 7:20�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> > >> Hello,
>
> > >> From a zone-file of a Microsoft Active Directory integrated DNS server
> > >> I get the date/time of the dynamic update entries in a format, which
> > >> is as far as I know the hours since january 1st 1901.
>
> > If it *is* then the easiest way is this:
>
> > 
> > import datetime
> > print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839)
>
> > 
>
> > But, as someone pointed out, that puts you somewhere in 2300.
> > Where are you getting the 1901 from (and the hours, for that
> > matter). If it's based, as AD dates are, for example, from 1601,
> > then the calc becomes:
>
> > 
> > import datetime
> > print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839)
>
> > 
>
> > which looks more realistic. But frankly I'm guessing.
>
> > TJG
>
> (3566839/24)/365 = 407   - YES I did this calculation too and was
> surprised. But if you try this out in MS Excel:
>  ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-fieldby right-
> click on it to the
> date format "14.3.01 13:30")
>
> and then replace 3566839 by, let's say, "2", Excel calculates the date
> 01.10.1901 2:00 AM. Try out other values like 5 or 24! So I thought
> 3566839 represents hours.
>
> Dirk

Additional to my last posting: if you want to try this out in Excel
you should replace the command "REST" by the english command what
should be something like "remainder".
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: New subclass vs option in __init__

2007-12-07 Thread Neil Cerutti
On 2007-12-07, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Dec 6, 11:56 am, "Kurt Smith" <[EMAIL PROTECTED]> wrote:
>> It would seem that there are cases where one would be
>> preferable over the other: a) when the new behavior would
>> modify a large portion of the existing subclass, making a new
>> subclass would be ideal; b) when the new behavior changes only
>> slightly the existing subclass, perhaps a simple default
>> option in the subclass's __init__ method would be best.  Where
>> is the tipping point?
>
> Good question.

The major factor in the tipping point is clarity. And simplicity.
The two major factors in deciding the tipping point are: clarity,
simplicity, and extensibility. ... The THREE major tipping point
factors ARE: clarity, simplicity, extensibility. And efficiency.
Among the many factors in deciding the tipping point are: (etc.,
etc.)

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Dirk Hagemann
On 7 Dez., 16:21, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Dec 7, 7:20�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> >> Hello,
>
> >> From a zone-file of a Microsoft Active Directory integrated DNS server
> >> I get the date/time of the dynamic update entries in a format, which
> >> is as far as I know the hours since january 1st 1901.
>
> If it *is* then the easiest way is this:
>
> 
> import datetime
> print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839)
>
> 
>
> But, as someone pointed out, that puts you somewhere in 2300.
> Where are you getting the 1901 from (and the hours, for that
> matter). If it's based, as AD dates are, for example, from 1601,
> then the calc becomes:
>
> 
> import datetime
> print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839)
>
> 
>
> which looks more realistic. But frankly I'm guessing.
>
> TJG

(3566839/24)/365 = 407   - YES I did this calculation too and was
surprised. But if you try this out in MS Excel:
 ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
3566839 in field A1 and switch the format of the result-fieldby right-
click on it to the
date format "14.3.01 13:30")

and then replace 3566839 by, let's say, "2", Excel calculates the date
01.10.1901 2:00 AM. Try out other values like 5 or 24! So I thought
3566839 represents hours.

Dirk
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: File to dict

2007-12-07 Thread Glauco
[EMAIL PROTECTED] ha scritto:
> Hello everyone,
> 
> I have written this small utility function for transforming legacy
> file to Python dict:
> 
> 
> def lookupdmo(domain):
> lines = open('/etc/virtual/domainowners','r').readlines()
> lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
> lines]
> lines = [ x for x in lines if len(x) == 2 ]
> d = dict()
> for line in lines:
> d[line[0]]=line[1]
> return d[domain]
> 

cache = None

def lookup( domain ):
if not cache:
   cache = dict( [map( lambda x: x.strip(), x.split(':'))  for x in 
open('/etc/virtual/domainowners','r').readlines()])
return cache.get(domain)





Glauco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Hello everyone,

(snip)

> Say, I would like to transform a file containing entries like
> the following into a list of lists with doublecolon treated as
> separators, i.e. this:
> 
> tm:$1$$:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin
> 
> would get transformed into this:
> 
> [ ['tm', '$1$$', '1010', '6', , '/home/owner1/imap/domain1.tld/
> tm', '/sbin/nologin'] [...] [...] ]

The csv module is your friend.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Zentrader
If we use minutes from 2001, then 3566839 comes out as sometime in
October, 2007 (6.78622 years).  Close but no cigar.  Is anyone familar
enough with Excel to translate the formula or do we have to go a-
googling?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Matt_D
On Dec 7, 12:33 pm, Matt_D <[EMAIL PROTECTED]> wrote:
> On Dec 7, 12:27 pm, Matt_D <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 7, 11:42 am, Virgil Dupras <[EMAIL PROTECTED]>
> > wrote:
>
> > > On Dec 7, 9:05 am, Matt_D <[EMAIL PROTECTED]> wrote:
>
> > > > Hello there, this is my first post to the list. Only been working with
> > > > Python for a few days. Basically a complete newbie to programming.
>
> > > > I'm working with csv module as an exercise to parse out a spreadsheet
> > > > I use for work.(I am an editor for a military journalism unit) Not
> > > > trying to do anything useful, just trying to manipulate the data.
> > > > Anyway, here's the code I've got so far:
>
> > > > import csv
> > > > import string
> > > > import os
>
> > > > #Open the appropriate .csv file
> > > > csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))
>
> > > > #Create blank dictionary to hold {[author]:[no. of stories]} data
> > > > story_per_author = {}
>
> > > > def author_to_dict(): #Function to add each author to the dictionary
> > > > once to get initial entry for that author
> > > > for row in csv_file:
> > > > author_count = row[-1]
> > > > story_per_author[author_count] = 1
>
> > > > #Fetch author names
> > > > def rem_blank_authors(): #Function to remove entries with '' in the
> > > > AUTHOR field of the .csv
> > > > csv_list = list(csv_file) #Convert the open file to list format
> > > > for e-z mode editing
> > > > for row in csv_list:
> > > > author_name = row[-1]
> > > > if author_name == '': #Find entries where no author is listed
> > > > csv_list.remove(row) #Remove those entries from the list
>
> > > > def assign_author_to_title(): #Assign an author to every title
> > > > author_of_title = {}
> > > > for row in csv_file:
> > > > title = row[3]
> > > > author = row[-1]
> > > > author_of_title[title] = author
>
> > > > assign_author_to_title()
> > > > print author_of_title
>
> > > > --
>
> > > > Ok, the last two lines are kind of my "test the last function" test.
> > > > Now when I run these two lines I get the error:
>
> > > > Traceback (most recent call last):
> > > >   File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
> > > > \scriptutils.py", line 310, in RunScript
> > > > exec codeObject in __main__.__dict__
> > > >   File "D:\Python25\csv_read.py", line 33, in 
> > > > print author_of_title
> > > > NameError: name 'author_of_title' is not defined
>
> > > > I am guessing that the author_of_title dict does not exist outside of
> > > > the function in which it is created? The concept of instantiation is
> > > > sort of foreign to me so I'm having some trouble predicting when it
> > > > happens.
>
> > > > If I call the assign_author_to_title function later, am I going to be
> > > > able to work with the author_of_title dictionary? Or is it best if I
> > > > create author_of_title outside of my function definitions?
>
> > > > Clearly I'm just stepping through my thought process right now,
> > > > creating functions as I see a need for them. I'm sure the code is
> > > > sloppy and terrible but please be gentle!
>
> > > As you said, author_of_title doesn't exist outside of
> > > assign_author_to_title() because it has been instantiated in the
> > > function, and thus belong to the local scope. You could instantiate
> > > your dictionary outside of the function, but the nicest way to handle
> > > this would be to add a line "return author_of_title" at the end of
> > > assign_author_to_title() and have "print assign_author_to_title()"
> > > instead of the 2 last lines.
>
> > Another newb question, same project:
>
> > #Fetch author names
> > def rem_blank_authors(): #Function to remove entries with '' in the
> > AUTHOR field of the .csv
> > csv_list = list(csv_file) #Convert the open file to list format
> > for e-z mode editing
> > for row in csv_list:
> > author_name = row[-1]
> > if author_name == '': #Find entries where no author is listed
> > csv_list.remove(row) #Remove those entries from the list
> > return csv_list
>
> > def author_to_dict(): #Function to add each author to the dictionary
> > once to get initial entry for that author
> > #rem_blank_authors() #Call this function to remove blank author
> > fields before building the main dictionary
> > for row in csv_file:
> > author_count = row[-1]
> > if author_count in story_per_author:
> > story_per_author[author_count] += 1
> > else:
> > story_per_author[author_count] = 1
> > return story_per_author
>
> > def assign_author_to_title(): #Assign an author to every title
> > author_of_title = {}
> > for row in csv_file:
> > title = row[3]
> > author = row[-1]
> > author_of_title[title] = author
>
> > author_to_dict()
> > print story_per_author
>
> > --
>
> > The solution provided for my previous post worked out. Now I'm testi

Python 2.4.4, Segmentation fault

2007-12-07 Thread Ruslan Mashukov
Program terminated with signal 11, Segmentation fault.
Environment: FreeBSD 6.2, Python 2.4.4, MySQLdb 1.2.2, SQLObject 0.9.1

I faced with an error in our multithreaded, network oriented application,
wich interacts actively with MySQL database.

Though I am not very experienced with FreeBSD and gdb, I have still tried to
collect information about the error.
I'll be happy to hear any comments and suggestions.

TIA

Here is a link to the full gdb info: http://paste-it.net/5038
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: File to dict

2007-12-07 Thread Neil Cerutti
On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Neil Cerutti <[EMAIL PROTECTED]> wrote:
>
>> On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote:
>>> from __future__ import with_statement
>>>
>>> def loaddomainowners(domain):
>>> with open('/etc/virtual/domainowners','r') as infile:
>> 
>> I've been thinking I have to use contextlib.closing for
>> auto-closing files. Is that not so?
>> 
> That is not so.
>
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit 
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 from __future__ import with_statement
 with open('diffs.txt') as f:
> ...print len(list(f))
> ...
> 40
 f
>

Thanks. After seeing your answer I managed to find what I'd
overlooked before, in the docs for file.close:

  As of Python 2.5, you can avoid having to call this method
  explicitly if you use the with statement. For example, the
  following code will automatically close f when the with block
  is exited: 
  
from __future__ import with_statement

with open("hello.txt") as f:
for line in f:
print line

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I embed Windows Python in C# or VC++?

2007-12-07 Thread Christian Heimes
grbgooglefan wrote:
> I want to use Python's Windows (python25.dll) version to embed in my
> C# (or atleast VC++) program for performing syntax checks on the
> Python expressions which are later supposed to be evaluated at runtime
> by another C++ program
> 
> For this, I would like to use CPython API functions such as
> Py_Initialize, PyModule_New, PyModule_GetDict, PyRun_String,
> PyObject_GetAttrString, PyObject_CallObject, PyTuple_SetItem & other
> similar functions from my C#/ VC++ program on Windows.

It's not a matter of C++ or C## but a matter of managed or unmanaged
language. Nowadays VS C++ can create old style binaries and CLR. For C++
you can use  the MSI but I recommend a source installation. It makes
debugging easier. You may want to port my PCbuild9 directory from svn
trunk (Python 2.6) to Python 2.5 if you like to use VS 2008.

For CLR/.NET (Managed C++, C#, VB, ...) you need the PythonDotNET
bindings from http://pythonnet.sf.net/. Brian (the creator of
PythonDotNET) and I are very busy in the last weeks and months. The last
preview release is outdated. Please check out the latest version from
PythonDotNET's SVN.

The support for unmanaged C++ is better than the support for managed
.NET code.

Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [NEWB] Dictionary instantiation?

2007-12-07 Thread Bruno Desthuilliers
Matt_D a écrit :
> Hello there, this is my first post to the list. Only been working with
> Python for a few days. Basically a complete newbie to programming.
> 
> I'm working with csv module as an exercise to parse out a spreadsheet
> I use for work.(I am an editor for a military journalism unit) Not
> trying to do anything useful, just trying to manipulate the data.
> Anyway, here's the code I've got so far:
> 
> import csv
> import string
> import os
> 
> #Open the appropriate .csv file
> csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))
> 
> #Create blank dictionary to hold {[author]:[no. of stories]} data
> story_per_author = {}
> 
> def author_to_dict(): #Function to add each author to the dictionary
> once to get initial entry for that author

First point: your comment would be better in a docstring - and that 
would make the code more readable

def author_to_dict():
   """Function to add each author to the dictionary
  once to get initial entry for that author
   """
> for row in csv_file:

Second point: you're using 2 global variables. This is something to 
avoid whenever possible (that is: almost always). Here you're in the 
very typical situation of a function that produces output 
(story_per_author) depending only on it's input (csv_file) - so the 
correct implementation is to pass the input as an argument and return 
the output:

> author_count = row[-1]
> story_per_author[author_count] = 1


def author_to_dict(csv_file):
 story_per_author = {}
 for row in csv_file:
 author_count = row[-1]
 story_per_author[author_count] = 1
 return story_per_author

Now take care: the object returned by csv.reader is not a sequence, it's 
an iterator. Once you've looped over all it's content, it's exhausted.

> #Fetch author names
> def rem_blank_authors(): 

same remark wrt/ comments

#Function to remove entries with '' in the
> AUTHOR field of the .csv

   # Convert the open file to list format
   # for e-z mode editing

> csv_list = list(csv_file) 

Yet another useless global.


 > for row in csv_list:
> author_name = row[-1]
> if author_name == '': #Find entries where no author is listed
> csv_list.remove(row) #Remove those entries from the list

Since you don't return anything from this function, the only effect is 
to consume the whole global csv_file iterator - the csv_list object is 
discarded after function execution.


> def assign_author_to_title(): #Assign an author to every title
> author_of_title = {}
> for row in csv_file:
> title = row[3]
> author = row[-1]
> author_of_title[title] = author

Same remarks here

> 
> assign_author_to_title()
> print author_of_title

author_of_title is local to the assign_author_to_title function. You 
cannot access it from outside.

> --
> 
> Ok, the last two lines are kind of my "test the last function" test.
> Now when I run these two lines I get the error:
> 
> Traceback (most recent call last):
22>   File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
> \scriptutils.py", line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "D:\Python25\csv_read.py", line 33, in 
> print author_of_title
> NameError: name 'author_of_title' is not defined
>
> I am guessing that the author_of_title dict does not exist outside of
> the function in which it is created? 

Bingo.

> The concept of instantiation is
> sort of foreign to me so I'm having some trouble predicting when it
> happens.

It has nothing to do with instanciation, it's about scoping rules. A 
named defined in a function is local to that function. If you create an 
object in a function and want to make it available to the outside world, 
you have to return it from the function - like I did the rewrite of 
author_to_dict - and of course assign this return value to another name 
in the caller function scope.

> If I call the assign_author_to_title function later, am I going to be
> able to work with the author_of_title dictionary? Or is it best if I
> create author_of_title outside of my function definitions?

By all mean avoid global variables. In all the above code, there's not a 
single reason to use them. Remember that functions take params and 
return values. Please take a little time to read more material about 
functions and scoping rules.

> Clearly I'm just stepping through my thought process right now,
> creating functions as I see a need for them. I'm sure the code is
> sloppy and terrible

Well... It might be better !-)

Ok, there are the usual CS-newbie-struggling-with-new-concepts errors. 
The cure is well-known : read more material (tutorials and code), 
experiment (Python is great for this - read about the '-i' option of the 
python interpreter), and post here when you run into trouble.

> but please be gentle!

Hope I haven't been to rude !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any simpler way to do this

2007-12-07 Thread Virgil Dupras
On Dec 7, 9:37 am, Lars Johansen <[EMAIL PROTECTED]> wrote:
> I have a function that looks like this:
>
> def Chooser(color):
>
> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x
>
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?
> --
> Lars Johansen <[EMAIL PROTECTED]>

"return getattr(term, color)" should do the trick.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Virgil Dupras
On Dec 7, 9:05 am, Matt_D <[EMAIL PROTECTED]> wrote:
> Hello there, this is my first post to the list. Only been working with
> Python for a few days. Basically a complete newbie to programming.
>
> I'm working with csv module as an exercise to parse out a spreadsheet
> I use for work.(I am an editor for a military journalism unit) Not
> trying to do anything useful, just trying to manipulate the data.
> Anyway, here's the code I've got so far:
>
> import csv
> import string
> import os
>
> #Open the appropriate .csv file
> csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))
>
> #Create blank dictionary to hold {[author]:[no. of stories]} data
> story_per_author = {}
>
> def author_to_dict(): #Function to add each author to the dictionary
> once to get initial entry for that author
> for row in csv_file:
> author_count = row[-1]
> story_per_author[author_count] = 1
>
> #Fetch author names
> def rem_blank_authors(): #Function to remove entries with '' in the
> AUTHOR field of the .csv
> csv_list = list(csv_file) #Convert the open file to list format
> for e-z mode editing
> for row in csv_list:
> author_name = row[-1]
> if author_name == '': #Find entries where no author is listed
> csv_list.remove(row) #Remove those entries from the list
>
> def assign_author_to_title(): #Assign an author to every title
> author_of_title = {}
> for row in csv_file:
> title = row[3]
> author = row[-1]
> author_of_title[title] = author
>
> assign_author_to_title()
> print author_of_title
>
> --
>
> Ok, the last two lines are kind of my "test the last function" test.
> Now when I run these two lines I get the error:
>
> Traceback (most recent call last):
>   File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
> \scriptutils.py", line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "D:\Python25\csv_read.py", line 33, in 
> print author_of_title
> NameError: name 'author_of_title' is not defined
>
> I am guessing that the author_of_title dict does not exist outside of
> the function in which it is created? The concept of instantiation is
> sort of foreign to me so I'm having some trouble predicting when it
> happens.
>
> If I call the assign_author_to_title function later, am I going to be
> able to work with the author_of_title dictionary? Or is it best if I
> create author_of_title outside of my function definitions?
>
> Clearly I'm just stepping through my thought process right now,
> creating functions as I see a need for them. I'm sure the code is
> sloppy and terrible but please be gentle!

As you said, author_of_title doesn't exist outside of
assign_author_to_title() because it has been instantiated in the
function, and thus belong to the local scope. You could instantiate
your dictionary outside of the function, but the nicest way to handle
this would be to add a line "return author_of_title" at the end of
assign_author_to_title() and have "print assign_author_to_title()"
instead of the 2 last lines.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I embed Windows Python in C# or VC++?

2007-12-07 Thread Virgil Dupras
On Dec 7, 9:03 am, grbgooglefan <[EMAIL PROTECTED]> wrote:
> On Dec 7, 3:07 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>
>
>
> > En Fri, 07 Dec 2007 01:24:57 -0300, grbgooglefan <[EMAIL PROTECTED]>  
> > escribió:
>
> > > On Dec 7, 12:17 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > > wrote:
> > >> En Thu, 06 Dec 2007 23:27:15 -0300, grbgooglefan <[EMAIL PROTECTED]>
> > >> escribió:
>
> > >> > I want to use Python's Windows (python25.dll) version to embed in my
> > >> > C# (or atleast VC++) program for performing syntax checks on the
> > >> > Python expressions which are later supposed to be evaluated at runtime
> > >> > by another C++ program [...]> Can I start doing the development using  
> > >> the include, lib & the
> > >> > python25.dll files availale after installing this MSI?
>
> > >> Yes. You don't require the source package to embed Python and use the  
> > >> API in your programs.
>
> > > Does it mean, I can embed Python in C# as well with the same APIs?
>
> > No; you can use the Python API in a native C++ application (the Python  
> > code is plain C, but all the include files have the 'extern "C" {}'  
> > declarations). For .NET there are IronPython and PythonNet, but I cannot  
> > comment on them, surely someone else may help. See  
> > http://www.python.org/about/
>
> > --
> > Gabriel Genellina- Hide quoted text -
>
> > - Show quoted text -
>
> Hello, Anybody else out there has used Python from C#?

Yes. I use Python for .Net to embed python code in my applications,
and it works pretty well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New subclass vs option in __init__

2007-12-07 Thread Carl Banks
On Dec 7, 9:36 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-12-07, Carl Banks <[EMAIL PROTECTED]> wrote:
>
> > On Dec 6, 11:56 am, "Kurt Smith" <[EMAIL PROTECTED]> wrote:
> >> It would seem that there are cases where one would be
> >> preferable over the other: a) when the new behavior would
> >> modify a large portion of the existing subclass, making a new
> >> subclass would be ideal; b) when the new behavior changes only
> >> slightly the existing subclass, perhaps a simple default
> >> option in the subclass's __init__ method would be best.  Where
> >> is the tipping point?
>
> > Good question.
>
> The major factor in the tipping point is clarity. And simplicity.
> The two major factors in deciding the tipping point are: clarity,
> simplicity, and extensibility. ... The THREE major tipping point
> factors ARE: clarity, simplicity, extensibility. And efficiency.
> Among the many factors in deciding the tipping point are: (etc.,
> etc.)

..., lots of experience, 20/20 foresight, a good Ouija board,
luck, 


Carl Banks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Neil Cerutti
On 2007-12-07, Duncan Booth <[EMAIL PROTECTED]> wrote:
> from __future__ import with_statement
>
> def loaddomainowners(domain):
> with open('/etc/virtual/domainowners','r') as infile:

I've been thinking I have to use contextlib.closing for
auto-closing files. Is that not so?

-- 
Neil Cerutti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does python build its AST

2007-12-07 Thread MonkeeSage
On Dec 7, 9:50 am, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On Dec 7, 3:23 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
>
> > A quick question about how python parses a file into compiled
> > bytecode. Does it parse the whole file into AST first and then compile
> > the AST, or does it build and compile the AST on the fly as it reads
> > expressions? (If the former case, why can't functions be called before
> > their definitions?)
>
> > Thanks,
> > Jordan
>
> Python uses a highly optimized table based LL(1) parser to create a
> syntax tree. In Python 2.5 it transforms the concrete syntax tree
> ( CST ) into an AST before compilation. Before that it compiled the
> CST directly. I'm not sure what you are asking for ( in parentheses )?
> Parser actions or preprocessing the tree? The latter is definitely
> possible and you can build your own compilation machinery using the
> parser module and the compile function.
>
> Kay

Thanks for your reply. You answered my main question. The secondary
question is why is it a NameError to try to use a variable/function
prior to the declaration in a source file, since python has already
seen the declaration on the first pass building the CST/AST? At
compile time, shouldn't it already know about it? (Forgive my
ignorance.)

Regards,
Jordan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread supercooper
On Dec 7, 8:15 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> On 7 Dez., 14:34, supercooper <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 7, 7:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
>
> > > From a zone-file of a Microsoft Active Directory integrated DNS server
> > > I get the date/time of the dynamic update entries in a format, which
> > > is as far as I know the hours since january 1st 1901.
> > > For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
> > > Excel I use this:
> > > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> > > 3566839 in field A1 and switch the format of the result-field to the
> > > corresponding date-time format).
>
> > > You might guess what I need now: I want to calculate this somehow in
> > > python.
>
> > > Sorry, but I couldn't find anything in the module time or something
> > > else to get this calculated.
>
> > > Does anyone know how to convert this time in python to something
> > > usable or how to convert this formula in python?
>
> > > Thanks a lot and regards
> > > Dirk
>
> > I think you want the xldate_as_tuple function in the xlrd module:
>
> >http://www.lexicon.net/sjmachin/xlrd.htm
>
> > It works like a champ for me:
>
> > >>> import xlrd
> > >>> xlrd.xldate.xldate_as_tuple(38980,0)
>
> > (2006, 9, 20, 0, 0, 0)
>
> > chad!
>
> Thanks so far, that comes close to a solution I think, BUT when I
> enter 3566985 instead of 38980 I get the following error:
> Traceback (most recent call last):
>   File "test.py", line 20, in 
> print xlrd.xldate.xldate_as_tuple(3566985,0)
>   File "C:\Python25\lib\site-packages\xlrd\xldate.py", line 75, in
> xldate_as_tuple
> raise XLDateTooLarge(xldate)
> xlrd.xldate.XLDateTooLarge: 3566985
>
> Do I have to use another function of this module? My number is 2
> digits shorter than yours. What is 38980 representing?
>
> Dirk

Excel stores dates as floating point
numbers; the number of days (or fraction thereof) since
12/31/1899. So 38980.0 is midnight 9/20/2006. You think your numbers
represent
the number of hours since 1/1/1901?

3,566,985 hrs/24 hrs in a day = ~148,618 days
148,618 days/365 days in a year = ~407 years

Am I doing the math wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


module organization/inheritance problem

2007-12-07 Thread km
Hi all,

I have a python module (M) with the following structure
M (directory)
   | __init__.py   (class Base(object) ...)
   | - a.py   (class A(Base) ...)
   | - b.py   (class B(Base) ...)
   | - c.py   (class C(Base) ...)

The __init_.py has a class which all the sub-modules (a,b,c)  classes
inherit from.
* The class has  an __init__ method which imports certian modules  and
nothing more
* Each submodule (a,b,c) has a class each which are derived from the class
defined in __init__.py
* Each submodule's classe's __init__  method extends the base class __init__
method and imports some more modules specific to be used in that class

I have thought of such subclassing to avoid repetition of importing modules
across the directory hierarchy beneath.
Now is the class defined in __init__.py is not acessible to the submodules.
what could be done to make it work ? am i missing something ?


regards,
KM
-- 
http://mail.python.org/mailman/listinfo/python-list

Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Dirk Hagemann
Hello,

>From a zone-file of a Microsoft Active Directory integrated DNS server
I get the date/time of the dynamic update entries in a format, which
is as far as I know the hours since january 1st 1901.
For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
Excel I use this:
="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
3566839 in field A1 and switch the format of the result-field to the
corresponding date-time format).

You might guess what I need now: I want to calculate this somehow in
python.

Sorry, but I couldn't find anything in the module time or something
else to get this calculated.

Does anyone know how to convert this time in python to something
usable or how to convert this formula in python?

Thanks a lot and regards
Dirk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite or xml

2007-12-07 Thread Paul Boddie
On 7 Des, 09:31, Kelie <[EMAIL PROTECTED]> wrote:
>
> Ah, now you're making it hard for me to decide again. :-) Talking
> about comfortable, I do like Amara XML toolkit a lot. But I'll stick
> with sqlite in this case.

As a user of unfashionable XML technologies *and* relational database
systems, I'd also recommend that you stick with whatever is more
convenient: a couple of thousand records is not a big database, even
for sqlite, and you could probably load the data into a DOM on modern
hardware (although not necessarily a Web browser DOM, but that's
another topic). The main differentiator is likely to be the
convenience of querying and making edits, especially if the latter is
of any interest, with efficiency only making an appearance if you're
doing intensive or sophisticated queries (as opposed to infrequent
"one off" queries). Indeed, if you're likely to be changing the data,
the relational database approach starts to look more attractive
because you won't need to play around with whichever document
structure that your XML library employs, although updating large parts
of a hierarchy through some DOM-like API can be easier than a plain
SQL-based relational approach.

Some people might recommend sqlite plus an object-relational mapper,
but leaving my own skepticism for object-relational mappers to one
side, if you're tempted to combine the two, I'd argue that sticking
with XML would probably be sufficient in this situation. I suppose
that XML databases are meant to be the ultimate hybrid of object-
oriented data manipulation and efficient access to the data (indexing
and so on), but I can't comment on their merits personally.

Paul
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Giles Brown
On 7 Dec, 13:20, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> Hello,
>
> From a zone-file of a Microsoft Active Directory integrated DNS server
> I get the date/time of the dynamic update entries in a format, which
> is as far as I know the hours since january 1st 1901.
> For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
> Excel I use this:
> ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-field to the
> corresponding date-time format).
>
> You might guess what I need now: I want to calculate this somehow in
> python.
>
> Sorry, but I couldn't find anything in the module time or something
> else to get this calculated.
>
> Does anyone know how to convert this time in python to something
> usable or how to convert this formula in python?
>
> Thanks a lot and regards
> Dirk

Something is a bit off here...

"""
>>> import datetime
>>> timezero=datetime.datetime(1901, 1, 1)
>>> timezero+datetime.timedelta(hours= 3566839)
datetime.datetime(2307, 11, 27, 7, 0)
"""

Giles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread mrkafk

Duncan Booth wrote:
> Just some minor points without changing the basis of what you have done
> here:

All good points, thanks. Phew, there's nothing like peer review for
your code...

> But why do you construct a dict from that input data simply to throw it
> away?

Because comparing strings for equality in a loop is writing C in
Python, and that's
exactly what I'm trying to unlearn.

The proper way to do it is to produce a dictionary and look up a value
using a key.

>If you only want 1 domain from the file just pick it out of the list.

for item in list:
if item == 'searched.domain':
return item...

Yuck.


> with open('/etc/virtual/domainowners','r') as infile:
> pairs = [ line.split(':',1) for line in infile if ':' in line ]

Didn't think about doing it this way. Good point. Thx

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eclipse pywintypes.com_error

2007-12-07 Thread kyosohma
On Dec 7, 9:10 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Spindle wrote:
> > I checked the key,and it was found under HKEY_CLASSES_ROOT.And as i
> > mentioned before,
> > the problem happens only with eclipse and pydev,on the same machine i
> > can run the script from command line or with IDLE without any errors.
>
> Well, that's bizarre then. Hopefully someone else can chime in
> with an idea.
>
> TJG

This is just a theory, but since Vista is supposed to be more secure,
maybe Eclipse doesn't have the "rights" to access that particular
registry entry. I recall reading that Norton and McAfee had a lot of
trouble getting access to Vista's internals...

I'm not sure why Python would though. I've also heard that if such-and-
such a program isn't installed in the correct place, it doesn't always
function correctly, so that might be the issue too.

Then again, maybe I'm just blowing smoke.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Some python syntax that I'm not getting

2007-12-07 Thread Chris
On Dec 7, 2:31 pm, waltbrad <[EMAIL PROTECTED]> wrote:
>
> I understand how D['say'] gets you 5,  But I still don't understand
> the line after the 5.
>
> How is the character 's' some special code?  And I don't get what is
> going on with the % character.  I'm used to it's use in c-style
> formatting, but this just seems so bizarre.  I can tell that the key
> is being replaced by it's value in the string, but I don't know how
> that is being done.
>
> TIA

http://docs.python.org/lib/typesseq-strings.html

The '%' invokes the formatter, the 's' specifies string type.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which configparse?

2007-12-07 Thread Sion Arrowsmith
Neal Becker  <[EMAIL PROTECTED]> wrote:
>I've looked at configparse, cfgparse, iniparse.
>
>configparse looks like what I want, but it seems last commit was >2years
>ago.
>
>What is the best choice?

ConfigParser is the battery included in the standard library. If
you're planning on distributing your script, consider the value
of this.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Gnu/Linux dialogue boxes in python

2007-12-07 Thread kyosohma
On Nov 30, 7:55 am, Donn Ingle <[EMAIL PROTECTED]> wrote:
> Hi,
>  Okay, so I am in the mood to try this: Inform the user about what modules
> the app requires in a graphical dialogue that can vary depending on what
> the system already has installed. (It will fail-to output on cli)
>
> I am running Kubuntu and I seem to have 'kdialog' installed by default (not
> sure if it came as stock.)
>
> What other 'stock' systems are there out there in the wild? Ubuntu? Suse?
> Fedora? Others?
>
> I would take a stab at wrapping them in python so that I can use the first
> dialogue system found to popup messages for the user.
>
> (Hoping, natch, that this has already been done ... ? )
>
> \d

If you built a GUI with wxPython, it would just use the OS's native
dialogs unless it didn't have one and then it would use a generic
dialog. I would think creating a installer with wxPython and threads
would be fairly trivial.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Class Best Practice

2007-12-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Dec 5, 12:18 am, Rod Person <[EMAIL PROTECTED]> wrote:
>> -BEGIN PGP SIGNED MESSAGE-
>> Hash: SHA1
>>
>> I've been doing python programming for about 2 years as a hobby and now
>> I'm finally able to use it at work in an enterprise environment. Since
>> I will be creating the base classes and libraries I wondering which why
>> is consider best when creating python classes:
>>
>> 1:
>> class Foo(object):
>>   member1=''
>>   member2=0
>>
>>   def __init__(self,member1='',member2=0):
>> self.member1 = member1
>> self.member2 = member2
>>
>> 2:
>> class Foo(object):
>> def  __init(self,member1='',member2=0):
>> self.member1 = member1
>> self.member2 = member2
>>
> 
> 
> The short answer : if 2 works, then stick with it.

The yet-even-shorter-answer: 2

!-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Matt Nordhoff
Chris wrote:
> Ta Matt, wasn't paying attention to what I typed. :)
> And didn't know that about .get() and not having to declare the
> global.
> Thanks for my mandatory new thing for the day ;)

:-)
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Erros when compiling a CPP program which uses CPython API functions

2007-12-07 Thread Christian Heimes
grbgooglefan wrote:
> I am compiling CPP program which uses CPython API functions from
> Python 2.5.1 source code
> 
> First I compiled with this commanline, that time I got "pyconfig.h"
> not found.

On Unix you have to run ./configure and make before you can use a source
tree. It creates a valid pyconfig.h for you. You may want to use the
./configure option --enable-shared.

> So, I added "-I../../PC" to my cmd line to get pyconfig.h, like:

PC/pyconfig.h is for Windows only!


Christian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __iadd__ useless in sub-classed int

2007-12-07 Thread MonkeeSage
On Dec 7, 12:45 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Fri, 07 Dec 2007 03:01:28 -0300, MonkeeSage <[EMAIL PROTECTED]>
> escribió:
>
> > I've wondered about this myself. Seems to me, to prevent clobbering
> > subclasses, __iadd__ (and all of the integer and float and whatever)
> > methods that return new instances, should work like this (obviously I
> > mean in the C backend, this is just to show the behavior):
>
> > def __iadd__(self, other):
> >   return self.__class__(self + other)
>
> This would slow down *all* of Python, and is only useful for those who
> actually inherit from some builtin class (not so common)
>
> --
> Gabriel Genellina

I understand why it doesn't. It just *seems* like it should work that
way when you first run into it (and has bitten me a couple times
before). But then, I'm not Dutch. :)

Regard,
Jordan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any simpler way to do this

2007-12-07 Thread Tim Golden
Lars Johansen wrote:
> I have a function that looks like this:
> 
> def Chooser(color):
> 
> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x
> 
> 
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?

One option -- given your source code -- is this. Obviously this only
works if the color name exactly matches the attribute name.


def Chooser(color):
 return getattr(term, color, None)


If you needed to vary things then a dictionary lookup
is probably the best bet, eg:


def Chooser(color):
 color_map = {
   "RED" : term.RED,
   "BLUE" : term.AQUAMARINE
 }
 return color_map.get(color)


Obviously in either case you have to know what to do with
exceptions, but then that's true of your sample code as well.
My code mirrors yours in that None is returned if no match
is found.

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Erros when compiling a CPP program which uses CPython API functions

2007-12-07 Thread grbgooglefan
On Dec 7, 2:17 pm, grbgooglefan <[EMAIL PROTECTED]> wrote:
> On Dec 7, 12:32 pm, grbgooglefan <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > I am compiling CPP program which uses CPython API functions from
> > Python 2.5.1 source code
>
> > First I compiled with this commanline, that time I got "pyconfig.h"
> > not found.
> > g++ -Os -I../../Include ../../libpython2.5.a -lm -ldl -lpthread -lutil
> > testeval.cpp
> > In file included from testeval.cpp:1:
> > ../../Include/Python.h:8:22: pyconfig.h: No such file or directory
> > In file included from ../../Include/Python.h:57,  from
> > testeval.cpp:1:
> > ../../Include/pyport.h:4:48: pyconfig.h: No such file or directory
> > ../../Include/pyport.h:734:2: #error "LONG_BIT definition appears
> > wrong for platform (bad gcc/glibc config?)."
>
> > So, I added "-I../../PC" to my cmd line to get pyconfig.h, like:
> > g++ -Os -I../../Include -I../../PC/ ../../libpython2.5.a -lm -ldl -
> > lpthread -lutil testeval.cpp
>
> > As soon as I ran this command I got a long list of errors as shown
> > below.
> > Why the dllimport errors are coming? I did not get these errors when I
> > did same compilation with Python 2.2.3.
> > Please help. Thanks.
>
> > In file included from ../../Include/Python.h:76,  from
> > testeval.cpp:1:
> > ../../Include/pymem.h:50: `dllimport' was not declared in this scope
> > ../../Include/pymem.h:50: ISO C++ forbids declaration of `__declspec'
> > with notype
> > ../../Include/pymem.h:50: syntax error before `void'
> > ../../Include/pymem.h:51: `dllimport' was not declared in this scope
> > ../../Include/pymem.h:51: ISO C++ forbids declaration of `__declspec'
> > with notype
> > ../../Include/pymem.h:51: redefinition of `int __declspec'
> > ../../Include/pymem.h:50: `int __declspec' previously defined here
> > ../../Include/pymem.h:51: syntax error before `void'
> > ../../Include/pymem.h:52: `dllimport' was not declared in this scope
> > ../../Include/pymem.h:52: ISO C++ forbids declaration of `__declspec'
> > with notype
> > ../../Include/pymem.h:52: redefinition of `int __declspec'
> > ../../Include/pymem.h:51: `int __declspec' previously defined here
> > ../../Include/pymem.h:52: syntax error before `void'
> > In file included from ../../Include/Python.h:78,  from
> > testeval.cpp:1:
> > ../../Include/object.h:371: `dllimport' was not declared in this scope
> > ../../Include/object.h:371: ISO C++ forbids declaration of
> > `__declspec' with notype
> > ../../Include/object.h:371: redefinition of `int __declspec'
> > ..
> > ../../Include/Python.h:134: redefinition of `int __declspec'
> > ../../Include/pystrtod.h:11: `int __declspec' previously defined here
> > ../../Include/Python.h:134: syntax error before `*' token
> > testeval.cpp: In function `int main(int, char**)':
> > testeval.cpp:94: `Py_Initialize' undeclared (first use this function)
> > testeval.cpp:94: (Each undeclared identifier is reported only once for
> > each
> >function it appears in.)
> > testeval.cpp:95: `PyRun_SimpleStringFlags' undeclared (first use this
> > function)
>
> I am doing this on following Linux OS config:
> Linux njl36a-7003 2.4.21-9.0.1.ELsmp #1 SMP Mon Feb 9 22:26:51 EST
> 2004 i686 i686 i386 GNU/Linux>cat /etc/redhat-release
>
> Red Hat Enterprise Linux AS release 3 (Taroon Update 1)- Hide quoted text -
>
> - Show quoted text -

This is resolved when I used the pyconfig.h file not from Python-2.5.1/
PC/pyconfig.h but the top level which is Python-2.5.1/pyconfig.h
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread david
On Fri, 07 Dec 2007 16:46:56 +0100, Glauco wrote:

> [EMAIL PROTECTED] ha scritto:
>> Hello everyone,
>> 
>> I have written this small utility function for transforming legacy file
>> to Python dict:
>> 
>> 
>> def lookupdmo(domain):
>> lines = open('/etc/virtual/domainowners','r').readlines() lines
>> = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
>> lines]
>> lines = [ x for x in lines if len(x) == 2 ] d = dict()
>> for line in lines:
>> d[line[0]]=line[1]
>> return d[domain]
>> 
>> 
> cache = None
> 
> def lookup( domain ):
> if not cache:
>cache = dict( [map( lambda x: x.strip(), x.split(':'))  for x in
> open('/etc/virtual/domainowners','r').readlines()])
> return cache.get(domain)
> 

>>> lookup(1)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in lookup
UnboundLocalError: local variable 'cache' referenced before assignment

You miss the:
def lookup(domain):
global cache
...

bye
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Nested Functions & Lambda Expressions

2007-12-07 Thread Terry Jones
> "Duncan" == Duncan Booth <[EMAIL PROTECTED]> writes:
Duncan> Terry Jones <[EMAIL PROTECTED]> wrote:
>> Duncan Booth wrote:

Duncan> You'll kick yourself for not seeing it.
Duncan> If you changed fn_inner to:

Duncan> def fn_inner():
Duncan> a, v = v, a

Duncan> then you also changed 'a' and 'v' into local variables.
Duncan> LOAD/STORE_FAST is used to access local variables, LOAD/STORE_DEREF
Duncan> are used to access variables in an outer scope.

Argh, yes :-)  [Cue background sound of kicking self]

Thanks.

Terry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite or xml

2007-12-07 Thread Kelie
On Dec 6, 3:37 pm, [EMAIL PROTECTED] wrote:
> If you're happy going with sqlite then stick with it.  If on the other
> hand you were considering XML because you're more comfortable with
> that (e.g. you find XML easy to work with and you're more familiar
> with XPath/XQuery than SQL) then you could use XML if you wanted.  The
> choice is not between XML and databases, it's between XML and
> relational. There are -- shock-horror! -- full-featured XML databases
> too (e.g. Berkeley DB XML, which is lightweight, fast, embeddable and
> open source like sqlite, with indexing, transactions etc. if you need
> that).

Tim?

Ah, now you're making it hard for me to decide again. :-) Talking
about comfortable, I do like Amara XML toolkit a lot. But I'll stick
with sqlite in this case.

Thanks for your valuable input and for mentioning Berkeley DB XML. I
didn't know about it and will have to read about it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any simpler way to do this

2007-12-07 Thread Chris
On Dec 7, 10:37 am, Lars Johansen <[EMAIL PROTECTED]> wrote:
> I have a function that looks like this:
>
> def Chooser(color):
>
> if color == "RED":
> x = term.RED
> elif color == "BLUE":
> x = term.BLUE
> elif color == "GREEN":
> x = term.GREEN
> elif color == "YELLOW":
> x = term.YELLOW
> elif color == "CYAN":
> x = term.CYAN
> elif color == "MAGENTA":
> x = term.MAGENTA
> return x
>
> Wouldn there been easier if I could just skip all the "*if's" and just
> "return term.color", however this gives a syntax error, are there any
> clever way to do this ?
> --
> Lars Johansen <[EMAIL PROTECTED]>

def Chooser(color):
return getattr(term, color)

You could also do:

def Chooser(color):
return getattr(term, colour, 'Default response if colour doesn't
exist')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-07 Thread Matt_D
On Dec 7, 11:42 am, Virgil Dupras <[EMAIL PROTECTED]>
wrote:
> On Dec 7, 9:05 am, Matt_D <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello there, this is my first post to the list. Only been working with
> > Python for a few days. Basically a complete newbie to programming.
>
> > I'm working with csv module as an exercise to parse out a spreadsheet
> > I use for work.(I am an editor for a military journalism unit) Not
> > trying to do anything useful, just trying to manipulate the data.
> > Anyway, here's the code I've got so far:
>
> > import csv
> > import string
> > import os
>
> > #Open the appropriate .csv file
> > csv_file = csv.reader(open("D:\\Python25\\BNSR.csv"))
>
> > #Create blank dictionary to hold {[author]:[no. of stories]} data
> > story_per_author = {}
>
> > def author_to_dict(): #Function to add each author to the dictionary
> > once to get initial entry for that author
> > for row in csv_file:
> > author_count = row[-1]
> > story_per_author[author_count] = 1
>
> > #Fetch author names
> > def rem_blank_authors(): #Function to remove entries with '' in the
> > AUTHOR field of the .csv
> > csv_list = list(csv_file) #Convert the open file to list format
> > for e-z mode editing
> > for row in csv_list:
> > author_name = row[-1]
> > if author_name == '': #Find entries where no author is listed
> > csv_list.remove(row) #Remove those entries from the list
>
> > def assign_author_to_title(): #Assign an author to every title
> > author_of_title = {}
> > for row in csv_file:
> > title = row[3]
> > author = row[-1]
> > author_of_title[title] = author
>
> > assign_author_to_title()
> > print author_of_title
>
> > --
>
> > Ok, the last two lines are kind of my "test the last function" test.
> > Now when I run these two lines I get the error:
>
> > Traceback (most recent call last):
> >   File "D:\Python25\Lib\SITE-P~1\PYTHON~1\pywin\framework
> > \scriptutils.py", line 310, in RunScript
> > exec codeObject in __main__.__dict__
> >   File "D:\Python25\csv_read.py", line 33, in 
> > print author_of_title
> > NameError: name 'author_of_title' is not defined
>
> > I am guessing that the author_of_title dict does not exist outside of
> > the function in which it is created? The concept of instantiation is
> > sort of foreign to me so I'm having some trouble predicting when it
> > happens.
>
> > If I call the assign_author_to_title function later, am I going to be
> > able to work with the author_of_title dictionary? Or is it best if I
> > create author_of_title outside of my function definitions?
>
> > Clearly I'm just stepping through my thought process right now,
> > creating functions as I see a need for them. I'm sure the code is
> > sloppy and terrible but please be gentle!
>
> As you said, author_of_title doesn't exist outside of
> assign_author_to_title() because it has been instantiated in the
> function, and thus belong to the local scope. You could instantiate
> your dictionary outside of the function, but the nicest way to handle
> this would be to add a line "return author_of_title" at the end of
> assign_author_to_title() and have "print assign_author_to_title()"
> instead of the 2 last lines.

Another newb question, same project:

#Fetch author names
def rem_blank_authors(): #Function to remove entries with '' in the
AUTHOR field of the .csv
csv_list = list(csv_file) #Convert the open file to list format
for e-z mode editing
for row in csv_list:
author_name = row[-1]
if author_name == '': #Find entries where no author is listed
csv_list.remove(row) #Remove those entries from the list
return csv_list

def author_to_dict(): #Function to add each author to the dictionary
once to get initial entry for that author
#rem_blank_authors() #Call this function to remove blank author
fields before building the main dictionary
for row in csv_file:
author_count = row[-1]
if author_count in story_per_author:
story_per_author[author_count] += 1
else:
story_per_author[author_count] = 1
return story_per_author

def assign_author_to_title(): #Assign an author to every title
author_of_title = {}
for row in csv_file:
title = row[3]
author = row[-1]
author_of_title[title] = author

author_to_dict()
print story_per_author

--

The solution provided for my previous post worked out. Now I'm testing
the author_to_dict function, modified to get an accurate count of
stories each author has written. Now, if I call rem_blank_authors,
story_per_author == {}. But if I #comment out that line, it returns
the expected key values in story_per_author. What is happening in
rem_blank_authors that is returning no keys in the dictionary?

I'm afraid I don't really understand the mechanics of "return" and
searching the docs hasn't yielded too much help since "return" is such
a common word (in both the Python 2.5

Re: eclipse pywintypes.com_error

2007-12-07 Thread Tim Golden
Spindle wrote:
> I checked the key,and it was found under HKEY_CLASSES_ROOT.And as i
> mentioned before,
> the problem happens only with eclipse and pydev,on the same machine i
> can run the script from command line or with IDLE without any errors.

Well, that's bizarre then. Hopefully someone else can chime in
with an idea.

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does python build its AST

2007-12-07 Thread Kay Schluehr
On Dec 7, 3:23 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
> A quick question about how python parses a file into compiled
> bytecode. Does it parse the whole file into AST first and then compile
> the AST, or does it build and compile the AST on the fly as it reads
> expressions? (If the former case, why can't functions be called before
> their definitions?)
>
> Thanks,
> Jordan

Python uses a highly optimized table based LL(1) parser to create a
syntax tree. In Python 2.5 it transforms the concrete syntax tree
( CST ) into an AST before compilation. Before that it compiled the
CST directly. I'm not sure what you are asking for ( in parentheses )?
Parser actions or preprocessing the tree? The latter is definitely
possible and you can build your own compilation machinery using the
parser module and the compile function.

Kay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> 
>> The csv module is your friend.
> 
> (slapping forehead) why the Holy Grail didn't I think about this? 

If that can make you feel better, a few years ago, I spent two days 
writing my own (SquaredWheel(tm) of course) csv reader/writer... before 
realizing there was such a thing as the csv module :-/

Should have known better...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Gnu/Linux dialogue boxes in python

2007-12-07 Thread Jorgen Grahn
On Sun, 02 Dec 2007 17:18:45 +0200, Donn Ingle <[EMAIL PROTECTED]> wrote:
>> But why?  Either
>> 
>> (a) your program has a GUI and can display a dialogue box by itself
>> (b) your program has a GUI but has problems opening even a tiny part
>> of it (missing modules?), and should output diagnostics on the terminal
>> (c) your program is console-based, or a daemon or something, and should
>> not require a GUI to work.
>> 
> I realise those things, and it's the simplest case. 
>
>  I was thinking of  allow a setup.py file to
> be double-clicked and have the install start to run. When it comes to the
> bit where all the import statements happen, it can popup a stock dialogue
> informing the user about what they need to install first.

But does "setup.py install" really trigger any of your code's imports?
I must admit I haven't give it much thought.

Somehow this seems like setup.py's job, and if it cannot do it maybe
someone should invent an alternative.

Or maybe it's setup.py's job to create a suitable distribution:

./setup.py --help-commands
  ...
  bdistcreate a built (binary) distribution
  bdist_dumb   create a "dumb" built distribution
  bdist_rpmcreate an RPM distribution
  bdist_wininstcreate an executable installer for MS Windows

"bdist_wininst" has a very nice GUI.  But I doubt that you can
make it warn for unmet dependencies.

>  Another thing to realize, and I have experienced this first-hand, is that a
> bunch of text, no matter how nicely formatted, spewed out of an app in
> white on black ( the usual terminal colours ) does *not* invite a user's
> attention. To read it is a chore and they usually panic.

I have experienced it too. I have tried to understand it, and failed.
Do they read books and newspapers? They are generally not stupid.


So what you really want is a nice GUI Python installer for Linux,
which everyone can use, and which can explain to users that they need
some other packages first.  Yes, that sounds like a very reasonable
thing to want.


/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Speed of Nested Functions & Lambda Expressions

2007-12-07 Thread Duncan Booth
Terry Jones <[EMAIL PROTECTED]> wrote:

> Duncan Booth wrote:
> 
>> You can use Python's bytecode disassembler to see what actually gets 
>> executed here:
>> 
>> >>> def fn_outer(v):
>> a=v*2
>> def fn_inner():
>> print "V:%d,%d" % (v,a)
>> 
>> fn_inner()
>> 
>> >>> import dis
>> >>> dis.dis(fn_outer)
>>   2   0 LOAD_DEREF   1 (v)
> [snip]
[snip]
> 
> I'd like to understand what it is that triggers the use of
> LOAD/STORE_DEREF versus LOAD/STORE_FAST. This seems dependent on how
> fn_inner above uses the a and v variables. If I change the print
> "V:%d,%d" % (v,a) line to be something like (a, v) = (v, a) or do
> other simple uses and assignments to a and v, LOAD/STORE_FAST is used.
> It seems that it's the use of print (in this case) that triggers the
> use of LOAD/STORE_DEREF in the bytecode. 

> Can anyone shed more light on what in general causes the switch to
> LOAD/STORE_DEREF?

You'll kick yourself for not seeing it.

If you changed fn_inner to:

  def fn_inner():
  a, v = v, a

then you also changed 'a' and 'v' into local variables. LOAD/STORE_FAST is 
used to access local variables, LOAD/STORE_DEREF are used to access 
variables in an outer scope.

There is no way in Python 2.x to rebind a name from a nested scope: any 
name you use as a target of an assignment is always either a local variable 
or a global variable.

(Actually, that's a lie, Google some of my old posts if you want to know 
how to rebind a name in a nested scope, but I warn you in advance it is 
really hackish and not something you would ever do for real.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Dirk Hagemann
On 7 Dez., 16:50, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> On 7 Dez., 16:21, Tim Golden <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > On Dec 7, 7:20�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> > >> Hello,
>
> > >> From a zone-file of a Microsoft Active Directory integrated DNS server
> > >> I get the date/time of the dynamic update entries in a format, which
> > >> is as far as I know the hours since january 1st 1901.
>
> > If it *is* then the easiest way is this:
>
> > 
> > import datetime
> > print datetime.date (1901, 1, 1) + datetime.timedelta (hours=3566839)
>
> > 
>
> > But, as someone pointed out, that puts you somewhere in 2300.
> > Where are you getting the 1901 from (and the hours, for that
> > matter). If it's based, as AD dates are, for example, from 1601,
> > then the calc becomes:
>
> > 
> > import datetime
> > print datetime.date (1601, 1, 1) + datetime.timedelta (hours=3566839)
>
> > 
>
> > which looks more realistic. But frankly I'm guessing.
>
> > TJG
>
> (3566839/24)/365 = 407   - YES I did this calculation too and was
> surprised. But if you try this out in MS Excel:
>  ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-fieldby right-
> click on it to the
> date format "14.3.01 13:30")
>
> and then replace 3566839 by, let's say, "2", Excel calculates the date
> 01.10.1901 2:00 AM. Try out other values like 5 or 24! So I thought
> 3566839 represents hours.
>
> Dirk

Oh - sorry again: in the Excel formula replace also ZEIT with TIME.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: eclipse pywintypes.com_error

2007-12-07 Thread Tim Golden
gurkan wrote:
> i have treid the script :
> 
> #import active_directory
> import win32com.client
> 
> win32com.client.Dispatch ("ADODB.Command")
> #me = active_directory.find_user ()
> 
> #print me
> 
> again i got the error :
> 
> Traceback (most recent call last):
>   File "H:\dev\eclipse\workspace\pyProject\src\pyPackage
> \adDeneme3.py", line 4, in 
> win32com.client.Dispatch ("ADODB.Command")
>   File "E:\Python25\Lib\site-packages\win32com\client\__init__.py",
> line 95, in Dispatch
> dispatch, userName =
> dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
>   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> line 98, in _GetGoodDispatchAndUserName
> return (_GetGoodDispatch(IDispatch, clsctx), userName)
>   File "E:\Python25\Lib\site-packages\win32com\client\dynamic.py",
> line 78, in _GetGoodDispatch
> IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx,
> pythoncom.IID_IDispatch)
> pywintypes.com_error: (-2147024770, 'The specified module could not be
> found.', None, None)

I don't think it's that the CoCreateInstance can't be found:
that's a COM error you're seeing and it means that the
IDispatch mechanism can't find the "ADODB.Command" you're
looking for. If I get the chance I'll try to find a Vista
machine to find out what the equivalent is. If anyone on
the list has Vista and/or knows what the score is here,
please let me know.

To double-check, Gurkan, could you open the Registry and
browse to HKEY_CLASSES_ROOT and look for a key ADODB.Command.
I presume it's not present.

TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread supercooper
On Dec 7, 7:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> Hello,
>
> From a zone-file of a Microsoft Active Directory integrated DNS server
> I get the date/time of the dynamic update entries in a format, which
> is as far as I know the hours since january 1st 1901.
> For Example: the number 3566839 is 27.11.07 7:00. To calculate this in
> Excel I use this:
> ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-field to the
> corresponding date-time format).
>
> You might guess what I need now: I want to calculate this somehow in
> python.
>
> Sorry, but I couldn't find anything in the module time or something
> else to get this calculated.
>
> Does anyone know how to convert this time in python to something
> usable or how to convert this formula in python?
>
> Thanks a lot and regards
> Dirk

I think you want the xldate_as_tuple function in the xlrd module:

http://www.lexicon.net/sjmachin/xlrd.htm

It works like a champ for me:

>>> import xlrd
>>> xlrd.xldate.xldate_as_tuple(38980,0)
(2006, 9, 20, 0, 0, 0)
>>>

chad!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ftplib.nlst gives error on empty directory

2007-12-07 Thread Giampaolo Rodola'
On 7 Dic, 10:42, loial <[EMAIL PROTECTED]> wrote:
> Trying to use ftplib.FTP.nlst()  method to list the files in
> a directory on a FTP server.
>
> It works fine except when there are no files in the directory. Then it
> gives the error
>
> ftplib.error_perm: 550 No files found.
>
> How can I handle this cleanly?

That's the response which comes straight from the server and that
causes ftplib to raise the error_perm exception.
imho, the culprit is the server since it shouldn't return that kind of
response which clashes with the RFC-959 standard specification.
Anyway, to avoid that you could just put your code into a try/except
statement:

try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "Directory is empty."
else:
raise
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python and a 2 gigs Usb Stick (pure pythonic stick)

2007-12-07 Thread Tim Chase
> i've received for my birthday two usb key, and i had the idea to make
> the 2GB one a special python usb key.
> So far i've put on it :
> Movable Python
> My Python directory
> Iron Python
> Jython
> Instant django
> 
> the file installation for :
> Python , iron python , jython , PIL , Pygame , Pywin32
> 
> The pdf in a doc_programmation :
> dive into python , programmting python
> 
> What else should i add in this key in your opinion ?

If providing Jython, do you need an install of the JVM/JRE or
other Java dev-tools?

I'd recommend some sort of version control software (Subversion,
Mercurial, Bazaar, and Git stand out as reasonable choices in my
research/experience, with RCS coming in as a fallback; CVS and
the distributed VCS's such as Darcs fall lower on my list but
some folks swear by 'em).

Perhaps also include a movable version of your favorite editor?
Nothing worse than getting stuck using Notepad, edit, or edlin ;)

Given that the above list of contents shouldn't come remotely
close to a quarter of the space on the stick (exceptions possibly
made depending on your editor and JRE requirements), you could
install a USB-stick version of Linux, add  all the above, and
then just boot off the USB stick into a premade environment you
can take with you.

Just a few ideas,

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Chris
On Dec 7, 1:31 pm, [EMAIL PROTECTED] wrote:
> Hello everyone,
>
> I have written this small utility function for transforming legacy
> file to Python dict:
>
> def lookupdmo(domain):
> lines = open('/etc/virtual/domainowners','r').readlines()
> lines = [ [y.lstrip().rstrip() for y in x.split(':')] for x in
> lines]
> lines = [ x for x in lines if len(x) == 2 ]
> d = dict()
> for line in lines:
> d[line[0]]=line[1]
> return d[domain]
>
> The /etc/virtual/domainowners file contains double-colon separated
> entries:
> domain1.tld: owner1
> domain2.tld: own2
> domain3.another: somebody
> ...
>
> Now, the above lookupdmo function works. However, it's rather tedious
> to transform files into dicts this way and I have quite a lot of such
> files to transform (like custom 'passwd' files for virtual email
> accounts etc).
>
> Is there any more clever / more pythonic way of parsing files like
> this? Say, I would like to transform a file containing entries like
> the following into a list of lists with doublecolon treated as
> separators, i.e. this:
>
> tm:$1$$:1010:6::/home/owner1/imap/domain1.tld/tm:/sbin/nologin
>
> would get transformed into this:
>
> [ ['tm', '$1$$', '1010', '6', , '/home/owner1/imap/domain1.tld/
> tm', '/sbin/nologin'] [...] [...] ]

For the first one you are parsing the entire file everytime you want
to lookup just one domain.  If it is something reused several times
during your code execute you could think of rather storing it so it's
just a simple lookup away, for eg.

_domain_dict = dict()
def generate_dict(input_file):
finput = open(input_file, 'rb')
global _domain_dict
for each_line in enumerate(finput):
line = each_line.strip().split(':')
if len(line)==2: _domain_dict[line[0]] = line[1]

finput.close()

def domain_lookup(domain_name):
global _domain_dict
try:
return _domain_dict[domain_name]
except KeyError:
return 'Unknown.Domain'


Your second parsing example would be a simple case of:

finput = open('input_file.ext', 'rb')
results_list = []
for each_line in enumerate(finput.readlines()):
results_list.append( each_line.strip().split(':') )
finput.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread mrkafk


Glauco wrote:

> cache = None
>
> def lookup( domain ):
> if not cache:
>cache = dict( [map( lambda x: x.strip(), x.split(':'))  for x in
> open('/etc/virtual/domainowners','r').readlines()])
> return cache.get(domain)

Neat solution! It just needs small correction for empty or badly
formed lines:

dict([map( lambda x: x.strip(), x.split(':'))  for x in open('/etc/
virtual/domainowners','r') if ':' in x])

-- 
http://mail.python.org/mailman/listinfo/python-list


Open Source Symposium CFP ending soon

2007-12-07 Thread Jeremy Fluhmann
Just a reminder that there's only one week left for the Open Source
Symposium Call For Participation!  http://www.texasoss.org/cfp (Deadline is
December 15th)

If you've been considering submitting, but aren't sure, I encourage you to
go ahead and submit!  I know several of you present at your user group
meetings and aren't afraid to speak in front of a large audience.  The
number of submissions are a little low right now, but it's to be expected
since they usually all pour in during the last week (and some even after the
deadline).

Once a few more talks start coming in, I'll likely post some of the topics
on the schedule page.  This may give you an idea about something you may
want to submit.  Remember, the topic range is wide and covers any aspect of
open source that you'd like to talk about.


Symposium updates:
I've finally setup a new blog for news and updates.  You can subscribe to
the feed from the from the News page (http://www.texasoss.org/news ), or
from the blog directly at http://blog.texasoss.org/

There's an IRC channel on Freenode, #texasoss

There is a panel session planned for the second day of the conference.
Topic is currently TBD.  More information will be posted to the site and
blog.


CFP submissions:
To submit a proposal, please e-mail [EMAIL PROTECTED] with the
following information:
Your Name
Your Email
[optional] Short Bio
Presentation Title
Presentation Abstract
[optional] Links to your presentation
Time slot (20, 50 minute, or requested time)

Please visit http://www.texasoss.org/cfp for more information.

Thanks,
Jeremy Fluhmann
Open Source Symposium 2008
http://www.texasoss.org/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: weird embedding problem

2007-12-07 Thread DavidM
On Fri, 07 Dec 2007 00:53:15 -0800, Graham Dumpleton wrote:

> Are you actually linking your C program against the Python library?

Yes. Refer OP:

>> I'm embedding python in a C prog which is built as a linux shared lib.
>> The prog is linked against libpython, and on startup, it calls
>> Py_Initialize().
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File to dict

2007-12-07 Thread Chris
Ta Matt, wasn't paying attention to what I typed. :)
And didn't know that about .get() and not having to declare the
global.
Thanks for my mandatory new thing for the day ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to browse a C Library with Python

2007-12-07 Thread georg.heiss
On 5 Dez., 21:03, "Rafael Sachetto" <[EMAIL PROTECTED]> wrote:
> This could be a solution
>
> import commands
>
> callables = commands.getoutput("nm -D /lib/libc.so.6 | egrep ' T '
> ").split("\n")
> callables = [c.split()[2] for c in callables]
>
> print callables
>
> On Dec 5, 2007 5:26 PM, Rafael Sachetto <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > > > with Python it is simple to call direct functions from c-librarys.
> > > > Is there a way to browse over alibraryi.e. '/lib/libc.so' with
> > > > python, to see all possible functions in alibrary?
>
> > > You could use the subprocess module to execute 'nm /lib/libc.so' and look
> > > at lines with type T.
>
> > To do this on a dynamiclibraryyou have to use nm -D /lib/libc.so
>
> > --
> > Rafael Sachetto Oliveira
>
> > Sir - Simple Image Resizer
> >http://rsachetto.googlepages.com
>
> --
> Rafael Sachetto Oliveira
>
> Sir - Simple Image Resizerhttp://rsachetto.googlepages.com- Zitierten Text 
> ausblenden -
>
> - Zitierten Text anzeigen -

works fine ..., thanks a lot georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Who is Jesus?

2007-12-07 Thread aassime abdellatif
Who is Jesus?

Without a doubt, you have often heard the claim that Jesus is God, the
second person in the "Holy trinity." However, the very Bible which is
used as a basis for knowledge about Jesus and as the basis for
doctrine within Christianity clearly belies this claim. We urge you to
consult your own Bible and verify that the following conclusions are
not drawn out of context:

1. God is All Knowing.but Jesus was not
When speaking of the day of judgment, Jesus clearly gave evidence of a
limitation on his knowledge when he said, "but of that day and hour
knoweth no man, no, not the angels which are in Heaven, neither the
son, but the Father." Mark 13:32, and Matt 24:36. But God knows all.
His knowledge is without any limitations. That Jesus, of his own
admission, did not know when the day of judgment would be, is clear
proof that Jesus is not all-knowing, and that Jesus is therefore not
God.

2. God is All Powerful.but Jesus was not
While Jesus performed many miracles, he himself admitted that the
power he had was not his own but was derived from God when he said,
"Verily, verily I say unto you, the Son can do nothing of himself, but
what he seeth the Father do..." St. John 5:19. Again he said, "I can
of mine own self do nothing: as I hear I judge: and my judgment is
just; because I seek not mine own will, but the will of the Father
which hath sent me." St. John 5:30. But God is not only all-powerful,
He is also the source of all power and authority. That Jesus, of his
own admission, could do nothing on his own is clear proof that Jesus
is not all-powerful, and that therefore Jesus is not God.

3. God does not have a God.but Jesus did have a God.
God is the ultimate judge and refuge for all, and He does not call
upon nor pray to any others. But Jesus acknowledged that there was one
whom he worshipped and to whom he prayed when he said, "l ascend unto
my Father and your Father, and to my God and your God." St. John
20:17. He is also reported to have cried out while on the cross, "My
God, my God why hast thou forsaken me?" Matt 27:46. If Jesus were God,
then couldn't this be read, "Myself, myself why hast thou forsaken
me?" Would that not be pure nonsense? When Jesus prayed the Lord's
prayer (Luke 11:2-4), was he praying to himself? When in the garden of
Gethsemane he prayed, "O my Father, if it be possible, let this cup
pass from me: Nevertheless not as I will but as thou wilt." Matt
26:36-39. Was Jesus praying to himself? That Jesus, of his own
admission and by his own actions, acknowledged, worshipped, and prayed
to another being as God is clear proof that Jesus himself is not God.

4. God is an invisible spirit.but Jesus was flesh and blood
While thousands saw Jesus and heard his voice, Jesus himself said that
this could not be done with God when he said. "No man hath seen God at
any time." St. John 1:18. '"Ye have neither heard His voice at any
time nor seen His shape." St. John 5:37. He also said in St. John
4:24. "God is a spirit and they that worship him must worship him in
spirit and in truth." That Jesus would say that no one had seen or
heard God at any time, while his followers both saw and heard him, is
clear proof that Jesus was not God.

5. No one is greater than God and no one can direct Him but Jesus
acknowledged someone greater than himself whose will was distinct from
his own.
Perhaps the clearest indication we have that Jesus and God are not
equal, and therefore not one and the same, come again from the mouth
of Jesus himself who said in St. John 14:28, "My Father is greater
than I." When someone referred to him as good master in Matt 19:17,
Jesus responded, "Why callest thou me good? There is none good but
one, that is God..." Furthermore, Jesus drew clear distinctions
between himself and God when he said, "I proceeded forth and came from
God, neither came I of myself but He sent me." St. John 8:42. Jesus
gave clear evidence of his subordination to God, rather than his
equality with God,when he said in Luke 22:42, "not my will but thine
be done" and in St. John 5:30, "I seek not mine own will but the will
of the Father which hath sent me." That Jesus would admit that he did
not come into the world on his own initiative but was directed to do
so, that he would acknowledge another being as greater than himself,
and that he would negate his own will in deference to affirming the
will of another, give clear proof that Jesus is not the Supreme One
and therefore Jesus is not God.

Conclusion
The Church recognizes the Bible as the primary source of knowledge
about God and Jesus. But since the Bible makes it clear that Jesus is
not the Supreme Being and the Supreme Being is not Jesus, upon what
basis have you come to believe otherwise?

My brother or sister, the belief that the Supreme Being is a Trinity
is false and completely inconsistent with the words of Jesus as
presented in the Bible. God is one, not three. He is a perfect unity.

If you are interested in the truth abou

Python 3.0a2 is out

2007-12-07 Thread Christian Heimes
A new alpha of Python 3000 was released a few minutes ago!

http://www.python.org/download/releases/3.0/

Have fun and don't forget to report bugs at http://bugs.python.org/

Christian



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-07 Thread Boris Borcic
Dirk Hagemann wrote:
> (3566839/24)/365 = 407   - YES I did this calculation too and was
> surprised. But if you try this out in MS Excel:
>  ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0)  (put
> 3566839 in field A1 and switch the format of the result-fieldby right-
> click on it to the
> date format "14.3.01 13:30")
> 
> and then replace 3566839 by, let's say, "2", Excel calculates the date
> 01.10.1901 2:00 AM.

Hum, how can it be that Excel changes from YY to  year display format ? 
What 
does it display in the first case with a  display format ?
-- 
http://mail.python.org/mailman/listinfo/python-list


changing fonts?

2007-12-07 Thread jyoung79
This is probably a silly question, but alas, I'll ask it anyway...

Is it possible with Python, to change the font of the text returned in the 
Terminal Window in OS X?  For example, lets say I'm running a Python program in 
Terminal, and it asks me "Please enter an English word to be changed to 
Greek:".  So I then enter "bread".  Is it possible for the next answer that 
Python returns in the Terminal Window to be displayed in the 'Symbols' font so 
that the Greek text is displayed correctly?  I have my doubts, but thought I'd 
ask.

Thanks!

Jay
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calculate an age

2007-12-07 Thread Pierre Quentel
On Dec 7, 7:09 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

> How many days in a year? 365.25 (J2000 epoch), 365.2422 [as I
> recall](B1900 epoch), 365.0 (non-leap year), 366 (leap year)? Gregorian
> or Julian calendar -- and depending upon one's country, the Gregorian
> reform may take place at different years.
>
> Simple months of (year/12) days, or calendrical mishmash (30 days
> hath September, April, June, and November...) again with leap year
> exceptions?
>

Hi,

I don't see where the ambiguity is. Isn't it obvious what we mean by
"I am X years, Y months and Z days" ?

Regards,
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >