[JOB] - Python Architect - Singapore

2011-06-06 Thread Rob
Our client, part of one of the largest Telcos in the world is
currently on the hunt for what they describe as a Python Senior
Developer/Team Lead/Systems Archtiect, for their Singapore office.

This particular part of the organisation has offices around the world
servicing world wide brand-name clients.

The key aspects to this role are


1. Role based in Singapore, therefore the candidate must have already
decided Singapore is for themas there is no relocation package. I
have recently put a more junior person across for another role with
the company and this candidate's wife is from Singapore and as they
have decided to already move back home, it suits them to go for this
role.


2. Salaries - This slightly junior candidate (who has done this
transition before) is currently on $90kAUD in Australia and is
looking to move to Singapore for $90k SGD ($68k AUD). You will not be
able to achive the same dollar for dollar (AUD) transitionBUT, the
taxes in Singapore are anywhere from 5-10% which means that
effectively you could potentially have more take-home pay than you
would in Australia. Therefore if you use similar transition as above,
that is what you could achieve. I am not an expert on the cost of
living in Singapore, therefore if this is a new transition for you,
you would need to do your own investigationsbut from what I have
heard the above calculation provides a similar lifestyle. THIS ROLE IS
OFFERING BETWEEN $110K - $120k SGD per annum

3. Process - My client is happy for telephone and Skype interviews AND
they can get you to work in the Australian office first to aclimatise
to the systems etc and to meet key people of the company.


This is a permanent opportunity, perfect for someone who is eager to
go to Singapore for a career change.


As a most senior member of the team, you will be required to be
competent in all things Python related, full SDLC experience across a
range of RDBMS. You will have the ability to lead a team, to mentor,
to present and ultimately to deliver on key internal and external
projects

If this role sounds perfect for you, please don't hesitate to submit
your CV to be considered immediately

Python, Python, Python, Python, Python

+61 2 9439 4643

Rob Stevens  rob.stev...@higherrecruitment.com.au

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


Not defined

2005-10-01 Thread Rob
When trying the basic tutorial for cgkit I always seem to get a not defined 
error as follows.

Pythonwin GUI

>>> from cgkit import *
>>> Sphere()
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'Sphere' is not defined
>>> b=Box(name="Cube", pos=(1.5,2,0))
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'Box' is not defined
>>>

I am useing  ver 2.4

A little help would be most appreciated.

Forgive me please if this is not the proper place for this ?  I am trying to 
keep an active brain :)

Regards Gramps



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


Re: Not defined

2005-10-01 Thread Rob
Thanks for the replies gives me something to chew on.

Regards Gramps 


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


Imaplib gmail move email from inbox to another folder then delete from inbox not working

2013-08-25 Thread rob
I am using imaplib to copy a message from inbox to another folder.  I then use 
/Deleted on the message.  When I use expunge it does not remove the message 
from the inbox.  I still have the 'Inbox' and 'newfolder' labels on the 
message.  I want to only have the 'newfolder' label on the message.
-- 
http://mail.python.org/mailman/listinfo/python-list


Imaplib & Gmail - cannot move from inbox to custom folder (message remains in both)

2013-08-26 Thread rob
I am using Imaplib and connecting to a Gmail account.  I am issuing commands to 
copy the email to a custom folder then issuing delete.  After expunge message 
still remains in inbox and customer folder.

# COPY EMAIL TO FOLDER
copyStatus = m.copy(emailid, 'CIRIMPORTED')
print 'id of message copied is: %s status: %s' % (emailid,copyStatus)
 
# SET THE MESSAGE TO HAVE '\Deleted' FLAG (EXPUNGE WILL COMPLETE DELETE 
PROCESS)
storeStatus = m.store(emailid,"+FLAGS", r'(\Deleted)')
print 'id of message stored is: %s status: %s %s' % 
(emailid,storeStatus[0],storeStatus[1])
#print '**'

#DELETES ANY EMAIL MARKED \Deleted
m.expunge()
m.close()
m.logout()

Does anyone have any imaplib code the works with Gmail to move from inbox to 
another folder?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Imaplib & Gmail - cannot move from inbox to custom folder (message remains in both)

2013-08-26 Thread rob
On Monday, August 26, 2013 5:56:09 PM UTC-6, MRAB wrote:
> On 27/08/2013 00:34, r...@attoenterprises.com wrote:
> 
> > I am using Imaplib and connecting to a Gmail account.  I am issuing 
> > commands to copy the email to a custom folder then issuing delete.  After 
> > expunge message still remains in inbox and customer folder.
> 
> >
> 
> >  # COPY EMAIL TO FOLDER
> 
> >  copyStatus = m.copy(emailid, 'CIRIMPORTED')
> 
> >  print 'id of message copied is: %s status: %s' % 
> > (emailid,copyStatus)
> 
> >
> 
> >  # SET THE MESSAGE TO HAVE '\Deleted' FLAG (EXPUNGE WILL COMPLETE 
> > DELETE PROCESS)
> 
> >  storeStatus = m.store(emailid,"+FLAGS", r'(\Deleted)')
> 
> >  print 'id of message stored is: %s status: %s %s' % 
> > (emailid,storeStatus[0],storeStatus[1])
> 
> >  #print '**'
> 
> >
> 
> >  #DELETES ANY EMAIL MARKED \Deleted
> 
> >  m.expunge()
> 
> >  m.close()
> 
> >  m.logout()
> 
> >
> 
> > Does anyone have any imaplib code the works with Gmail to move from inbox 
> > to another folder?
> 
> >
> 
> There's an example in docs which says:
> 
> 
> 
>  M.store(num, '+FLAGS', '\\Deleted')
> 
> 
> 
> You have:
> 
> 
> 
>  m.store(emailid,"+FLAGS", r'(\Deleted)')
> 
> 
> 
> Could it be that the flags should be r'\Deleted'?

I have tried it with the variations on the web of \\Deleted, r'\Deleted, and 
\Deleted.  The Delete works because I see in the status 'Deleted'.  However it 
does not remove from Inbox.  
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE won't run

2006-10-12 Thread Rob
I have Python 2.4.3 installed on Windows XP on both a real computer and a 
virtual machine under VMware. Just recently, IDLE stopped working. I would 
select IDLE from the start menu or right click on a .PY file and open it in 
IDLE, but nothing happens. I just uninstalled Python on the virtual machine 
and installed 2.5 in the hope that that would fix the problem, but it 
didn't. It, too, would do nothing when I tried to run IDLE. In both cases, 
the Python command line window will come up, but that's not what I want to 
use.

Does anyone know of a way to fix this problem? Is there a new Windows 
update that is now interfering with IDLE? Would Norton Antivirus be 
interfering with it somehow? (It's running in both environments.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE won't run

2006-10-12 Thread Rob
hg <[EMAIL PROTECTED]> banged out in news:[EMAIL PROTECTED]:

> 
> What kind of error do you see by calling idle from the command line
> (ex: 
>  "c:\\python.exe c:\\idle.py"
> 

When I ran it that way, I got a raft of warnings about a "problem 
retrieving theme element 'builtin-forground'" from the colour theme that I 
had set up, then IDLE actually came up. After deleting my colour theme, I 
tried running IDLE in the usual manner (via the shortcut or by opening a 
.PY file in it), and it worked.

(It's rather curious that, even after uninstalling version 2.4.3 
completely, my theme was preserved when I installed 2.5.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Serial port failure

2006-12-15 Thread Rob
Hi all,

I am fairly new to python, but not programming and embedded.  I am
having an issue which I believe is related to the hardware, triggered
by the software read I am doing in pySerial.  I am sending a short
message to a group of embedded boxes daisy chained via the serial port.
 When I send a 'global' message, all the connected units should reply
with their Id and Ack in this format '0 Ack'  To be certain that I
didn't miss a packet, and hence a unit, I do the procedure three times,
sending the message and waiting for a timeout before I run through the
next iteration.  Frequently I get through the first two iterations
without a problem, but the third hangs up and crashes, requiring me to
remove the Belkin USB to serial adapter, and then reconnect it.  Here
is the code:

import sys, os
import serial
import sret
import time

from serial.serialutil import SerialException

 GetAck Procedure

def GetAck(p):
response = ""

try:
response = p.readline()
except SerialException:
print ">>>>>Timed out<<<<<"
return -1
res = response.split()

#look for ack in the return message
reslen = len(response)
if reslen > 5:
if res[1] == 'Ack':
return res[0]
elif res[1] == 'Nak':
return 0x7F
else:
return -1


>>>>> Snip <<<<<<

 GetNumLanes Procedure

def GetNumLanes(Lanes):
print "Looking for connected units"
# give a turn command and wait for responses
msg = ".g t 0 336\n"

for i in range(3):
port = OpenPort()
time.sleep(3)
print port.isOpen()
print "Request #%d" % (i+1)
try:
port.writelines(msg)
except OSError:
print "Serial port failure.  Power cycle units"
port.close()
sys.exit(1)

done = False
# Run first connection check
#Loop through getting responses until we get a -1 from GetAck
while done == False:
# lane will either be -1 (timeout), 0x7F (Nak),
# or the lane number that responded with an Ack
lane = GetAck(port)
if lane >= '0':
if False == Lanes.has_key(lane):
Lanes[lane] = True
else:
done = True
port.close()
time.sleep(3)

# Report number of lanes found
NumLanes = len(Lanes)
if NumLanes == 1:
print "\n\nFound 1 unit connected"
else:
print "\n\nFound %d units connected" % NumLanes

return NumLanes


>>>>>> Snip <<<<<<

 Main Program Code Section


#open the serial port
# capture serial port errors from trying to open the port

port = OpenPort()

# If we got to here, the port exists.  Set the baud rate and timeout
values

# I need to determine how many lanes are on this chain
# First send a turn command

#Create a dictionary of lanes so I can check each lane's responses
Lanes = {}
#<><><><><><><><><><><><><><><><>
# Call the lane finder utility
NumLanes = GetNumLanes(Lanes)
#<><><><><><><><><><><><><><><><>

#if no lanes responded, exit from the utility
if 0 == NumLanes:
print "I can't find any units connected."
print "Check your connections and try again"
sys.exit(1)

# list the lanes we have in our dictionary
for n in Lanes:
print "Lane - %s" % n

Now, here is the error message that I get

[EMAIL PROTECTED]:~/py$ ./Thex.py
Looking for connected units
True
Request #1
True
Request #2
Serial port failure.  Power cycle units
[EMAIL PROTECTED]:~/py$ ./Thex.py
The serial port is unavailable.
Disconnect your USB to Serial adapter, Then
reconnect it and try again.
[EMAIL PROTECTED]:~/py$

Does anyone have any ideas?

Thanks,

rob < [EMAIL PROTECTED] >

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


Re: Serial port failure

2006-12-15 Thread Rob
Here is OpenPort


 OpenPort procedure

def OpenPort(name):
BRate = 19200
Tout  = 3

try:
# Initialize the port
p = serial.Serial(name)
# handle failures gracefully
except SerialException:
print "The serial port is unavailable."
print "Disconnect your USB to Serial adapter, Then"
print "reconnect it and try again."
sys.exit(1)

p.setBaudrate(19200)
p.setTimeout(3)  #set timeout to 1.5 seconds

# finish opening the port and assign a file handle
p.open()
return p



On Dec 15, 1:07 pm, hg <[EMAIL PROTECTED]> wrote:
> Rob wrote:
> > Hi all,
>
> > I am fairly new to python, but not programming and embedded.  I am
> > having an issue which I believe is related to the hardware, triggered
> > by the software read I am doing in pySerial.  I am sending a short
> > message to a group of embedded boxes daisy chained via the serial port.
> >  When I send a 'global' message, all the connected units should reply
> > with their Id and Ack in this format '0 Ack'  To be certain that I
> > didn't miss a packet, and hence a unit, I do the procedure three times,
> > sending the message and waiting for a timeout before I run through the
> > next iteration.  Frequently I get through the first two iterations
> > without a problem, but the third hangs up and crashes, requiring me to
> > remove the Belkin USB to serial adapter, and then reconnect it.  Here
> > is the code:
>
> > import sys, os
> > import serial
> > import sret
> > import time
>
> > from serial.serialutil import SerialException
> > 
> >  GetAck Procedure
> > 
> > def GetAck(p):
> > response = ""
>
> > try:
> > response = p.readline()
> > except SerialException:
> > print ">>>>>Timed out<<<<<"
> > return -1
> > res = response.split()
>
> > #look for ack in the return message
> > reslen = len(response)
> > if reslen > 5:
> > if res[1] == 'Ack':
> > return res[0]
> > elif res[1] == 'Nak':
> > return 0x7F
> > else:
> > return -1
>
> >>>>>> Snip <<<<<<
> > 
> >  GetNumLanes Procedure
> > 
> > def GetNumLanes(Lanes):
> > print "Looking for connected units"
> > # give a turn command and wait for responses
> > msg = ".g t 0 336\n"
>
> > for i in range(3):
> > port = OpenPort()
> > time.sleep(3)
> > print port.isOpen()
> > print "Request #%d" % (i+1)
> > try:
> > port.writelines(msg)
> > except OSError:
> > print "Serial port failure.  Power cycle units"
> > port.close()
> > sys.exit(1)
>
> > done = False
> > # Run first connection check
> > #Loop through getting responses until we get a -1 from GetAck
> > while done == False:
> > # lane will either be -1 (timeout), 0x7F (Nak),
> > # or the lane number that responded with an Ack
> > lane = GetAck(port)
> > if lane >= '0':
> > if False == Lanes.has_key(lane):
> > Lanes[lane] = True
> > else:
> > done = True
> > port.close()
> > time.sleep(3)
>
> > # Report number of lanes found
> > NumLanes = len(Lanes)
> > if NumLanes == 1:
> > print "\n\nFound 1 unit connected"
> > else:
> > print "\n\nFound %d units connected" % NumLanes
>
> > return NumLanes
>
> >>>>>>> Snip <<<<<<
> > 
> >  Main Program Code Section
> > 
>
> > #open the serial port
> > # capture serial port errors from trying to open the port
>
> > port = OpenPort()
>
> > # If we got to here, the port exists.  Set the baud rate and timeout
> > values
>
> > # I need to determine how many lanes are on this chain
> > # First send a turn command
>
> > #Create a 

Re: Serial port failure

2006-12-15 Thread Rob
Craig,

In the embedded firmware, the each box re-transmits after it finishes
reading the packet.  This is a very rudimentary system, and uses no
flow control.  The topology is that each embedded box has a master and
a slave port.  The master is used to receive data from the upstream
box, and send acks or naks back to the upstream box.  The slave is
connected to the master of the next downstream box.

Does that clear up the picture a little bit?

Rob

On Dec 15, 11:30 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Rob <[EMAIL PROTECTED]> wrote:
> >  I am fairly new to python, but not programming and embedded.  I am
> >  having an issue which I believe is related to the hardware, triggered
> >  by the software read I am doing in pySerial.  I am sending a short
> >  message to a group of embedded boxes daisy chained via the serial port.
> >   When I send a 'global' message, all the connected units should reply
> >  with their Id and Ack in this format '0 Ack'What is to stop all the 
> > embedded boxes talking at once?
>
> I suspect that the embedded boxes all taking at once is confusing the
> serial port driver.  Maybe it is creating a break condition that it
> doesn't deal with properly?  Or perhaps I've misunderstood the
> topology!
>
> What sort of flow control are you using?  Could it have got out of
> step with XON-XOFF?
>
> Assuming the driver is locking up then it looks like a serial port
> driver bug.  In my day job I do a lot of stuff with serial ports and
> I've found that drivers vary wildly in quality!
>
> My advice is to try a different serial port hardware.  I've found ones
> based on the PL2303 chip to be very reliable both under windows and
> linux.
>
> Eg this one :-
>
>  http://www.scan.co.uk/Products/ProductInfo.asp?WebProductID=98192
>
> Or one of these (which were based on PL2303 last time I bought one)
>
>  http://www.comtrol.com/products/catalog.asp?group=usbserialhubs
>
> I don't think anything you can do from python/user-space should be
> able to lock up the kernel mode serial driver.  If it does lock up it
> is a driver bug.
>
> Here you'll find a little program I wrote which, with the help of a
> loopback connector, you can check your serial port out
>
>  http://www.craig-wood.com/nick/pub/cambert.exe
>
> Run the program from a cmd prompt and it will tell you how to use it.
>
> I've broken a lot of serial port drivers with that program ;-)
>
> --
> Nick Craig-Wood <[EMAIL PROTECTED]> --http://www.craig-wood.com/nick

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


Re: Serial port failure

2006-12-15 Thread Rob
I have been modifying the code today, tracing through it and trying to
make it more robust and implement data hiding.  That way as someone
reads through my main they will see intuitively what I am doing.   For
that reason I went back and added a filename parameter to OpenPort.

The reason I am closing and opening the port is the same reason I
posted.  I thought that by opening and closing the port each time (I
don't do it in the 'real' code, I could determine whether the bug lay
with hardware or software, or in the USB to Serial adapter.

Rob

On Dec 15, 3:02 pm, hg <[EMAIL PROTECTED]> wrote:
> Rob wrote:
> > Here is OpenPort
>
> > 
> >  OpenPort procedure
> > 
> > def OpenPort(name):
> > BRate = 19200
> > Tout  = 3
>
> > try:
> > # Initialize the port
> > p = serial.Serial(name)
> > # handle failures gracefully
> > except SerialException:
> > print "The serial port is unavailable."
> > print "Disconnect your USB to Serial adapter, Then"
> > print "reconnect it and try again."
> > sys.exit(1)
>
> > p.setBaudrate(19200)
> > p.setTimeout(3)  #set timeout to 1.5 seconds
>
> > # finish opening the port and assign a file handle
> > p.open()
> > return p
>
> > On Dec 15, 1:07 pm, hg <[EMAIL PROTECTED]> wrote:
> >> Rob wrote:
> >> > Hi all,
>
> >> > I am fairly new to python, but not programming and embedded.  I am
> >> > having an issue which I believe is related to the hardware, triggered
> >> > by the software read I am doing in pySerial.  I am sending a short
> >> > message to a group of embedded boxes daisy chained via the serial port.
> >> >  When I send a 'global' message, all the connected units should reply
> >> > with their Id and Ack in this format '0 Ack'  To be certain that I
> >> > didn't miss a packet, and hence a unit, I do the procedure three times,
> >> > sending the message and waiting for a timeout before I run through the
> >> > next iteration.  Frequently I get through the first two iterations
> >> > without a problem, but the third hangs up and crashes, requiring me to
> >> > remove the Belkin USB to serial adapter, and then reconnect it.  Here
> >> > is the code:
>
> >> > import sys, os
> >> > import serial
> >> > import sret
> >> > import time
>
> >> > from serial.serialutil import SerialException
> >> > 
> >> >  GetAck Procedure
> >> > 
> >> > def GetAck(p):
> >> > response = ""
>
> >> > try:
> >> > response = p.readline()
> >> > except SerialException:
> >> > print ">>>>>Timed out<<<<<"
> >> > return -1
> >> > res = response.split()
>
> >> > #look for ack in the return message
> >> > reslen = len(response)
> >> > if reslen > 5:
> >> > if res[1] == 'Ack':
> >> > return res[0]
> >> > elif res[1] == 'Nak':
> >> > return 0x7F
> >> > else:
> >> > return -1
>
> >> >>>>>> Snip <<<<<<
> >> > 
> >> >  GetNumLanes Procedure
> >> > 
> >> > def GetNumLanes(Lanes):
> >> > print "Looking for connected units"
> >> > # give a turn command and wait for responses
> >> > msg = ".g t 0 336\n"
>
> >> > for i in range(3):
> >> > port = OpenPort()
> >> > time.sleep(3)
> >> > print port.isOpen()
> >> > print "Request #%d" % (i+1)
> >> > try:
> >> > port.writelines(msg)
> >> > except OSError:
> >> > print "Serial port failure.  Power cycle units"
> >> > port.close()
> >> > sys.exit(1)
>
> >> > done = False
> >> > # Run first connection check
> >> > #Lo

Re: Serial port failure

2006-12-15 Thread Rob
Leo,

I like your tuple idea.  I will implement it.  The ack and nak both
have the same format, namely: "Id Ack" or "Id Nak"

rob

On Dec 15, 4:34 pm, "Leo Kislov" <[EMAIL PROTECTED]> wrote:
> Rob wrote:
> > Hi all,
>
> > I am fairly new to python, but not programming and embedded.  I am
> > having an issue which I believe is related to the hardware, triggered
> > by the software read I am doing in pySerial.  I am sending a short
> > message to a group of embedded boxes daisy chained via the serial port.
> >  When I send a 'global' message, all the connected units should reply
> > with their Id and Ack in this format '0 Ack'  To be certain that I
> > didn't miss a packet, and hence a unit, I do the procedure three times,
> > sending the message and waiting for a timeout before I run through the
> > next iteration.  Frequently I get through the first two iterations
> > without a problem, but the third hangs up and crashes, requiring me to
> > remove the Belkin USB to serial adapter, and then reconnect it.  Here
> > is the code:
>
> > import sys, os
> > import serial
> > import sret
> > import time
>
> > from serial.serialutil import SerialException
> > 
> >  GetAck Procedure
> > 
> > def GetAck(p):
> > response = ""
>
> > try:
> > response = p.readline()
> > except SerialException:
> >print ">>>>>Timed out<<<<<"
> >return -1
> > res = response.split()
>
> > #look for ack in the return message
> > reslen = len(response)
> > if reslen > 5:
> > if res[1] == 'Ack':
> >return res[0]
> >elif res[1] == 'Nak':
> >return 0x7F
> >else:
> >return -1
>
> > >>>>> Snip <<<<<<
> > 
> >  GetNumLanes Procedure
> > 
> > def GetNumLanes(Lanes):
> >print "Looking for connected units"
> > # give a turn command and wait for responses
> >msg = ".g t 0 336\n"
>
> >for i in range(3):
> >port = OpenPort()
> >time.sleep(3)
> >print port.isOpen()
> >print "Request #%d" % (i+1)
> >try:
> >port.writelines(msg)
> >except OSError:
> >print "Serial port failure.  Power cycle units"
> >port.close()
> >sys.exit(1)
>
> > done = False
> > # Run first connection check
> >#Loop through getting responses until we get a -1 from GetAck
> > while done == False:
> ># lane will either be -1 (timeout), 0x7F (Nak),
> ># or the lane number that responded with an Ack
> >lane = GetAck(port)
> >if lane >= '0':Your GetAck returns either string or number and 
> > then you compare it
> with a string. If you compare string with a number python currently
> returns result you probably don't expect
>
> >>> -1 >= '0'
> False
> >>> 0x7f >= '0'False
>
> This is a wart and it will be fixed in python 3.0 (it will raise
> exception) I think you should rewrite GetAck to return a tuple (state,
> lane)
>
> def GetAck(p):
>response = ""
>
>try:
>response = p.readline()
>except SerialException:
>print ">>>>>Timed out<<<<<"
>return 'Timeout', 'NoID'
>res = response.split()
>
>#look for ack in the return message
>reslen = len(response)
>if reslen > 5:
>if res[1] == 'Ack':
>return 'Ack', res[0]
>elif res[1] == 'Nak':
>return 'Nak', Does Nak response contain lane id?
>else:
>return 'Unknown', 'NoID'
>
> And then instead of
>
> lane = GetAck(port)
> if lane >= '0':
>
> use
> 
> state, lane = GetAck(port)
> if state == 'Ack':
> 
>   -- Leo

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


Re: searching for IDE

2005-06-12 Thread Rob
Try ActiveState Komodo.  It costs $30 for a personal license, and is well 
worth it.  If you like visual studio you will like it.

Like many other people, I have looked far and wide for a Python IDE and this 
is what I've found.  The free solutions don't cut it, at least without 
spending many many hours of work, more than $30 worth.


R


"alexrait1" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I need an IDE for python that has the ability to show the filds of a
> class when I write "."
> Just the way it works in eclipse/JBuilder with java or visual studio
> with c++
> For now I treid eric3 and IDLE they don't do this...
> 


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


Calling a function with unknown arguments?

2007-03-07 Thread Rob
I can get a list of a function's arguments.
>>> def bob(a, b):
... return a+b
...
>>> bob.func_code.co_varnames
('a', 'b')

Let's say that I also have a dictionary of possible arguments for this
function.
>>> possible = {'a':10, 'b':5, 'c':-3}

How do I proceed to call bob(a=10, b=5) with this information?

Thanks!

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


Re: Calling a function with unknown arguments?

2007-03-07 Thread Rob
> You can do this with a list comprehension:
> bob(*[possible[k] for k in bob2.func_code.co_varnames])
>
> The LC creates a list of arg values in the same order as the var names
> for the function. Putting a * before the list when you call bob()
> turns that list into it's arguments.

Thanks Tom! This turns out to be exactly what I needed.

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


Re: Local python web server problem

2009-02-09 Thread Rob
> I run the cherrypy hello world! example and when I visit
> 127.0.0.1:8080
> on firefox, a nice "Hello World" appears. I am on ubuntu and my ip in
> local network is 192.168.100.18
> but when I visit 192.168.100.18, there is another page: "It Works!".
> What is "It Works!"? and when I type 192.168.100.18:8080 in another
> local pc, the page didn't load?

You need to have the server listen on 192.168.100.18 not 127.0.0.1. 
They are different.  127.0.0.1 is visible only locally. The
192.168.100.18 is visible both locally and from other hosts.

I don't use cherrypy so don't know how you set this up.  Are you using
apache to host cherrypy or does it have it's own web server? If your using
apache the IP address is selected with the Listen directive normally in
the /etc/apache2/ports.conf file.

> Thanks and sorry for my bad English.
Your english is good.

Rob

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


Re: global name 'sqrt' is not defined

2009-02-09 Thread Rob
> Any ideas?  If I do something like "import math" in the subfunction, 
> then the error changes to "global name 'math' is not defined".

Presumably ipython does an import so you need to import it yourself
something like:

from math import sqrt

at the top of your source file.  I don't know why math would not be
defined, it's built in -- probably a scoping logic problem in your code. 
Put the form/import statement at the top of your module file (as is
usually done), not inside a function or other block.

Rob

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


Re: How can I intentionally crash my lappy?

2010-12-20 Thread rob

On 12/20/2010 4:22 AM, Steven D'Aprano wrote:

On Mon, 20 Dec 2010 02:45:18 -0600, mechtheist wrote:


I am no programmer, but know the rudiments [the rudi'est of rudiments]
of working with Python.  I have a simple need,  to have a simple
script/app I can run that will crash my PC.  On my desktops, I can
always hit the reset, but that is not an option with my laptop.  Can
anyone tell me of an easy way to guarantee a program will instantly
kill/BSOD my windows7/64bit laptop?

Any help is much appreciated.

You realise that the operating system (yes, even Windows!) is designed to
*not* crash no matter what the application does?

(The OS may live up to that requirement imperfectly, but still, it tries.)


You'll probably find that task easier from C than from Python. But if I
were to attempt such a strange thing, I'd try to shut down some critical
processes used by the OS. I'm not much of a Windows person, but if you
call up the task manager (ctrl-alt-del) and inspect the process list,
then find one that causes the machine to crash if you shut it down, you
can probably do the same thing from a script.
Thank you, good approach ideas there.  Windows has gotten a lot better 
about crashing, but it is definitely still way the f 'imperfect'.  Now I 
just have to figure a way to make it imperfecter.

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


Re: How can I intentionally crash my lappy?

2010-12-20 Thread rob
Thanks, that is exactly what I was looking for.  Unfortunately, it is 
only for /non/-USB keyboards, I may be able to figure something out from 
there with hotkey or something.


On 12/20/2010 3:31 AM, Stefan Sonnenberg-Carstens wrote:

http://pcsupport.about.com/od/tipstricks/ht/makebsodxp.htm
Am Mo, 20.12.2010, 09:45 schrieb mechtheist:

I am no programmer, but know the rudiments [the rudi'est of rudiments]
of working with Python.  I have a simple need,  to have a simple
script/app I can run that will crash my PC.  On my desktops, I can
always hit the reset, but that is not an option with my laptop.  Can
anyone tell me of an easy way to guarantee a program will instantly
kill/BSOD my windows7/64bit laptop?

Any help is much appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


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


os x compile, install?

2010-04-27 Thread Rob
Hi,

Python on my system is behaving badly, so I want to create a new
install from source code.  I have OS X 10.6.2, I downloaded the source
code (Python-2.6.5.tar.bz2) and did the usual, ./configure, make, sudo
make install.  Build went fine.  But on install, why is it putting
things is my home directory?

[...]
running build_scripts
running install_lib
creating /Users/rob/Library/Python
creating /Users/rob/Library/Python/2.6
creating /Users/rob/Library/Python/2.6/site-packages
copying build/lib.macosx-10.4-x86_64-2.6/_AE.so -> /Users/rob/Library/
Python/2.6/site-packages
copying build/lib.macosx-10.4-x86_64-2.6/_AH.so -> /Users/rob/Library/
Python/2.6/site-packages
copying build/lib.macosx-10.4-x86_64-2.6/_App.so -> /Users/rob/Library/
Python/2.6/site-packages
[...]

Later, this causes imports that require those .so files to fail.  For
example...

RobsMac Python-2.6.5 $ python
Python 2.6.5 (r265:79063, Apr 28 2010, 13:40:18)
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import zlib
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named zlib

What is going on?

thanks,
Rob
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os x compile, install?

2010-04-28 Thread Rob
On Apr 28, 2:09 pm, Rob  wrote:
> Hi,
>
> Python on my system is behaving badly, so I want to create a new
> install from source code.  I have OS X 10.6.2, I downloaded the source
> code (Python-2.6.5.tar.bz2) and did the usual, ./configure, make, sudo
> make install.  Build went fine.  But on install, why is it putting
> things is my home directory?

Doh!  Nevermind...  I had created a ~/.pydistutils.cfg file a
couple weeks ago, for some stupid reason I can't remember.  I forgot
to delete that file.  It's contents were:

[install]
install_lib = ~/Library/Python/$py_version_short/site-packages
install_scripts = ~/bin

So it was overriding the normal setup.py behavior.

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


Back-end Python Developer Seeking Telecommute Work

2013-05-17 Thread Rob Sutton
I am seeking part/full time work as a back-end Python developer (telecommute or 
Utah only).  I have been maintaining a 
Debian/Python/Django/Apache/PostgreSQL/PHP/MySql web application for 3 years on 
my own.  I do all the development, database and system management myself. I can 
setup a complete system from scratch remotely or setup the hosting service.  I 
have experience with Virtualbox and ProxMox virtualization.  I have expereince 
in all areas of IT including telecom, programming, networking, hardware and 
software.  Worked with Retail stores, warehousing systems, accounting software, 
data interchange, hardware interfacing, etc.  

Regards,

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


Re: Conditional decoration

2012-06-18 Thread Rob Williscroft
Roy Smith wrote in news:jro9cj$b44$1...@panix2.panix.com in 
gmane.comp.python.general:

> Is there any way to conditionally apply a decorator to a function?
> For example, in django, I want to be able to control, via a run-time
> config flag, if a view gets decorated with @login_required().
> 
> @login_required()
> def my_view(request):
> pass

You need to create a decorator that calls either the original
function or the decorated funtion, depending on your condition, 
Something like (untested):

def conditional_login_required( f ):
  _login_required = login_required()(f)
  
  def decorated( request ):
if condition == "use-login":
  return _login_required( request )
else:
  return f( request )
  
  return decorated

@conditional_login_required
def my_view(request):
  pass

Replace (condition == "use-login") with whatever your "run-time 
control flag" is.

-- 
Rob.



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


Re: Sharing code between different projects?

2012-08-13 Thread Rob Day
I'd just create a module - called shared_utils.py or similar - and import
that in both projects. It might be a bit messy if there's no 'unifying
theme' to the module - but surely it'd be a lot less messy than your
TempDirectory class, and anyone else who knows Python will understand
'import shared_utils' much more easily.

I realise you might not want to say, but if you could give some idea what
sort of projects these are, and what sorts of code you're trying to share,
it might make things a bit clearer.

I'm not really sure what your concerns about 'versioning and how to link
different pieces together' are - what d you think could go wrong here?

On 13 August 2012 17:53, andrea crotti  wrote:

> I am in the situation where I am working on different projects that
> might potentially share a lot of code.
>
> I started to work on project A, then switched completely to project B
> and in the transiction I copied over a lot of code with the
> corresponding tests, and I started to modify it.
>
> Now it's time to work again on project A, but I don't want to copy
> things over again.
>
> I would like to design a simple and nice way to share between projects,
> where the things I want to share are simple but useful things as for
> example:
>
> class TempDirectory:
> """Create a temporary directory and cd to it on enter, cd back to
> the original position and remove it on exit
> """
> def __init__(self):
> self.oldcwd = getcwd()
> self.temp_dir = mkdtemp()
>
> def __enter__(self):
> logger.debug("create and move to temp directory %s" %
> self.temp_dir)
> return self.temp_dir
>
> def __exit__(self, type, value, traceback):
> # I first have to move out
> chdir(self.oldcwd)
> logger.debug("removing the temporary directory and go back to
> the original position %s" % self.temp_dir)
> rmtree(self.temp_dir)
>
>
> The problem is that there are functions/classes from many domains, so it
> would not make much sense to create a real project, and the only name I
> could give might be "utils or utilities"..
>
> In plus the moment the code is shared I must take care of versioning and
> how to link different pieces together (we use perforce by the way).
>
> If then someone else except me will want to use these functions then of
> course I'll have to be extra careful, designing really good API's and so
> on, so I'm wondering where I should set the trade-off between ability to
> share and burden to maintain..
>
> Anyone has suggestions/real world experiences about this?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A difficulty with lists

2012-08-15 Thread Rob Day
> The list nlist inside of function xx is not the same as the variable u
> outside of the function:  nlist and u refer to two separate list objects.
>  When you modify nlist, you are not modifying u.
> 


Well - that's not quite true. Before calling the function, u is [1, 2, 3,
4] - but after calling the function,  u is [1, 2, 3, 4, 999]. This is a
result of using 'nlist += [999]' - the same thing doesn't happen if you use
'nlist = nlist+[999]' instead.

I'm not completely aware of what's going on behind the scenes here, but I
think the problem is that 'nlist' is actually a reference to a list object
- it points to the same place as u. When you assign to it within the
function, then it becomes separate from u - which is why nlist =
nlist+[999] and nlist = nlist[:-1] don't modify u - but if you modify nlist
in place before doing that, such as by using +=, then it's still pointing
to u, and so u gets modified as well.

So, for example:

>>> def blank_list(nlist):
... nlist[:] = [] # modifies the list in-place
...
>>> u
[1, 2, 3, 4]
>>> blank_list(u)
>>> u
[] # u has been changed by our change to nlist!

But if we change it so that it assigns to nlist rather than modifying it:

>>> def dont_blank_list(nlist):
... nlist = [] # creates a new list object rather than modifying the
current one
...
>>> u = [1, 2, 3, 4]
>>> u
[1, 2, 3, 4]
>>> dont_blank_list(u)
>>> u
[1, 2, 3, 4] # u is completely unaffected!
-- 
Robert K. Day
robert@merton.oxon.org




-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call perl script from html using python

2012-08-16 Thread Rob Day
On 16 August 2012 08:23, Pervez Mulla  wrote:

>
>
> In HTml when user submit POST method, it calling Python code Instead
> of this I wanna call perl script for sign up ..
>
>
Can you not just change the action= attribute in your  HTML attribute
to point to your Perl CGI script?

-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [CGI] Why is HTML not rendered?

2012-08-17 Thread Rob Day
On 17 August 2012 14:27, Gilles  wrote:

>
> print "Content-Type: text/plain;charset=utf-8"
> print
>


Here's the problem - you're telling the browser to display in plain text.
Try 'text/html' instead.

-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with simple print statement!

2012-08-24 Thread Rob Day
On Fri, 2012-08-24 at 12:43 -0700, Willem Krayenhoff wrote:
> Any idea why print isn't working here?  

You're using Python 3.2, but trying Python 2.7 syntax -
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function 
should explain the problem adequately.

(Incidentally - you can copy from the Windows console by right-clicking
and selecting "Mark". It's a little easier than taking a screenshot!)

Rob




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


Re: Unittest - testing for filenames and filesize

2012-08-26 Thread Rob Day
On Sun, 2012-08-26 at 10:36 -0700, Tigerstyle wrote:
> self.assertEqual(statinfo.st_size, filesize)
> 
> I'm still getting AssertionError and the error says: 100 !=b'
> 
> 

filesize is the character 'b' repeated one million times (the contents
of the file, in other words). statinfo.st_size is the number of bytes in
the file, i.e. 1,000,000. So when your assertEqual code checks if those
two values are equal, what do you think happens?

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


log4py confusion

2012-12-13 Thread Rob Richardson
Greetings!



I have finally gotten fed up with all of the Python scripts used in my company 
that have every parameter hard-coded.  I am rewriting one of them to read all 
of its parameters from an XML file.  Then, we can change the XML file to 
control which database it is using, whether its running in debug mode or not, 
and various other things.  One of the parameters I want the XML file to contain 
is the name of the script's log file.



I have a class named Settings that will contain all the parameters read from 
the XML file.  But if something goes wrong, I want to log it.  So, I want to 
have a Logger object for it to use.  I use a hard-coded file name for that.  
Then, after reading the XML file, I want to create a second Logger object that 
will be used by the rest of the script.



When I try to use the second Logger object, I get an exception complaining that 
'unicode' object has no attribute 'write'.



The script and the exception messages are below.  Can anyone see what I'm doing 
wrong?



Can anyone point me to a web site documenting the log4py module?



Thank you very much.



RobR





import os

import sys

import string

import win32api

import win32event

import win32com

import win32com.client

import win32net

import pythoncom

import time

import log4py

import xml.dom.minidom as minidom

import argparse



#Set to 1 to run loop once for debugging, set to 0 for operation

#Debug = 1



class DataElement:

value = None



def __init__(self, element = None):

if element != None:

self.GetData(element)



def GetData(self, element):

nodes = element.childNodes

for node in nodes:

if node.nodeType == node.TEXT_NODE:

self.value = node.data



def GetDataFromRoot(self, rootElement, targetName, defaultValue):

elements = rootElement.getElementsByTagName(targetName)

if elements:

dataElement = DataElement(elements[0])

if (dataElement):

self.value = dataElement.value

else:

self.value = defaultValue

else:

self.Value = defaultValue



def __nonzero__(self):

return self.value != None



class Settings:

logFile = "TaskToCrane_somethingnew.log"



def __init__(self):

print "I don't know what XML file to use yet."



def __init__(self, fileName, tempLogger):

tempLogger.info( "Settings will come from " + fileName)

settingsDoc = minidom.parse(fileName)

rootElement = settingsDoc.documentElement

# print "Root element name: " + rootElement.tagName



programControlElement = 
rootElement.getElementsByTagName("ProgramControl")[0]

logFileElement = DataElement()

logFileElement.GetDataFromRoot(programControlElement, "LogFile", 
self.logFile)

if logFileElement:

self.logFile = logFileElement.value

else:

tempLogger.error("Failed to get log file name.")



def Log(self, logger):

logger.info("Log file: " + str(self.logFile))



if __name__ == "__main__" :



TempLogger = log4py.Logger().get_instance("main")

TempLogger.set_rotation(log4py.ROTATE_DAILY, 5)



TempLogger.set_loglevel(log4py.LOGLEVEL_DEBUG)

TempLogger.set_formatstring("%T - %L  %M")

TempLogger.set_target("TaskToCrane_logging_base.log")



parser = argparse.ArgumentParser()

parser.add_argument("settings_file")

args = parser.parse_args()



programSettings = Settings(args.settings_file, TempLogger)

TempLogger.info("Setting actual log target to " + programSettings.logFile)



Logger = log4py.Logger().get_instance("main")

Logger.set_rotation(log4py.ROTATE_DAILY, 5)



Logger.set_loglevel(log4py.LOGLEVEL_DEBUG)

Logger.set_formatstring("%T - %L  %M")

Logger.set_target(programSettings.logFile)



programSettings.Log(TempLogger)



Traceback (most recent call last):

  File 
"D:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 
322, in RunScript

debugger.run(codeObject, __main__.__dict__, start_stepping=0)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", 
line 60, in run

_GetCurrentDebugger().run(cmd, globals,locals, start_stepping)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", 
line 655, in run

exec cmd in globals, locals

  File "D:\Program Files\WinCaps\Scripts\TaskToCrane_logging.py", line 91, in 


programSettings.Log(TempLogger)

  File "D:\Program Files\WinCaps\Scripts\TaskToCrane_logging.py", line 66, in 
Log

logger.info("Log file: " + str(self.logFile))

  File "log4py.py", line 359, in info

self.__Logger_showmessage(message, MSG_INFO)

 File "log4py.py", line 534, in __Logger_showmessage

target.write("%s\n" % line)

AttributeError: 'unicode' object h
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: log4py confusion

2012-12-13 Thread Rob Richardson
The last line,

programSettings.Log(TempLogger),
should have been

programSettings.Log(Logger)

I get the same error no matter which logger I use, though, which I don't 
understand.

Also, I'm using Python 2.7.

Thanks again for your help!

RobR
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
Rob Richardson
Sent: Thursday, December 13, 2012 1:58 PM
To: python-list@python.org
Subject: log4py confusion


Greetings!



I have finally gotten fed up with all of the Python scripts used in my company 
that have every parameter hard-coded.  I am rewriting one of them to read all 
of its parameters from an XML file.  Then, we can change the XML file to 
control which database it is using, whether its running in debug mode or not, 
and various other things.  One of the parameters I want the XML file to contain 
is the name of the script's log file.



I have a class named Settings that will contain all the parameters read from 
the XML file.  But if something goes wrong, I want to log it.  So, I want to 
have a Logger object for it to use.  I use a hard-coded file name for that.  
Then, after reading the XML file, I want to create a second Logger object that 
will be used by the rest of the script.



When I try to use the second Logger object, I get an exception complaining that 
'unicode' object has no attribute 'write'.



The script and the exception messages are below.  Can anyone see what I'm doing 
wrong?



Can anyone point me to a web site documenting the log4py module?



Thank you very much.



RobR





import os

import sys

import string

import win32api

import win32event

import win32com

import win32com.client

import win32net

import pythoncom

import time

import log4py

import xml.dom.minidom as minidom

import argparse



#Set to 1 to run loop once for debugging, set to 0 for operation

#Debug = 1



class DataElement:

value = None



def __init__(self, element = None):

if element != None:

self.GetData(element)



def GetData(self, element):

nodes = element.childNodes

for node in nodes:

if node.nodeType == node.TEXT_NODE:

self.value = node.data



def GetDataFromRoot(self, rootElement, targetName, defaultValue):

elements = rootElement.getElementsByTagName(targetName)

if elements:

dataElement = DataElement(elements[0])

if (dataElement):

self.value = dataElement.value

else:

self.value = defaultValue

else:

self.Value = defaultValue



def __nonzero__(self):

return self.value != None



class Settings:

logFile = "TaskToCrane_somethingnew.log"



def __init__(self):

print "I don't know what XML file to use yet."



def __init__(self, fileName, tempLogger):

tempLogger.info( "Settings will come from " + fileName)

settingsDoc = minidom.parse(fileName)

rootElement = settingsDoc.documentElement

# print "Root element name: " + rootElement.tagName



programControlElement = 
rootElement.getElementsByTagName("ProgramControl")[0]

logFileElement = DataElement()

logFileElement.GetDataFromRoot(programControlElement, "LogFile", 
self.logFile)

if logFileElement:

self.logFile = logFileElement.value

else:

tempLogger.error("Failed to get log file name.")



def Log(self, logger):

logger.info("Log file: " + str(self.logFile))



if __name__ == "__main__" :



TempLogger = log4py.Logger().get_instance("main")

TempLogger.set_rotation(log4py.ROTATE_DAILY, 5)



TempLogger.set_loglevel(log4py.LOGLEVEL_DEBUG)

TempLogger.set_formatstring("%T - %L  %M")

TempLogger.set_target("TaskToCrane_logging_base.log")



parser = argparse.ArgumentParser()

parser.add_argument("settings_file")

args = parser.parse_args()



programSettings = Settings(args.settings_file, TempLogger)

TempLogger.info("Setting actual log target to " + programSettings.logFile)



Logger = log4py.Logger().get_instance("main")

Logger.set_rotation(log4py.ROTATE_DAILY, 5)



Logger.set_loglevel(log4py.LOGLEVEL_DEBUG)

Logger.set_formatstring("%T - %L  %M")

Logger.set_target(programSettings.logFile)



programSettings.Log(TempLogger)



Traceback (most recent call last):

  File 
"D:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 
322, in RunScript

debugger.run(codeObject, __main__.__dict__, start_stepping=0)

  File "D:\Python27\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", 
line 60, in run

_GetCurrentDebugger().run(cmd, 

RE: log4py confusion

2012-12-13 Thread Rob Richardson
Thanks for the suggestion, but I don't think that can be it.  At least, it's 
not it on the line you specified.  That form, with the target name given as a 
hard-coded string, is in use in every Python script our company uses.  So, 
set_target() is expecting a file instead of a file name, there must be some 
implicit conversion going on that creates a file object of the given name 
before setting the log target to the file.  

On the other hand, it would certainly explain the " 'Unicode' object does not 
have attribute 'write' " message.  A file object would be expected to have an 
attribute named 'write', while a string object wouldn't.  

The error happens after the target is changed to a file name contained in a 
variable.  Why doesn't that implicit conversion work with a string contained in 
a variable?  Do I have to do an explicit cast of some kind?  Or, probably 
better, I should probably look up how to create a file object so I can pass it 
in to the set_target() function.

That's one reason I asked for documentation on log4py: so I could see what 
methods are available, and what arguments they actually expect.

Thanks again!

RobR


-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
MRAB
Sent: Thursday, December 13, 2012 2:35 PM
To: python-list@python.org
Subject: Re: log4py confusion

On 2012-12-13 18:58, Rob Richardson wrote:
> Greetings!
>
> I have finally gotten fed up with all of the Python scripts used in my 
> company that have every parameter hard-coded.  I am rewriting one of 
> them to read all of its parameters from an XML file.  Then, we can 
> change the XML file to control which database it is using, whether its 
> running in debug mode or not, and various other things.  One of the 
> parameters I want the XML file to contain is the name of the script's 
> log file.
>
> I have a class named Settings that will contain all the parameters 
> read from the XML file.  But if something goes wrong, I want to log 
> it.  So, I want to have a Logger object for it to use.  I use a 
> hard-coded file name for that.  Then, after reading the XML file, I 
> want to create a second Logger object that will be used by the rest of the 
> script.
>
> When I try to use the second Logger object, I get an exception 
> complaining that 'unicode' object has no attribute 'write'.
>
> The script and the exception messages are below.  Can anyone see what 
> I'm doing wrong?
>
[snip]
I think the problem might be that it's expecting a file object, not a file 
name/path as you have here:

 TempLogger.set_target("TaskToCrane_logging_base.log")

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


RE: log4py confusion

2012-12-13 Thread Rob Richardson
I think I have the answer.  All I need to do is use the str() function to 
convert the object stored in logFile from a Unicode string to a normal string:

Logger.set_target(str(programSettings.logFile))

RobR

-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
Rob Richardson
Sent: Thursday, December 13, 2012 2:52 PM
To: python-list@python.org
Subject: RE: log4py confusion

Thanks for the suggestion, but I don't think that can be it.  At least, it's 
not it on the line you specified.  That form, with the target name given as a 
hard-coded string, is in use in every Python script our company uses.  So, 
set_target() is expecting a file instead of a file name, there must be some 
implicit conversion going on that creates a file object of the given name 
before setting the log target to the file.  

On the other hand, it would certainly explain the " 'Unicode' object does not 
have attribute 'write' " message.  A file object would be expected to have an 
attribute named 'write', while a string object wouldn't.  

The error happens after the target is changed to a file name contained in a 
variable.  Why doesn't that implicit conversion work with a string contained in 
a variable?  Do I have to do an explicit cast of some kind?  Or, probably 
better, I should probably look up how to create a file object so I can pass it 
in to the set_target() function.

That's one reason I asked for documentation on log4py: so I could see what 
methods are available, and what arguments they actually expect.

Thanks again!

RobR


-Original Message-
From: Python-list 
[mailto:python-list-bounces+rob.richardson=rad-con@python.org] On Behalf Of 
MRAB
Sent: Thursday, December 13, 2012 2:35 PM
To: python-list@python.org
Subject: Re: log4py confusion

On 2012-12-13 18:58, Rob Richardson wrote:
> Greetings!
>
> I have finally gotten fed up with all of the Python scripts used in my 
> company that have every parameter hard-coded.  I am rewriting one of 
> them to read all of its parameters from an XML file.  Then, we can 
> change the XML file to control which database it is using, whether its 
> running in debug mode or not, and various other things.  One of the 
> parameters I want the XML file to contain is the name of the script's 
> log file.
>
> I have a class named Settings that will contain all the parameters 
> read from the XML file.  But if something goes wrong, I want to log 
> it.  So, I want to have a Logger object for it to use.  I use a 
> hard-coded file name for that.  Then, after reading the XML file, I 
> want to create a second Logger object that will be used by the rest of the 
> script.
>
> When I try to use the second Logger object, I get an exception 
> complaining that 'unicode' object has no attribute 'write'.
>
> The script and the exception messages are below.  Can anyone see what 
> I'm doing wrong?
>
[snip]
I think the problem might be that it's expecting a file object, not a file 
name/path as you have here:

 TempLogger.set_target("TaskToCrane_logging_base.log")

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


Re: sqlite3 puzzle

2013-01-15 Thread Rob Day
On 15 January 2013 07:09, llanitedave  wrote:

> So I put the following test code in my initialization method:
>
> # open database file
> self.geologger_db = sqlite3.connect('geologger.mgc')
> self.db_cursor = self.geologger_db.cursor()
> self.foreign_key_status = self.db_cursor.execute("PRAGMA foreign_keys = 
> ON")
> self.foreign_key_status = self.foreign_key_status.fetchone()
>
> print self.foreign_key_status
>
> I ran this several times while I was arranging the downstream queries, and 
> each time it returned '(1,)', which means foreign keys is enabled.
>
> But I was using a variable named 'cmd1' as a placeholder until I changed the 
> name to
> the more descriptive 'self.foreign_key_status'.  Since I made the name 
> change, however,
> the code only returns 'None'.  Reverting to the previous variable name has no 
> effect.

Hmm - your code doesn't quite match up with the docs at
http://docs.python.org/2/library/sqlite3.html. That seems to suggest
that you should call fetchone() on the cursor, not on the result of
execute().

Does the following work?

# open database file
self.geologger_db = sqlite3.connect('geologger.mgc')
self.db_cursor = self.geologger_db.cursor()
self.db_cursor.execute("PRAGMA foreign_keys = ON")
print self.db_cursor.fetchone()


--
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 puzzle

2013-01-15 Thread Rob Day
On 15 January 2013 15:51, llanitedave  wrote:
> Thanks for the suggestion, Rob, but that didn't make any difference.  I've 
> never had an issue with putting the execute object into a variable and 
> calling "fetch" on that variable.
>
> I can accept reality if it turns out that foreign keys simply isn't enabled 
> on the Python distribution of sqlite, although I don't know why that should 
> be the case.  I'm just curious as to why it worked at first and then stopped 
> working.

Well - you might be able to accept that, but I'm not sure I can! If it
was working before, it must be compiled in, and so it must be possible
to make it work again.

http://www.sqlite.org/foreignkeys.html#fk_enable seems to suggest that
"PRAGMA foreign_keys = ON" never returns anything, and it's only
"PRAGMA foreign_keys" which returns 0, 1 or None (when unsupported).
With that in mind, does the following code work?

# open database file

self.geologger_db = sqlite3.connect('geologger.mgc')
self.db_cursor = self.geologger_db.cursor()
self.db_cursor.execute("PRAGMA foreign_keys = ON")
self.db_cursor.execute("PRAGMA foreign_keys")
print self.db_cursor.fetchone()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 puzzle

2013-01-15 Thread Rob Day
Glad I could help!


Using a local source control system like git, bzr or hg is really
useful in situations like these - it's far, far easier to debug issues
of the form "I made changes and now it's broken" when you can do `git
diff yesterday's-version today's-version` and see exactly what the
changes were.


On 15 January 2013 20:29, llanitedave  wrote:
> On Tuesday, January 15, 2013 9:13:13 AM UTC-8, Rob Day wrote:
>> On 15 January 2013 15:51, llanitedave  wrote:
>>
>> > Thanks for the suggestion, Rob, but that didn't make any difference.  I've 
>> > never had an issue with putting the execute object into a variable and 
>> > calling "fetch" on that variable.
>>
>> >
>>
>> > I can accept reality if it turns out that foreign keys simply isn't 
>> > enabled on the Python distribution of sqlite, although I don't know why 
>> > that should be the case.  I'm just curious as to why it worked at first 
>> > and then stopped working.
>>
>>
>>
>> Well - you might be able to accept that, but I'm not sure I can! If it
>>
>> was working before, it must be compiled in, and so it must be possible
>>
>> to make it work again.
>>
>>
>>
>> http://www.sqlite.org/foreignkeys.html#fk_enable seems to suggest that
>>
>> "PRAGMA foreign_keys = ON" never returns anything, and it's only
>>
>> "PRAGMA foreign_keys" which returns 0, 1 or None (when unsupported).
>>
>> With that in mind, does the following code work?
>>
>>
>>
>> # open database file
>>
>>
>>
>> self.geologger_db = sqlite3.connect('geologger.mgc')
>>
>> self.db_cursor = self.geologger_db.cursor()
>>
>> self.db_cursor.execute("PRAGMA foreign_keys = ON")
>>
>> self.db_cursor.execute("PRAGMA foreign_keys")
>>
>> print self.db_cursor.fetchone()
>
> "http://www.sqlite.org/foreignkeys.html#fk_enable seems to suggest that 
> "PRAGMA foreign_keys = ON" never returns anything, and it's only "PRAGMA 
> foreign_keys" which returns 0, 1 or None (when unsupported)."
>
> That was it, exactly, Rob.  I don't know where I got the idea that I was 
> getting  a '1' from the 'ON' command, although I was sure that I'd seen it.  
> But once I just called "foreign_key" it returned just fine.
>
> Ummm...  Obviously I was up fiddling around too late.  Yeah, that's it.
>
>
> Thanks!  It's solved now.
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending a broadcast message using raw sockets

2013-01-21 Thread Rob Williscroft
Peter Steele wrote in
news:f37ccb35-8439-42cd-a063-962249b44...@googlegroups.com in
comp.lang.python: 

> I want to write a program in Python that sends a broadcast message
> using raw sockets. The system where this program will run has no IP or
> default route defined, hence the reason I need to use a broadcast
> message. 
> 
> I've done some searches and found some bits and pieces about using raw
> sockets in Python, but I haven't been able to find an example that
> explains how to construct a broadcast message using raw sockets. 
> 
> Any pointers would be appreciated.

This is part of my Wake-On-Lan script:

def WOL_by_mac( mac, ip = '', port = 9 ):
  import struct, socket

  a = mac.replace( ':', '-' ).split( '-' )
  addr = struct.pack( 'B'*6, *[ int(_, 16) for _ in a ] )
  msg = b'\xff' * 6 + addr * 16

  s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
  s.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 )
  s.sendto( msg, ( ip, port ) )
  s.close()


The mac address is 6 pairs of hex digits seperated by '-' or ':'.

http://en.wikipedia.org/wiki/Wake-on-LAN



Rob.

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


Re: Sending a broadcast message using raw sockets

2013-01-22 Thread Rob Williscroft
Peter Steele wrote in
news:0c2b3482-df46-4324-8bf9-2c45d3f6b...@googlegroups.com in
comp.lang.python: 

> On Monday, January 21, 2013 1:10:06 AM UTC-8, Rob Williscroft wrote:
>> Peter Steele wrote in
>> 
>> news:f37ccb35-8439-42cd-a063-962249b44...@googlegroups.com in
>> 
>> comp.lang.python: 
>> 
>> > I want to write a program in Python that sends a broadcast message

[snip]

>> This is part of my Wake-On-Lan script:
>> 
>> def WOL_by_mac( mac, ip = '', port = 9 ):
 
[snip]
 
> Thanks for the code sample. Does this code work if the box has no IP
> or default route assigned? I'm away from the office at the moment so I
> can't test this. 

No idea, but the sockets system must be up and running before the 
card (interface) has an IP (otherwise how would it ever get assigned) 
and I presume DHCP works in a similar manner.
 
However the "route assignemt" is irrelevent, broadcast messages never 
get routed.

Rob
-- 

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


Re: Sending a broadcast message using raw sockets

2013-01-22 Thread Rob Williscroft
Peter Steele wrote in
news:96947c45-f16b-4e97-b055-edc1241ee...@googlegroups.com in
comp.lang.python: 

> I just tried running you code, and the "sendto" call fails with
> "Network is unreachable". That's what I expected, based on other tests
> I've done. That's why I was asking about how to do raw sockets, since
> tools like dhclient use raw sockets to do what they do. It can clearly
> be duplicated in Python, I just need to find some code samples on how
> to construct a raw packet. 
> 

Try 
s = socket.socket( socket.AF_INET, socket.SOCK_RAW )

I tried this on windows and it needed admin privaleges to
run.

Rob.
-- 

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


Re: Dict comp help

2013-01-24 Thread Rob Day
On 24 January 2013 21:11, Oscar Benjamin  wrote:
 l = [{'a': 'xx', 'b': 'yy', 'c': 'zz'}, {'a': 'dd', 'b': 'ee', 'c': 'ff'}]
 dict(d.values()[:2] for d in l)
> {'xx': 'zz', 'dd': 'ff'}

Python doesn't guarantee any ordering of items in a dictionary; {'a':
'xx', 'b': 'yy', 'c': 'zz'}.values()[:2] may not return ['xx', 'zz']
in different Python implementations or future versions (though it
seems to work consistently in CPython 2.7). See
http://docs.python.org/2/library/stdtypes.html#dict.items.

--
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WLAN tester

2013-01-28 Thread Rob Day
On 28 January 2013 17:07, Wanderer  wrote:
> Yes. I noticed this variability. I've been using the Totusoft 
> Lan_Speedtest.exe to test some modules. I've tested through the wifi to our 
> intranet and saw variations I believe do to network traffic. I also tried 
> peer to peer and the write time actual got worse. I don't know if it has do 
> to with the firewall or the hard drive speed or just Windows giving this 
> process low priority. I also saw drop outs. So figuring out the metric for 
> pass/fail will be interesting. I'll check into setting an ftp for this test.

Why involve a protocol at all? I'd just create a socket
(http://docs.python.org/3.3/library/socket.html) and measure how long,
on average, it took to write a given number of arbitrary bytes (e.g.
"This is a string" repeated a million times) to it and then read a
given number of bytes back. That would be a relatively consistent
metric, whereas if you try using FTP you'll run into issues, as
already noted, where disk read/write speed and details of your FTP
server implementation like compression or multiple network connections
affect the result significantly.

--
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyrudp

2013-01-30 Thread Rob Day
Have you seen http://pyraknet.slowchop.com/? It appears to do a similar thing.

On 30 January 2013 17:02, Jorge Alberto Diaz Orozco
 wrote:
> I´ve tried it but it´s not reliable. Datagrams can arive disorganised or just 
> not arive.
> Some programmers said I most use TCP, but I need to use UDP.
> that´s why I need pyrudp, but I can not find it.
>
> On Jan 30, 2013, at 8:12 AM, Jorge Alberto Diaz Orozco
>
> What about the native socket call to SOCK_DGRAM?
>
> Here is a simple example to read messages of a udp socket.
>
> import socket
> UDP_IP = "127.0.0.1"
> UDP_PORT = 5005
>
> sock = socket.socket(socket.AF_INET, # Internet
> socket.SOCK_DGRAM) # UDP
> sock.bind((UDP_IP, UDP_PORT))
>
> while True:
> data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
> print "received message:", data
> --
> http://mail.python.org/mailman/listinfo/python-list



-- 
Robert K. Day
robert@merton.oxon.org
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: The devolution of English language and slothful c.l.p behaviors exposed!

2012-01-24 Thread Rob Richardson
"In America, they haven't spoken it for years!" -- Professor Henry Higgins, "My 
Fair Lady"

-Original Message-
On 24/01/2012 05:57, Rick Johnson wrote:

I would wish that pedantic citizens of the British colony in America stopped 
calling whatever misinterpreted waffle they produce, English.

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


PythonWin debugger holds onto global logging objects too long

2012-01-24 Thread Rob Richardson
I use PythonWin to debug the Python scripts we write.  Our scripts often use 
the log2py logging package.  When running the scripts inside the debugger, we 
seem to get one logging object for every time we run the script.  The result is 
that after running the script five times, the log file contains five copies of 
every message.  The only way I know to clean this up and get only a single copy 
of each message is to close PythonWin and restart it.

What do I have to do in my scripts to clean up the logging objects so that I 
never get more than one copy of each message in my log files?

Thank you very much!

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


Re: Cannot connect to IMAP server in Python 3.2

2012-04-04 Thread Rob Williscroft
Steven D'Aprano wrote in news:4f7d2475$0$3$c3e8...@news.astraweb.com in 
gmane.comp.python.general:

> I can connect to an IMAP server using Python 2.6:
> 
> steve@runes:~$ python2.6 
> Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) 

 server = imaplib.IMAP4_SSL('x')
 
> But when I try with Python 3.2, it just sits there until it times out:

 server = imaplib.IMAP4('x', imaplib.IMAP4_SSL_PORT)
 
> What am I doing wrong?
> 

Not using IMAP4_SSL, above you are using IMAP4 (non SSL) but with the 
SSL port.

http://docs.python.org/py3k//library/imaplib.html#imaplib.IMAP4_SSL

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


Re: ordering with duck typing in 3.1

2012-04-07 Thread Rob Williscroft
andrew cooke wrote in
news:33019705.1873.1333801405463.JavaMail.geo-discussion-forums@ynmm9 in
gmane.comp.python.general: 

> 
> hi,
> 
> please, what am i doing wrong here?  the docs say
> http://docs.python.org/release/3.1.3/library/stdtypes.html#comparisons
> "in general, __lt__() and __eq__() are sufficient, if you want the
> conventional meanings of the comparison operators" but i am seeing 
> 
>>   assert 2 < three
> E   TypeError: unorderable types: int() < IntVar()
> 
> with this test:
> 
> 
> class IntVar(object):
> 

> def __lt__(self, other):
> return self.value < other
> 
 
> so what am i missing?
> 

The part of the docs you are relying on uses the wording "in general",
IOW, it is not saying that defining __eq__ and __lt__ will always be 
sufficient.

In this case the expression "2 < three" is calling int.__lt__, which
doesn't know how to comapre to an instance of your class so returns 
NotImplemented.

At this point if you had defined a __gt__ method the interpreter would then 
try and call that having first switched the arguments around.  But you 
didn't so a TypeError is raised.

I'm afraid I couldn't find anywhere in the docs where that behaviour is 
described, I suspect I only know it from lurking on usenet for a number of 
years.

The best description that I could find of the behaviour you are seeing is 
at:

http://docs.python.org/py3k/reference/expressions.html#not-in

There is a paragraph that contains:

"... the == and != operators always consider objects of different types to 
be unequal, while the <, >, >= and <= operators raise a TypeError when 
comparing objects of different types that do not implement these operators 
for the given pair of types. ..."

Perhapse the docs could be reworded to note that, to define a full set of 
comparisons between *different* types, you need to define a full set of 
special methods.

Some links I found along the way:

http://docs.python.org/release/3.1.3/library/constants.html?
highlight=__lt__#NotImplemented

http://code.activestate.com/recipes/576685/
http://docs.python.org/py3k/library/functools.html#functools.total_ordering

Rob.


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


RE: How to stop the program as soon as one of the condition is met

2012-04-16 Thread Rob Richardson
Please show us your code.

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


How do I find out what file an import is using?

2012-05-09 Thread Rob Richardson
I am trying to work with a Python script someone else wrote.  The script 
includes the line
from Level3Utils import *

I need to look at the functions that are included in that import.  In an effort 
to identify exactly which file is being used, I renamed the Level3Utils.py and 
Level3Utils.pyc files in the same folder as the script I'm working on.  The 
import command in PythonWin executed without error.  I looked for a file named 
Level3Utils.py in my Python tree (d:/Python25, in my case).  None were there.  
I then commented out the import line and stepped through the code.  It ran 
without error!  The class that should have come from Level3Utils executed 
successfully without being imported!

How do I find out where the class definition actually is?

(There is no PYTHONPATH environmental variable defined on my machine.)

Thanks very much!

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


Re: None versus MISSING sentinel -- request for design feedback

2011-07-15 Thread Rob Williscroft
Steven D'Aprano wrote in news:4e1fd009$0$29986$c3e8da3
$54964...@news.astraweb.com in gmane.comp.python.general:

> I'm designing an API for some lightweight calculator-like statistics
> functions, such as mean, standard deviation, etc., and I want to support
> missing values. Missing values should be just ignored. E.g.:
> 
> mean([1, 2, MISSING, 3]) => 6/3 = 2 rather than 6/4 or raising an error.

If you can't make your mind up then maybe you shouldn't:

MISSING = MissingObject()
def mean( sequence, missing = MISSING ):
  ...

Rob.

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


Re: os.path.isdir do not work for Foder named '2011-07-03'

2011-07-18 Thread Rob Williscroft
Nulpum wrote in news:0bf400a3-735c-487a-8d74-
feb3b56be...@g5g2000prn.googlegroups.com in gmane.comp.python.general:

> I want to make sure that folder exists.
> '2011-07-03' is really exists. but 'os.path.isdir' say false
> Does anyone know why?
> 
>>>> os.path.isdir("C:\Users\Á¶Ã¢ÁØ\Desktop\logs")
> True
>>>> os.path.isdir("C:\Users\Á¶Ã¢ÁØ\Desktop\logs\2011-07-03")
> False

Maybe it isn't a directory, but a file, what does os.path.exists() return.

Also could it be a "Shortcut" in which case 2011-07-03.lnk will exist.

Also have you left "Hide extensions for known file types" switched on,
in which case it may really be "2011-07-03.zip" for example, a file 
not a directory even though Windows explorer shows it as a directory.

-- 
Rob.

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


Re: Returning a value from exec or a better solution

2011-08-29 Thread Rob Williscroft
Jack Trades wrote in
news:CAG5udOg=GtFGPmTB=1ojnvnrpdyucxdokn1wjqmomv9gx0+...@mail.gmail.com
in gmane.comp.python.general: 

> ... I wanted to allow the user to manually return the
> function from the string, like this:
> 
> a = exec("""
> def double(x):
>   return x * 2
> double
> """)
> 
> However it seems that exec does not return a value as it produces a
> SyntaxError whenever I try to assign it.

def test():
  src = (
  "def double(x):"
  "  return x * 2"
)
  globals  = {}
  exec( src, globals )
  return globals[ "double" ]
  
print( test() )

The a bove works on 2.7 (I tested it) on earlier versions you may need 
to use:

exec src in globals 

Rob.

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


Re: Button Label change on EVT_BUTTON in wxpython!!!

2011-08-29 Thread Rob Williscroft
Ven wrote in news:aa1212bb-35e5-4bf9-b8ad-7a3c083749c2
@x2g2000yql.googlegroups.com in gmane.comp.python.general:

> So, here is what I did/want:
> 
> self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
> self.Bind(wx.EVT_BUTTON, self.OnRun,id=ID_RUN_BUTTON)
> 
> def OnRun(self,evt):
>  self.run_button.SetLabel('Installing..')
>  #call a function that does the installation task
>  installation_task()
>  #After task completion, set the button label back to "Install"
>  self.run_button.SetLabel('Install')
> 
> When I try doing this, it doesn't set the label to "Installing" while
> the task is being performed. Any suggestions how do I achieve this?
> 

http://wiki.wxpython.org/CallAfter

Using this your OnRun will become somthing like:

def OnRun( self, evt ):
  def after():
installation_task()
self.run_button.SetLabel('Install')
  self.run_button.SetLabel('Installing..')
  wx.Callafter( after )

However if installation_task takes a long time you will need to use
threads, something like (untested):

def OnRun( self, evt ):
  def after():
self.run_button.SetLabel('Install')
  def task():
installation_task()
wx.Callafter( after )

  self.run_button.SetLabel('Installing..')

  import threading
  threading.Thread( target = task ).start()

Rob.

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w...@mail.gmail.com
in gmane.comp.python.general: 

>> def test():
>>  src = (
>>   "def double(x):"
>>  "  return x * 2"
>> )
>>  globals  = {}
>>  exec( src, globals )
>>  return globals[ "double" ]
>>
>> print( test() )
>>
> 
> I looked into doing it that way but it still requires that the user
> use a specific name for the function they are defining.  The docs on
> exec say that an implementation may populate globals or locals with
> whatever they want so that also rules out doing a simple "for item in
> globals", as there may be more than just the one function in there
> (though I suppose I may be able to work around that).
> 
> 

Why not just get the name from the user, or use a regular expression
to extract the first (or last, maybe) definition from the source string.

Rob.

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Jack Trades wrote in news:CAG5udOiOAge3uHrGSDTZ412GAg+CC-
6u8igoyj0lnf3hnwu...@mail.gmail.com in gmane.comp.python.general:

>> >>> class CapturingDict(dict):
>> ... def __setitem__(self, key, val):
>> ... self.key, self.val = key, val
>> ... dict.__setitem__(self, key, val)
>> ...
>> >>> c = CapturingDict()
>> >>> exec("def myfunction(x): return 1", c)
>> >>> c.key
>> 'myfunction'
>> >>> c.val
>> 
>>
>> HTH,
>>
>> --
>> Arnaud
>>
> 
> That's brilliant and works flawlessly.  Thank you very much!

If an impementation (as you say up thread) can populate globals 
or locals with whatever they want, then how do you know that last 
item added was the function definition the user supplied ?

Rob.

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Ethan Furman wrote in news:4e5d29c8.8010...@stoneleaf.us in 
gmane.comp.python.general:

> Jack Trades wrote:
>> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft wrote:
>>> If an impementation (as you say up thread) can populate globals
>>> or locals with whatever they want, then how do you know that last
>>> item added was the function definition the user supplied ?
> 
> Because the implementation will add things before the exec is processed. 

How do you know this ?, it isn't what the docs say.

http://docs.python.org/reference/simple_stmts.html#the-exec-statement

Rob.

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


Re: Returning a value from exec or a better solution

2011-08-30 Thread Rob Williscroft
Arnaud Delobelle wrote in 
news:CAJ6cK1YVi3NQgdZOUdhAESf133pUkdazM1PkSP=p6xfayvo...@mail.gmail.com in 
gmane.comp.python.general:

> On 30 August 2011 13:31, Jack Trades  wrote:
>>
>>
>> On Tue, Aug 30, 2011 at 2:37 AM, Rob Williscroft  wrote:
>>
>>>
>>> > That's brilliant and works flawlessly. ¶ÿThank you very much!
>>>
>>> If an impementation (as you say up thread) can populate globals
>>> or locals with whatever they want, then how do you know that last
>>> item added was the function definition the user supplied ?

> That's not an issue. The last statement that is executed will be the
> "def" statement.

You don't know that, an implementation may for example set __bultins__ 
to None, prior to returning, its not an unreasonable thing to do and
the docs don't say they can't.

Rob.

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


Re: Addition problems

2011-04-01 Thread Rob Williscroft
vm wrote in news:in4m1u$hsc$1...@news2.carnet.hr in
gmane.comp.python.general: 

> def fun1(params_used_below_except_lk_and_lk2):
> lk = 0.0
> lk2 = 0.0
> for raw_data, hist, freq in raw_data_hist_list:
> lk2 = lk2 + fun2(some_constants_and_params_from_this_scope)
> q = fun2(same_args_as_before)
> lk = lk + q
> print lk, lk2
> 
> For some set of input parameters, This function with specific input 
> prints out the same constant twice (as expected):
> 
> 15377.7424582 15377.7424582 (twice the same value)
> 
> If I comment out lines q = fun2 and lk = lk + q, fun1, with the
> same parameters, prints:
> 
> 0.0 3.3469936856
> 
> First value is expected, but I cannot understand how come the second 
> value is different in these two cases!

Clearly the value returned by fun2 (get_beta_func_fit_quality_hist_lk)
is different the second time you call it.

So it either depends on and modifies a global or a value referenced or 
contained in one of the arguments.

Rob.

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


Noob Question

2011-04-19 Thread Rob McGillivray
Hi All,

I'm new to Python, and trying to get python 3.2 installed on Centos 5.6. When I 
run 'make test', I receive several errors. The readme states that you can 
generally ignore messages about skipped tests, but as you can see below, some 
of the tests failed and a number were 'unexpected skips', so I'm not sure if I 
can go ahead with the install or need to perform further troubleshooting.

The output of 'make test' is shown below:

313 tests OK.
5 tests failed:
test_argparse test_distutils test_httpservers test_import
test_zipfile
31 tests skipped:
test_bz2 test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp
test_codecmaps_kr test_codecmaps_tw test_curses test_dbm_gnu
test_dbm_ndbm test_gdb test_gzip test_kqueue test_ossaudiodev
test_readline test_smtpnet test_socketserver test_sqlite test_ssl
test_startfile test_tcl test_timeout test_tk test_ttk_guionly
test_ttk_textonly test_urllib2net test_urllibnet test_winreg
test_winsound test_xmlrpc_net test_zipfile64 test_zlib
11 skips unexpected on linux2:
test_bz2 test_dbm_gnu test_dbm_ndbm test_gzip test_readline
test_ssl test_tcl test_tk test_ttk_guionly test_ttk_textonly
test_zlib
sys:1: ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' 
mode='a' encoding='UTF-8'>
make: *** [test] Error 1

Any help would be appreciated. Apologies if this post is to the wrong group. If 
so, please advise the appropriate group.

Thanks in advance,

Rob

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


RE: 3.2 test failures on Centos 5.6 (was Re: Noob Question)

2011-04-19 Thread Rob McGillivray
Hi Terry,

Much appreciate the pointers! :-)

I am trying to install from an RPM downloaded from python.org. I'm pretty new 
to Linux etc (very pleased to be finally getting into the wide world of OSS), 
so I'm double-challenged on a number of fronts right now.

I will run the failed tests in verbose mode as you recommended and then re-post 
my findings.

Again, appreciate the friendly welcome. :-)

Regards,

Rob


-Original Message-
From: python-list-bounces+rob=mymcgillivray@python.org 
[mailto:python-list-bounces+rob=mymcgillivray@python.org] On Behalf Of 
Terry Reedy
Sent: Tuesday, April 19, 2011 12:59 PM
To: python-list@python.org
Subject: 3.2 test failures on Centos 5.6 (was Re: Noob Question)

On 4/19/2011 10:55 AM, Rob McGillivray wrote:

> I'm new to Python, and trying to get python 3.2 installed on Centos 
> 5.6. When I run 'make test', I receive several errors.

Welcome to Python.

Newbie lesson 1: write an informative subject line that will catch the 
attention of people who can answer. (I just happened to open this because it is 
a slow day so far ;-).) Example:
   3.2 test failures on Centos 5.6
If you do not get any better answer than I can provide, I suggest reposting 
with that subject (my changed line will not be visible to some who have threads 
collapsed).

Lesson 2: provide all relevant info needed to answer. You did pretty good, 
except: What are you trying to install? A public binary built by someone else 
for Centos? Or one *you* compiled? If the latter, did you use the official 3.2 
source from the site or the latest 3.2.x source from the hg repository? (If 
either, I suggest trying the other.)

 > The readme
> states that you can generally ignore messages about skipped tests, but 
> as you can see below, some of the tests failed and a number were 
> 'unexpected skips', so I'm not sure if I can go ahead with the install 
> or need to perform further troubleshooting.

I have never built Python or used it on *nix, but I will give some informed 
guesses ;-).

> The output of 'make test' is shown below:
>
> 5 tests failed: test_argparse test_distutils test_httpservers 
> test_import test_zipfile

You need to run each of these in verbose mode to see who severe the failure is. 
Test_import would be of most concern to me.

 > 11 skips
> unexpected on linux2: test_bz2 test_dbm_gnu test_dbm_ndbm test_gzip 
> test_readline test_ssl test_tcl test_tk test_ttk_guionly 
> test_ttk_textonly test_zlib

These look like things with 3rd party dependencies. tcl/tk/ttk tests depend on 
finding tcl/tk installed. If you do not want to use the modules, no problem. If 
you do,

 > sys:1: ResourceWarning: unclosed
> file<_io.TextIOWrapper name='/dev/null' mode='a' encoding='UTF-8'>
> make: *** [test] Error 1

This is a bug either in some test or in the Python shutdown procedure, at least 
after running the tests. There were other things like this fixed near the end 
of 3.2 development and it may be fixed now.

> Any help would be appreciated. Apologies if this post is to the wrong 
> group. If so, please advise the appropriate group.

Right place to start. If there are Centos specific issues, you might want to 
look for a Centos list.

--
Terry Jan Reedy

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

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


Python 3.2 on CentOS 5.6 & compatibility concerns

2011-04-21 Thread Rob McGillivray
Hi All,
 
Does anyone know if it is 'safe' to install Python 3.2 on CentOS? By 'safe' I 
mean not breaking the existing base Python 2.4.x installation upon which 
various CentOS/RHEL services (like yum) depend. Will the 'make install' install 
3.2 in parallel with the existing 2.x installation, or break it? I'm new to 
Python and OSS, but the little I've read indicates that this could be a major 
risk.
 
My goal is to setup a dev platform (currently CentOS/Wing IDE/Python 3.2) and 
learn Python 3.x (as apparently this is the future of the language), but at the 
same time I'm looking to use CentOS as the server platform for deployment, and 
so want to understand what's involved in managing Python installations/upgrades 
on this platform. 
 
Thanks in advance,
 
Rob-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 dict question

2011-05-06 Thread Rob Wolfe
dmitrey  writes:

> hi all,
> suppose I have Python dict myDict and I know it's not empty.
> I have to get any (key, value) pair from the dict (no matter which
> one) and perform some operation.
> In Python 2 I used mere
> key, val = myDict.items()[0]
> but in Python 3 myDict.items() return iterator.
> Of course, I could use
> for key, val in myDict.items():
>do_something
>break
> but maybe there is any better way?

key, val = next(iter(myDict.items()))

http://docs.python.org/py3k/library/stdtypes.html#dictionary-view-objects

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


Re: How do I check all variables returned buy the functions exists

2017-09-15 Thread Rob Gaddi

On 09/15/2017 08:43 AM, Ganesh Pal wrote:

I have a function that return's x  variables  How do I check if all the the
values returned  are not None/False/0/''

Here is the same program to demonstrate this , but I  felt this can be
better  any suggestions ?


# vi file.py
import random
import string


def return_x_values():
 " returns x strings for further processing"
 value1 =  random.choice(string.ascii_letters)
 value2 = random.choice(string.ascii_letters)
 value3 = random.choice(string.ascii_letters)
 return (value1, value2, value3)


#unpack them

value1, value2 , value3 = return_x_values()


# check if its not none

# I think this can be better
if value1 and value2 and value3 :
print "continue with the program"

else:
   print "Exting the program"


# python file.py
continue with the program

I  am a Linux user with Python 2.7

Regards,
Ganesh



Don't unpack them yet, you still want them to be aggregated.

vals = return_x_values()
if all(vals):
v1, v2, v3 = vals
print "all values true"
else:
print "at least one false value"

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Boolean Expressions

2017-09-26 Thread Rob Gaddi

On 09/26/2017 03:23 PM, Cai Gengyang wrote:


I'm trying to understand the logic behind AND. I looked up Python logic tables

False and False gives False
False and True gives False
True and False gives False
True and True gives True.

So does that mean that the way 'and' works in Python is that both terms must be 
True (1) for the entire expression to be True ? Why is it defined that way, 
weird ? I was always under the impression that 'and' means that when you have 
both terms the same, ie either True and True or False and False , then it gives 
True



No, that would actually be an xnor (not xor) operation, a fairly rare 
usage case.  Python doesn't even provide an operator for that, the 
closest thing would be (bool(x) == bool(y)).


"And" means "and".  This is true AND that is true.

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Real Programmers Write Docs

2017-09-27 Thread Rob Gaddi
Anyone have any good references on using Sphinx to generate a mix of 
autogenerated API docs and hand-written "Yeah, but this is what you DO 
with it" docs?  Free is good but I'm happy to drop money on books if 
they're worthwhile.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Real Programmers Write Docs

2017-09-28 Thread Rob Gaddi

On 09/27/2017 04:15 PM, Ned Batchelder wrote:

On 9/27/17 6:55 PM, Rob Gaddi wrote:
Anyone have any good references on using Sphinx to generate a mix of 
autogenerated API docs and hand-written "Yeah, but this is what you DO 
with it" docs?  Free is good but I'm happy to drop money on books if 
they're worthwhile.




I can offer you an example: the coverage.py docs are in Sphinx, and use 
both auto-generated and hand-written pages: 
https://github.com/nedbat/coveragepy/tree/master/doc   I'm not sure what 
information you are looking for, maybe this will help?


--Ned.


Helps quite a bit, thanks Ned.  Basically I'm looking for a good example 
on structuring this sort of thing to keep it from spiraling out of 
control.  Looks like the big trick is to rely on hand-written structure 
around autoclass calls rather than letting automodule generate big walls 
of text.  PySerial was my other example, and has gone much the same route.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Line terminators in Python?

2017-09-29 Thread Rob Gaddi

On 09/29/2017 10:54 AM, Stefan Ram wrote:

   In some languages, printing »'\n'«, the Unicode code point 10,
   will have the effect of printing a line terminator, which might
   mean that the output device actually receives »\r\n«.

   The line terminator ostensibly depends on the operating
   system, but actually it depends on the output system. E.g.,
   under one operating system the console might accept another
   set of line separators than an editor. (Under Windows,
   »wordpad« accepts »\n«, while »notepad« requires »\r\n«.)

   What is the recommended way to terminate a line written with
   Python? Is it »\n« or something else? For example, in Java,
   in some cases, one should terminate the line with the value
   of »java.lang.System.lineSeparator()« which might or might
   not be equal to the value of »"\n"«.

   Does it possibly depend on the entity being written to, which
   might be

   - the Python console,
   - the IDLE console,
   - the operating system console or
   - a text file?



As everyone else has said; for general purpose (any of your cases) use 
you should always just use '\n' and it automagically works.  The only 
time I've ever needed to explicitly worry about '\r' is communicating 
over sockets or serial ports to devices.  And in those cases you need to 
stuff them with bytes rather than str anyhow, so you're already down in 
the gory bits.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a function of ipaddress to get the subnet only from input like 192.168.1.129/25

2017-10-17 Thread Rob Gaddi

On 10/17/2017 09:59 AM, Daniel Flick wrote:

I am very new to Python and have been struggling to find some info on 
processing IP addresses.

get_network returns 192.168.1.128/25 but I need 192.168.1.128 only.  I can do 
this with netaddr but I am working with Mako templates and ipaddress is a built 
in module so there are less dependencies.

Any ideas?



You mean, other than .split('/')?

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: I used list, def. why li += [100,200] , and li = li + [100,200] is different

2017-10-23 Thread Rob Gaddi

On 10/23/2017 09:29 AM, 임현준 wrote:

I am a Korean student, and I am a beginner in English and Python.;(

I can't understand about this def

If I want to print

[1,2,3,4,5]
[1,2,3,4,5,100,200]

I will make code like this, and I can understand code.


def modify(li):
  li += [100,200]

list = [1,2,3,4,5]
print(list)
modify(list)
print(list)


BUT, when I make code like this.

I will make code like this, and I can understand code.


def modify(li):
  li = li + [100,200]

list = [1,2,3,4,5]
print(list)
modify(list)
print(list)



python print

[1,2,3,4,5]
[1,2,3,4,5]

why 'li+= [100,200]'and 'li = li + [100,200]' 's print is different
please help me



Lists are mutable, they can be changed.  Your call to += is equivalent 
to a call to li.extend([100, 200]), which changes the single existing 
object pointed to by the "li" reference.  The second time, however, you 
take the existing value that "li" refers to [1,2,3,4,5], create a new 
object that is ([1,2,3,4,5] + [100,200]), and reassign the local 
reference "li" to point to that new object.  Then your function ends, 
"li" goes out of scope, nothing points to that newly created object and 
it gets lost.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: h5py.File() gives error message

2017-10-24 Thread Rob Gaddi

On 10/24/2017 10:58 AM, C W wrote:

Dear list,

The following Python code gives an error message

# Python code starts here:
import numpy as np
import h5py
train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")

# Python code ends

The error message:

train_dataset = h5py.File('train_catvnoncat.h5', "r")
Traceback (most recent call last):
   File "", line 1, in 
   File "/Users/M/anaconda/lib/python3.6/site-packages/h5py/_hl/files.py",
line 269, in __init__
 fid = make_fid(name, mode, userblock_size, fapl, swmr=swmr)
   File "/Users/M/anaconda/lib/python3.6/site-packages/h5py/_hl/files.py",
line 99, in make_fid
 fid = h5f.open(name, flags, fapl=fapl)
   File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
   File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
   File "h5py/h5f.pyx", line 78, in h5py.h5f.open
OSError: Unable to open file (unable to open file: name =
'train_catvnoncat.h5', errno = 2, error message = 'No such file or
directory', flags = 0, o_flags = 0)

My directory is correct, and the dataset folder with file is there.

Why error message? Is it h5py.File() or is it my file? Everything seems
pretty simple, what's going on?

Thank you!



Be 100% sure your directory is correct.  Try it again with an absolute 
path to the file.  Windows makes it far too easy for the working 
directory of a program to be other than what you think it is.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Easiest way to access C module in Python

2017-11-07 Thread Rob Gaddi

On 11/06/2017 05:59 PM, Grant Edwards wrote:

On 2017-11-06, John Pote  wrote:


I have successfully used Python to perform unit and integration tests in
the past and I'd like to do the same for some C modules I'm working with
at work. There seem to be a number of ways of doing this but being busy
at work and home I looking for the approach with the least learning curve.


When I want to test C modules (usually destined for an embedded
system) using a Python framework, I use ctypes.

https://docs.python.org/3/library/ctypes.html



I'll second ctypes.  It's pretty straightforward and I've made it do 
some very heavy lifting over the years.  Cython is definitely more work. 
 SWIG makes sense if you've got a huge number of interfaces you're trying
to map and need to automate the process, but if you've got south of 20 
I'd just do it natively with ctypes.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-18 Thread Rob Gaddi

On 12/18/2017 08:45 AM, Larry Martell wrote:

On Mon, Dec 18, 2017 at 11:33 AM, Marko Rauhamaa  wrote:

However, one great way to stand out is a portfolio of GitHub projects.
Several people have gotten an offer largely based on those (after they
aced the technical interviews). For example, we just hired someone who
had written a game in sed. That doesn't make him an "interesting
person," nor do we look for game or sed developers. But that silly
exercise deeply resonated with our team. We expect to have great synergy
with him.


I have been excluded from even getting an interview because I did not
have a portfolio of GitHub projects. I think that is a bad filter. I
work 60-70 hours a week for pay, and I have a family and personal
interests.



When I'm hiring I don't necessarily need a candidate to have an 
extensive open-source portfolio, but I need to see some kind of 
portfolio, just as a bar of "This is what I consider my good work to 
be."  The idea that someone is going to have years of experience, but 
not a single page of code that they can let me look over always strikes 
me as odd.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python Learning

2017-12-18 Thread Rob Gaddi

On 12/18/2017 01:52 PM, Gene Heskett wrote:

On Monday 18 December 2017 16:05:10 Rob Gaddi wrote:


On 12/18/2017 08:45 AM, Larry Martell wrote:

On Mon, Dec 18, 2017 at 11:33 AM, Marko Rauhamaa 

wrote:

However, one great way to stand out is a portfolio of GitHub
projects. Several people have gotten an offer largely based on
those (after they aced the technical interviews). For example, we
just hired someone who had written a game in sed. That doesn't make
him an "interesting person," nor do we look for game or sed
developers. But that silly exercise deeply resonated with our team.
We expect to have great synergy with him.


I have been excluded from even getting an interview because I did
not have a portfolio of GitHub projects. I think that is a bad
filter. I work 60-70 hours a week for pay, and I have a family and
personal interests.


When I'm hiring I don't necessarily need a candidate to have an
extensive open-source portfolio, but I need to see some kind of
portfolio, just as a bar of "This is what I consider my good work to
be."  The idea that someone is going to have years of experience, but
not a single page of code that they can let me look over always
strikes me as odd.


I've known Larry for years via another list. He has worked on a lot of
stuff in the financial arena, wrapped in non-disclosure clauses that
prevent him from even saying what color he dots the i's with, so he gets
work as much by word of mouth as other more conventional paths.

To not hire him because he doesn't have a big portfolio could be a
mistake, Rob. Its up to you.

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



Cheers, Gene Heskett



Not a big portfolio, anything.  Shell scripts that you're using to 
simplify your home login.  The garage door monitor you rigged up from an 
Arduino.  The Python script I wrote to fill a USB stick with a randomly 
chosen selection of MP3s.


I as well don't have a huge portfolio of GitHub projects that I spend my 
life maintaining, but I refuse to believe any of us get away with not 
writing any code outside out professional lives.  Personally, I'd argue 
I can get a better read of a programmer from the 120 line toy they 
tossed off one day to solve an immediate need than I can from the 50 
kLOC proprietary project they share with two other developers and are 
NDAed to the hilt on.


And as for Larry in particular, he's posted a portfolio's worth of code 
to this mailing list just in trying to help folks through their issues. 
For an actual interview I'd want it cleaned up to what he'd consider to 
be acceptable documentation standards for a project, but "demonstrate 
competence" is a well-cleared bar.  I just don't have any work at the 
moment that would justify bringing that big a cannon to bear.


So I stick to my point.  If you have literally nothing that you can show 
me at an interview, I'm dubious.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: property decorator?

2017-12-20 Thread Rob Gaddi

On 12/20/2017 03:56 PM, Irv Kalb wrote:

I am trying  to work through the concept of the @property decorator with 
respect to object oriented programming.

I believe that I understand how the @property and @.setter work - 
and that they are used to turn what looks like direct access to instance variables 
into method calls in an object.It seems like these two decorators are essentially 
fancy substitutes for traditional getter and setter methods.  But, I'm having a hard 
time understanding why these names were chosen.


> [snip]


My questions about this are really historical.  From my reading, it looks like using an 
@property decorator is a reference to an older approach using a built in 
"property" function.  But here goes:

1) Why were these decorator names chosen?  These two names @property and @.setter 
don't seem to be very clear to me.  At a minimum, they don't match.  Wouldn't decorator names 
like @.getter and @.setter have been better - more explicit?

2)  Alternatively, if the getter was going to use the @property decorator, then it would 
seem complimentary  to have the decorator name for the associated setter function to have 
the word "property" in its also, something like @propertySetter.

3)  If I create a method with the @property decorator, is there anything else that is implied about 
the name of the method other than you can now refer to the . - which 
calls the appropriate method?  My guess/understanding is that in my example above, "salary" 
is considered the property name, which is how you would refer to it outside of the object. Inside the 
class, you use the property name as the name of both the setter and the getter methods.  Is that the 
right way to think about it?


Finally, it seems very odd to me that when you use the @property decorator and the 
@.setter, that both of the methods that are decorated need to 
have the same name (but of course different set of parameters.)  As a teacher, this 
seems like it would be an extremely difficult concept to get across to students, as 
this does not work the same way as other Python functions (and methods).  Without a 
decorator, the second function of the same name overrides an earlier function of the 
same name, as in this simple example:


> [snip]
>

Irv



It's because of how Python implements decorators.  When I write

class C:
  def foobar(self):
pass

I create a binding in the local scope of class C with the name "foobar" 
that holds a function object.  We call this a "local variable" in 
keeping with other languages, but it's not really the same as it would 
be in like C, it's a reference in the local namespace to some other 
object.  When I decorate that foobar instead:


class C:
  @property
  def foobar(self):
pass

That variable now, instead of referencing a function object, references 
an instance of type 'property' that holds a reference to the original 
foobar method as it's "_getter".  When I expand that to


class C:
  @property
  def foobar(self):
return self.__foobar

  @foobar.setter
  def foobar(self, value):
self.__foobar = value

The second decoration calls the 'setter' method of the property instance 
stored in variable name foobar.  That method assigns the new method to 
the "_setter" of that property instance and returns the updated 
property, which is assigned redundantly to the variable name foobar.



--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python goto

2018-01-02 Thread Rob Gaddi

On 12/28/2017 04:35 AM, Skip Montanaro wrote:

Jorge> I would like to know if there is a goto command or something similar that
Jorge> I can use in Python.

Ned> Python does not have a goto statement. You have to use structured
Ned> statements: for, while, try/except, yield, return, etc.

Though it appears some wag has used function decorators to implement
goto statements:

https://pypi.python.org/pypi/goto-statement/1.1

Rather clever, it seems.

Skip



If only all that power had been used for good instead of evil...

--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Native object exposing buffer protocol

2018-01-05 Thread Rob Gaddi
I'd like to create a native Python object that exposes the buffer 
protocol.  Basically, something with a ._data member which is a 
bytearray that I can still readinto, make directly into a numpy array, etc.


I can do it by inheriting the entire thing from bytearray directly, but 
that gives me a whole lot of methods that are unsuitable for what I'm 
doing with it, which is reading the contents of a binary file, allowing 
them to be lightly malleable in memory, and then sending them on to a 
device.


Not the end of the world (the file's less than 2KB), but it seems like 
something that should be doable easily without having to throw around a 
lot of extraneous copies.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Native object exposing buffer protocol

2018-01-08 Thread Rob Gaddi

On 01/05/2018 04:27 PM, Ben Finney wrote:

Rob Gaddi  writes:


I'd like to create a native Python object that exposes the buffer
protocol.  Basically, something with a ._data member which is a
bytearray that I can still readinto, make directly into a numpy array,
etc.


The “etc.” seems pretty important, there. You want the behaviour of
‘bytearray’ without actually inheriting that behaviour from the
‘bytearray’ type. >


Well, one specific behavior.  Ideally, what I want is, when calls like 
RawIOBase.readinto and ndarray.frombuffer ask my class "Hey, do you have 
any raw bytes that I can read and potentially write?" it can answer "Why 
certainly, here they are."  Something like a:


class Thingy:
  def __memoryview__(self):
return memoryview(self._data)

But it doesn't look as if there's a dunder for that.  There's __bytes__, 
but that specifically requires you give back a bytes() object; even 
returning a bytearray causes an error.



So, it seems your options are:

* Enumerate all the things, specifically, that you do want your new type
   to do. Don't hide anything in “etc.”, so that you know exactly what
   behaviours need to be implemented. Implement all those behaviours,
   without benefit of inheriting from ‘bytearray’.

* Inherit from ‘bytearray’, but ameliorate the problems you want to
   avoid. This will require enumerating all those problems, so that you
   can know whether you have avoided them. Don't hide any of them in an
   “etc.”.


That's ultimately the way I'm going about it, but since this is only 
going to get used in-house, I'm approaching it the Pythonic way.  The 
problem is "Most methods of bytearray make no sense on a data structure 
representing a fixed length waveform."  The solution is "Well, don't use 
them."





Not the end of the world (the file's less than 2KB), but it seems like
something that should be doable easily without having to throw around
a lot of extraneous copies.


I look forward to your report from having tried it :-)




--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: pip --user by default

2018-01-15 Thread Rob Gaddi

On 01/13/2018 04:54 AM, Thomas Jollans wrote:

Hi,

I recently discovered the wonders of pip.conf: if I create a file
~/.config/pip/pip.conf* with:

[install]
user = true

then pip will install to the --user site-packages by default, rather
than trying to install packages into system directories.

The trouble is that this fails when you also use virtualenvs. In a
virtualenv, --user doesn't work, so pip fails when trying to install
anything in a virtualenv as long as the user pip.conf contains those lines.

Short of adding a pip.conf to every single virtualenv, is there any way
to work around this, and configure pip to install packages

  - into the user directories if possible
  - into the environment when in an environment

by default?

Thanks,
Thomas



* the path obviously depends on the OS:
https://pip.pypa.io/en/stable/user_guide/#config-file



Inside of a virtualenv, what's the difference between a --user install 
and a system one?


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


3.6.4 IDLE

2018-02-04 Thread Rob Alspach
Hi Everybody! I just installed python 3.6.4 it was a fresh install (no
former versions). I have never used python but have some IS background. The
videos I am seeing online all show the IDE / IDLE; however, it does not
install for me. I am installing from the download
python-3.6.4-embed-amd64.zip. I am running windows 10. I also have Oracle
on this laptop.

The file does not have an installer and also does not write to the file
path. I have already uninstalled and reinstalled the problem remains. I can
update the path no problem but where can I get the IDLE / IDE to follow
along with the videos on youtube? I am using notepad currently but have no
way to execute any files I write. If I save a file in notepad and open
through python the python window terminates when the operation is complete
(much to fast for these old eyes).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to work on a package

2018-02-07 Thread Rob Gaddi

On 02/07/2018 12:34 PM, Roel Schroeven wrote:

dieter schreef op 7/02/2018 8:21:

Likely, there are many ways to execute tests for your package.



I am using "setuptools" for packaging (an extension
of Python's standard "disutils"). Its "setup.py" supports the "test"
command. This means, properly set up, I can run tests
with "python setup.py test".


That can solve the testing issue, I guess, even though it feels weird to 
me that the most straightforward way doesn't work.


But testing is not the only issue. Often I'd like to start the Python 
interpreter to load one of the modules in the package to try some things 
out, or write a little script to do the same. These things are very 
natural to me when writing Python code, so it seems very strange to me 
that there's no easy way when working on a packages.


Don't other people do that?



The state of Python packaging is... unfortunate. Improving, due to huge 
amounts of work by some very dedicated people, but still unfortunate.


When I'm working on a module, the trick is to write a setup.py (using 
setuptools) from the very get-go.  Before I write a single line of code, 
I've got a setup.py and the directory framework.


Then you install the package using pip -e (or in practice --user -e). 
That's the missing piece.  That way you can import your module from the 
interpreter, because it's now on the path, but its physical location is 
right there where you left it, complete with your VCS metadata and etc.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to work on a package

2018-02-07 Thread Rob Gaddi

On 02/07/2018 03:17 PM, Grant Edwards wrote:

On 2018-02-07, Rob Gaddi  wrote:


When I'm working on a module, the trick is to write a setup.py (using
setuptools) from the very get-go.  Before I write a single line of code,
I've got a setup.py and the directory framework.

Then you install the package using pip -e (or in practice --user -e).
That's the missing piece.  That way you can import your module from the
interpreter, because it's now on the path, but its physical location is
right there where you left it, complete with your VCS metadata and etc.


How do you work on a package that must remain installed and usable the
whole time you're working on it?

IOW, only specific test apps or apps run in a specific directory
should get the "in-progress" foo module when they do an "import foo".



Achievable with a virtualenv, but now the process is even that much more 
complicated.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there are good DRY fix for this painful design pattern?

2018-02-26 Thread Rob Gaddi

On 02/26/2018 07:28 AM, Rhodri James wrote:

On 26/02/18 14:41, Steven D'Aprano wrote:

I have a class with a large number of parameters (about ten) assigned in
`__init__`. The class then has a number of methods which accept
*optional* arguments with the same names as the constructor/initialiser
parameters. If those arguments are None, the defaults are taken from the
instance attributes.

An example might be something like this:


class Foo:
 def __init__(self, bashful, doc, dopey, grumpy,
    happy, sleepy, sneezy):
 self.bashful = bashful  # etc

 def spam(self, bashful=None, doc=None, dopey=None,
    grumpy=None, happy=None, sleepy=None,
    sneezy=None):
 if bashful is None:
 bashful = self.bashful
 if doc is None:
 doc = self.doc
 if dopey is None:
 dopey = self.dopey
 if grumpy is None:
 grumpy = self.grumpy
 if happy is None:
 happy = self.happy
 if sleepy is None:
 sleepy = self.sleepy
 if sneezy is None:
 sneezy = self.sneezy
 # now do the real work...

 def eggs(self, bashful=None, # etc...
    ):
 if bashful is None:
 bashful = self.bashful
 # and so on

There's a lot of tedious boilerplate repetition in this, and to add
insult to injury the class is still under active development with an
unstable API, so every time I change one of the parameters, or add a new
one, I have to change it in over a dozen places.

Is there a good fix for this to reduce the amount of boilerplate?


You could use dicts?  Untested code:

class Foo:
     def __init__(self, **kwds):
     self.defaults = kwds

     def spam(self, **kwds):
     vars = self.defaults.copy()
     vars.update(kwds)
 # Do the work with vars['bashful'] etc




That's what I was about to suggest (and equally fail to test).  It at 
least segregates the set of "instance variables I want to have 
auto-default behavior" from the rest of them.  Yeah, **kwargs is clumsy, 
but it gets the job done.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: RFC: Proposal: Deterministic Object Destruction (Posting On Python-List Prohibited)

2018-03-01 Thread Rob Gaddi

On 03/01/2018 02:24 PM, Lawrence D’Oliveiro wrote:

On Thursday, March 1, 2018 at 6:44:39 PM UTC+13, Paul Rubin wrote:

DOM trees are a classic example (see the various DOM modules in the
Python stdlib).  Non-leaf nodes have a list of child nodes, child nodes
have pointers back upwards to their parent, and each child node has
pointers to its left and right siblings if they exist.  It's all very
circular.


This is why you have weak refs.



But making sure that the failure to use weakrefs doesn't memory leak the 
program into the pavement is why you have background garbage collection 
with intelligent cyclical reference breaking.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to minimize the need of run time checks?

2016-08-09 Thread Rob Gaddi
Juan Pablo Romero Méndez wrote:

> 2016-08-09 12:06 GMT-07:00 Paul Rubin :
>
>> Juan Pablo Romero Méndez  writes:
>> > In online forums sometimes people complain that they end up having to
>> > test constantly for None
>>
>> That's something of a style issue.  You can code in a way that avoids a
>> lot of those tests (not all of them).
>>
>
>
> This is exactly what I'm looking for :).  Do you have any resource (blog /
> book, etc) that discusses this style?
>

It's not a style, it's the absence of one.

def add2list(lst, elem):
lst.extend([elem, elem])
return lst

I did all the type checking I needed to there; none whatsoever.  If
passed a list, or something that behaves like one, that does the
expected thing.

If passed an ExtensionLadder, it probably does the wrong thing, but that
is no way my problem.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invalid Syntax

2016-08-09 Thread Rob Gaddi
Ltc Hotspot wrote:

> Hi, Everyone:
>
> What is the source of the following, 
> 'error message: SyntaxError: invalid syntax (, line 2)'
>
> v. Python 3.3
>
> Code reads:
>
> x=1
> if x==1
> # indent 4 spaces
> print "x = 1"
>
> Hal

A missing colon, the appropriate location of which is left as an
exercise to the reader.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to minimize the need of run time checks?

2016-08-09 Thread Rob Gaddi
Juan Pablo Romero Méndez wrote:

> 2016-08-09 13:18 GMT-07:00 Rob Gaddi :
>
>> Juan Pablo Romero Méndez wrote:
>>
>> > 2016-08-09 12:06 GMT-07:00 Paul Rubin :
>> >
>> >> Juan Pablo Romero Méndez  writes:
>> >> > In online forums sometimes people complain that they end up having to
>> >> > test constantly for None
>> >>
>> >> That's something of a style issue.  You can code in a way that avoids a
>> >> lot of those tests (not all of them).
>> >>
>> >
>> >
>> > This is exactly what I'm looking for :).  Do you have any resource (blog
>> /
>> > book, etc) that discusses this style?
>> >
>>
>> It's not a style, it's the absence of one.
>>
>> def add2list(lst, elem):
>> lst.extend([elem, elem])
>> return lst
>>
>> I did all the type checking I needed to there; none whatsoever.  If
>> passed a list, or something that behaves like one, that does the
>> expected thing.
>>
>> If passed an ExtensionLadder, it probably does the wrong thing, but that
>> is no way my problem.
>>
>
>
> So as the writer of the function you expect the user to read the function
> body to determine what is safe to pass or not?
>

No, but I expect them to read the function documentation.  The
alternative is to expect that the user is going to go around trying to
randomly call functions with whatever objects they happen to have lying
around in an attempt to figure out what they do.  The docstring for the
above function would probably be """Append two copies of elem to the
end of list lst."""

This goes back to the "consenting adults" principle in Python. 
Assume that the person calling your functions isn't a blithering moron
in need of protection from themselves. Sometimes you'll be wrong in
that assumption, but their life as a blithering moron is already quite
difficult and so you won't have substantially added to that by failing
to put guard rails up on your function. Conversely, if you explicitly
check isinstance(lst, list) then I can't, as one clever SOB, pass
it a list-like object and have it just work.  I instead would have to
have my object expressly subclass list, even if I had a reason not to.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3: Launch multiple commands(subprocesses) in parallel (but upto 4 any time at same time) AND store each of their outputs into a variable

2016-08-24 Thread Rob Gaddi
lax.cla...@gmail.com wrote:

> Hi,
>
> I've been reading various forums and python documentation on subprocess, 
> multithreading, PIPEs, etc.  But I cannot seem to mash together several of my 
> requirements into working code.
>
> I am trying to:
>
> 1) Use Python 3+ (specifically 3.4 if it matters)
> 2) Launch N commands in background (e.g., like subprocess.call would for 
> individual commands)
> 3) But only limit P commands to run at same time
> 4) Wait until all N commands are done
> 5) Have an array of N strings with the stdout+stderr of each command in it.
>
> What is the best way to do this?
> There are literally many variations of things in the Python documentation and 
> Stackoverflow that I am unable to see the forest from trees (for my problem).
>
> Thank you very much!

First off, I'm assuming that the stdout+stderr of these commands is of
reasonable size rather than hundreds of megabytes.

What you want is a finite pool of threads (or processes) that execute
the tasks.  multiprocessing.pool.Pool will do it.  So will
concurrent.futures, which is what I'd personally use just out of more
familiarity with it.

In either case your task should wrap a call to subprocess. 
subprocess.run is your easiest answer if you've got Python 3.5; the task
would call it with stdout and stderr=subprocess.PIPE, get the
CompletedProcess back, and then store the .stdout and .stderr string
results.  For older Python, create a subprocess.Popen (again with stdout
and stderr=subprocess.PIPE) and call the communicate() method.

There's probably a dozen other ways.  That one there, that's your
easiest.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: degrees and radians.

2016-08-24 Thread Rob Gaddi
murdocksgra...@gmail.com wrote:

> On Saturday, May 4, 2002 at 3:37:07 AM UTC-4, Jim Richardson wrote:
>> 
>> I am trying to get the math module to deal with degrees rather than
>> radians. (that it deals with radians for the angular functions like
>> sin() isn't mentioned in the docs, which was sort of an eyeopener :)  I
>> can't find any info on doing this. I can convert from-to degrees in the
>> code calling the function, but that's a bit clunky. Any pointers to an
>> FM to R? :
>> 
>> -- 
>> Jim Richardson
>>  Anarchist, pagan and proud of it
>> http://www.eskimo.com/~warlock
>> Linux, from watches to supercomputers, for grandmas and geeks.
>
> For what is is worth.. Electrical Engineers for the most part work in degrees 
> NOT Radians for example try doing polar to rectangular or vice versa in 
> polar. 
> I have never seen it done. 
>

While I fully admit to thinking in degrees, any time I'm actually doing
any mathematical work my units are either radians or cycles.  The
representation of angle in fixed point cycles actually comes out really
nicely; each bit takes you from hemispheres to quadrants to octants,
etc.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Alternatives to XML?

2016-08-24 Thread Rob Gaddi
Frank Millman wrote:

> Hi all
>
> I have mentioned in the past that I use XML for storing certain structures 
> 'off-line', and I got a number of comments urging me to use JSON or YAML 
> instead.
>
> In fact XML has been working very well for me, but I am looking into 
> alternatives simply because of the issue of using '>' and '<' in attributes. 
> I can convert them to '>' and '<', but that imposes a cost in terms of 
> readability.
>
> Here is a simple example -
>
> 
>   
> 
>   
> 
>   
>   
> 
>   
> 
>   
> 
>
> This is equivalent to the following python code -
>
> if _param.auto_party_id is not None:
> if on_insert:
> value = auto_gen(_param.auto_party_id)
> elif not_exists:
> value = ''
>
> The benefit of serialising it is partly to store it in a database and read 
> it in at runtime, and partly to allow non-trusted users to edit it without 
> raising security concerns.
>
> I ran my XML through some online converters, but I am not happy with the 
> results.
>
> Here is a JSON version -
>
> {
>   "case": {
> "compare": {
>   "-src": "_param.auto_party_id",
>   "-op": "is_not",
>   "-tgt": "$None",
>   "case": {
> "on_insert": {
>   "auto_gen": { "-args": "_param.auto_party_id" }
> },
> "not_exists": {
>   "literal": { "-value": "" }
> }
>   }
> }
>   }
> }
>
> I can see how it works, but it does not seem as readable to me. It is not so 
> obvious that 'compare' has three arguments which are evaluated, and if true 
> the nested block is executed.
>
> Here is a YAML version -
>
> case:
> compare:
>   case:
>on_insert:
> auto_gen:
>  _args: "_param.auto_party_id"
>not_exists:
> literal:
>  _value: ""
>   _src: "_param.auto_party_id"
>   _op: is_not
>   _tgt: "$None"
>
> This seems even worse from a readability point of view. The arguments to 
> 'compare' are a long way away from the block to be executed.
>
> Can anyone offer an alternative which is closer to my original intention?
>
> Thanks
>
> Frank Millman
>

You've been staring at that XML too long; you've become familiar with
it.  It's just as unreadable as the JSON or the YAML unless you already
know what it says.

That said, one core difference between XML and the other two is that XML
allows for the idea that order matters.  JSON and YAML both consider
key/value pair objects in the same way Python does a dict -- there is AN
order because there has to be one, but it's not expected to be
important or preserved. And when you start talking about "close to"
you're talking about preserving ordering.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Multimeter USB output

2016-08-29 Thread Rob Gaddi
Joe wrote:

> The UT61B has two interfaces, a RS232C interface and this usb interface. 
> The RS232 interface works well with PySerial. It continously transmits 2 
> .. 3 Pakets per second with 14 Bytes each. This happens unsolicited 
> without any command as long as the RS232C/USB button on the DMM is active.
>

>From someone who does a LOT of code to talk to DMMs, scopes, counters,
etc?  Word of advice.  You're done.  Declare victory and move on.

You've got it working on one interface.  The other is even less well
documented and requires doing deep-down stuff against libusb because
there's no actual kernel driver, and you've got a Chinese manufacturer
of a low-end device being of little to no help so now you're trying to
reverse engineer the protocol from bad code without even the help of a
packet sniffer.  This is the sort of rabbit hole that weeks manage to
fall into with nothing to show for them.

If this is an exercise in learning to work with libusb then have at. 
But if what you actually need from this is to talk to the meter?  You're
talking to it already.  Take the win and walk.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Linear Time Tree Traversal Generator

2016-09-20 Thread Rob Gaddi
ROGER GRAYDON CHRISTMAN wrote:

> I am trying to find a better (i.e. more efficient) way to implement a 
> generator
> that traverses a tree.
>
> The current model of the code (which is also used by a textbook I am teaching
> from does this)
>
>def __iter__(node):
>  for x in iter(node._left):
>   yield x
>  yield node._value
>  for x in iter(node._right)
>   yield x
>
> This is nice, simple, and straightforward, but has an O(n log n) running time,
> since
> values from the leaves of the tree have to be yielded multiple times to the 
> top
> of the tree.
>
> Now, I could certainly implement a linear-time traversal without the gnerator:
>
> def to_list(node,result):
>   """append node information to result"""
>   result = to_list(node._left, result)
>   result.append(node._value)
>   return to_list(node,_right, result)
>
> but then that requires the extra memory space to build the list into, which
> is basically what the generator is supposed to avoid.
>
> Now, I did see that itertools has a chain method for concatenating
> iterators, so it would be nice to concatenate the results from the 
> recursive calls without the for loops, but I have no idea how to
> squeeze the 'yield node._value' in between them.
>
> Is there hope for a linear-time tree-traversal generator, or will
> I have just have to settle for an n-log-n generator or a linear time
> behavior with linear extra space?
>
> Roger Christman
> instructor
> Pennsylvania State University
>

The only thing that's O(N log N) in that is the number of actual yield
calls.  If you're doing pretty much anything with those values as
they're being iterated over then they'll dominate the timing, and that
is O(N).

If you're using Python 3.4 or above you can turn that into

def __iter__(node):
  yield from iter(node._left)
  yield node._value
  yield from iter(node._right)

I think there's a little bit of optimization that goes on using yield
from.  That said, all this has a serious stink of premature
optimization.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Counting words in a string??

2016-09-30 Thread Rob Gaddi
Jake wrote:

> Hi, I need a program which:
> 1) Asks the user for a sentence of their choice (not including punctuation)
> 2) Ask the user which word they would like to know is repeated
> 3) Print out to the user how many times the word came up which they chose 
> from their sentence.
>
> It would help if you could comment the code. 
> Thankyou in advance!!

I'm sure it would help; your professor will probably take points off
otherwise.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python and ssh for remote login

2016-10-05 Thread Rob Gaddi
Noah wrote:

> Hello folk,
>
> I would like to use a python script to ssh into a server using a username
> and password and perhaps ass port.
>
> Any ideas on how to script that.
>
> Thanks
>
> Noah

paramiko

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to process syntax errors

2016-10-12 Thread Rob Gaddi
mr.puneet.go...@gmail.com wrote:

> On Monday, October 10, 2016 at 7:45:40 PM UTC+5:30, mr.pune...@gmail.com 
> wrote:
>> Hi 
>> 
>> Is there any way to capture syntax errors and process them ? I want to write 
>> a function which calls every time whenever there is syntax error in the 
>> program.
>> 
>> For example, 
>> 
>> inside example.py 
>> 
>> I just mention below line 
>> 
>> 
>> Obj = myClass()
>> Obj xyz
>> 
>> Obj is instance of a class. But there is syntax error on xyz. So I want to 
>> grab that error and process.
>> 
>> Regards, Puneet
>
> Steve, You are absolutely right. I am trying to eliminate the method of using 
> parenthesis while calling in my file. Especially when I call it from a 
> instance.

There's a simple solution then.  Don't do that.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: need help for an assignment plz noob here

2016-10-17 Thread Rob Gaddi
pedrorenato1...@gmail.com wrote:

> Hello guys. so my assignment consists in creating a key generator so i can 
> use it in later steps of my work. In my first step i have to write a function 
> called key_generator that receives an argument, letters, that consists in a 
> tuple of 25 caracters. The function returns a tuple of 5 tuples of caracters, 
> each tuple with 5 elements.
>  Sounds confusing right? well I have the final product but i dont know how to 
> get there. I was told by my professor that I dont really have to use any 
> complicated knowledge of python so I have to keep it simple. Can u help me 
> plz? just give me a hint how to do it and i'll do everything plz.
>
> example:
> Python Shell
>
>>>> letters = (‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, \
> ... ‘H’, ‘I’, ‘J’, ‘ ’, ‘L’, ‘M’, ‘N’, \
> ... ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, \
> ... ‘V’, ‘X’, ‘Z’, ‘.’)
>>>> key_generator(letters)
> ... ((‘A’, ‘B’, ‘C’, ‘D’, ‘E’),
> ... (‘F’, ‘G’, ‘H’, ‘I’, ‘J’),
> ... (‘ ’, ‘L’, ‘M’, ‘N’, ‘O’),
> ... (‘P’, ‘Q’, ‘R’, ‘S’, ‘T’),
> ... (‘U’, ‘V’, ‘X’, ‘Z’, ‘.’))

Start by playing with letters in the shell and seeing what you can do
with it.  The word you're looking for is 'slices'.  Figure out
interactively what you need to do, then write it up.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


System-wide module path

2016-10-24 Thread Rob Gaddi
On a Linux (Ubuntu) system, with no concerns for Python < 3.4, how do I
  a) Add a directory to the system-wide (rather than per-user) module
path? 
  b) Tell pip that I would like to install a given module to there.

What's going on is that we're trying to set up an internal software
distribution system to make sure that internally-written software gets
installed on a bunch of identical machines. The easiest mechanism to
work with in all of this is a single directory on the server that can
simply be rsync'd to all of the target machines.  So if I could do my
installs to /usr/highland/python3.4/site-packages, and put all the
executable stubs that pip creates into /usr/highland/bin, then I can
just rsync all of /usr/highland.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why keys method does not work with MutableMapping?

2016-11-11 Thread Rob Gaddi
triccare triccare wrote:

> Greetings,
>
> Apologies if this has shown up twice; I jumped the gun sending before
> confirming registration.
>
> I have a class that completely implements MutableMapping, meaning that all
> the abstract methods are implemented. However, the keys method no longer
> returns the keys, but simply a repr of the instance.  Example is below.
> Same is true for the items method.
>
> It would seem that, if all the abstract methods have been implemented, the
> keys and items methods should be able to perform exactly like the native
> dict versions. There does not seem to be a need to override these methods.
>
> Thank you for your time.
> triccare
>
> Code:
>
> from collections import MutableMapping
>
> class MyDict(MutableMapping):
>
> def __init__(self, *args, **kwargs):
> self.data = dict(*args, **kwargs)
>
> def __getitem__(self, key):
> return self.data[self.__keytransform__(key)]
>
> def __setitem__(self, key, value):
> self.data[self.__keytransform__(key)] = value
>
> def __delitem__(self, key):
> del self.data[self.__keytransform__(key)]
>
> def __iter__(self):
> return iter(self.data)
>
> def __len__(self):
> return len(self.data)
>
> def __keytransform__(self, key):
> return key
>
> md = MyDict({'a': 1, 'b':2})
> md.keys()
> ==> KeysView()

Nope, that's exactly right.  That's the python3 behavior.

>>> d = {'a': 1, 'b':2}
>>> d.keys()
dict_keys(['b', 'a'])

Keys returns a dedicated keys object now, not just a list.  That thing
you got back isn't a repr string; it's the actual object.  If it were a
string it'd be quoted.

Try list(md.keys()).


-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Access to the caller's globals, not your own

2016-11-14 Thread Rob Gaddi
Steven D'Aprano wrote:

> Suppose I have a library function that reads a global configuration setting:
>
> # Toy example
> SPAMIFY = True
> def make_spam(n):
> if SPAMIFY:
> return "spam"*n
> else:
> return "ham"*n
>
>
> Don't tell me to make SPAMIFY a parameter of the function. I know that. 
> That's 
> what I would normally do, but *occasionally* it is still useful to have a 
> global configuration setting, and those are the cases I'm talking about.
>
>
> Now the caller can say:
>
> import library
> library.SPAMIFY = False
> result = library.make_spam(99)
>
>
> but that would be Wrong and Bad and Evil, because you're affecting *other* 
> code, not your code, which relies on SPAMIFY being True. Doing this is 
> (maybe) 
> okay when testing the library, but not for production use.
>
> What I really want is for make_spam() to be able to look at the caller's 
> globals, so that each caller can create their own per-module configuration 
> setting:
>
> import library
> SPAMIFY = False  # only affects this module, no other modules
> result = library.make_spam(99)
>
>
> But... how can make_spam() look for the caller's globals rather than its own?
>
> I'd rather not do this:
>
>
> def make_spam(n, namespace):
> SPAMIFY = namespace['SPAMIFY']
> ...
>
> which forces the user to do this:
>
> result = library.make_spam(99, globals())
>
>
> which defeats the purpose of making it a global setting. (If I wanted to 
> *require* the caller to pass a parameter, I would just force them to pass in 
> the flag itself. The whole point is to not require that.)
>
> I'd be okay with making the namespace optional:
>
>
> def make_spam(n, namespace=None):
> if namespace is None:
> namespace = ... # magic to get the caller's globals
> SPAMIFY = namespace['SPAMIFY']
> ...
>
>
> but what magic do I need? globals() is no good, because it returns the 
> library's global namespace, not the caller's.
>
>
> Any solution ought to work for CPython, IronPython and Jython, at a minimum.
>

class Library:
  SPAMIFY = False
  def make_spam(m):
...

import library
Library = library.Library()

result = Library.make_spam(99)

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why does this list swap fail?

2016-11-14 Thread Rob Gaddi
38016226...@gmail.com wrote:

> L=[2,1]
> L[0],L[L[0]-1]=L[L[0]-1],L[0]
>
> The L doesn't change. Can someone provide me the detail procedure of this 
> expression?

Better question: Why does that list swap exist?  If you're just trying
to put the language through its paces that's one thing, but I certainly
hope that's not actually going to be production code.  Even if it were
right it's unreadable.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQt pass data from class

2016-11-15 Thread Rob Gaddi
luca72 wrote:

> Hello i need to this
>
> class Form(QWidget, Ui_Form):
> """
> Class documentation goes here.
> """
> def __init__(self, parent=None):
> """
> Constructor
> 
> @param parent reference to the parent widget
> @type QWidget
> """
> super(Form, self).__init__(parent)
> self.setupUi(self)
> self.tabWidget.setCurrentIndex(0)
> combo = QComboBox()
> self.disegno = Cornice()
>
> class Cornice(QPainter):
> 
> def __init__(self, parent=None):
> 
> lista_dati = []
>
> in the class Form i have a lineEdit
>
> in the class Cornice i need to write something link
>
> self.lineEdit.setText('blabla') that is in the class Form
>
> in wich way i can have access to the lineedit of class Form without event 
> from class Cornice
>
> Many Thanks

Traditionally you'd have Cornice emit a Signal, which when you
__init__the Form you'd connect to the appropriate slot.  I don't recall
PyQt syntax, but in PySide it would look like

self.disengo.theSignal.connect(self.lineEdit.setText)


-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >