Re: slightly OT -- LaTeX

2011-09-02 Thread Alan
http://www.pytex.org/

hth,
Alan Isaac
-- 
http://mail.python.org/mailman/listinfo/python-list


multiprocessing: child process share changes to global variable

2013-12-02 Thread Alan
In the code below, child processes see changes to global variables caused by 
other child processes. That is, pool.map is producing a list where the value of 
``lst`` is being (non-deterministically) shared across child processes.  
Standard advice is that, "Processes have independent memory space" and "each 
process works with its own copy" of global variables, so I thought this was not 
supposed to happen. In the end, the globals are not changed, which matches my 
expectation. Still, clearly I have misunderstood what seemed to be standard 
advice.  Can someone clarify for me?

Expected result from pool.map: [[0],[1],[2]]
Usual result: [[0],[0,1],[0,1,2]]
Occasional result: [[0],[1],[0,2]]

Thanks,
Alan Isaac


#--- temp.py -
#run at Python 2.7 command prompt
import time
import multiprocessing as mp
lst = []
lstlst = []

def alist(x):
lst.append(x)
lstlst.append(lst)
print "a"
return lst

if __name__=='__main__':
pool = mp.Pool(3)
print pool.map(alist,range(3)) #UNEXPECTED RESULTS
print "b"
time.sleep(0.1)

print "c"
print lst
print lstlst
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing: child process share changes to global variable

2013-12-09 Thread Alan
I received a suggestion off list that my results indicated that the jobs were 
not being distributed across the pool workers.  I used 
mp.current_process().name to confirm this suggestion.

Alan Isaac
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Distributing python applications as a zip file

2014-07-24 Thread Alan
On Wednesday, July 23, 2014 4:43:11 AM UTC-4, Leo jay wrote:
> But if you use windows and you happen to use multiprocessing,
> please be aware of this bug I encountered several years ago.
> https://mail.python.org/pipermail/python-dev/2011-December/115071.html


It looks like this was fixed for 3.2.  Was the fix ever backported to 2.7?

-- 
Thanks,
Alan Isaac
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: What is the simplest method to get a vector result?

2014-07-24 Thread Alan
You can use `list(math.sin(x * math.pi / 2) for x in index)` or use `numpy`, 
which supports array math.
-- 
https://mail.python.org/mailman/listinfo/python-list


building static python with Numeric

2007-07-17 Thread Alan
Dears,

It's about Pyhton for Linux X86.

First, I would like to know if it's possible to build a fully static
python binary, something that does not depends on others libraries
when using 'ldd python', e.g. If so, how?

Second, I would like to build a python for distribution that would
include (statically if possible) the package Numeric-24.2. Is it
possible? How?

Summarising, I would like to build a python binary independent of
others libraries where I could 'import Numeric'.

I would appreciate very much any help here.

Many thanks in advance.

Cheers,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Tix.Tk() on Mac Intel

2007-07-26 Thread Alan
Hi List!

I have I Macbook Pro Intel running OSX 10.4.10.

I downloaded Python 2.5 and tried
TclTkAquaBI-8.4.10.0.dmg, but I got:

Traceback (most recent call last):
 File "", line 1, in 
 File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py",
line 210, in __init__
   self.tk.eval('package require Tix')
_tkinter.TclError: no suitable image found.  Did find:
   /Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture

Which make sense since tcltkaqua is released only for PPC. Googling a
bit, since tcltkaqua stopped development, I found they recommended
ActiveTcl, but Tix is not included in the package.

So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got:
>>> Tix.Tk()
Traceback (most recent call last):
 File "", line 1, in 
 File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py",
line 210, in __init__
   self.tk.eval('package require Tix')
_tkinter.TclError: can't find package Tix

The only way I got Tix.Tk() working so far was using Fink but I want
the nice aqua visual for python. Is there any way of getting it
working?

I would appreciate any help here.
Many thanks in advance.
Cheers,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


python static with Numeric

2007-07-26 Thread Alan
Hi List!

Does anyone here knows how to compile python with Numeric in a static way?

Many thanks in advance.

Cheers,
Alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resolving declaring class of a method at runtime

2007-11-16 Thread Alan
On Nov 16, 8:51 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> There should be a term for "optimization" techniques that actually slow
> things down instead of speeding them up.
>

I belive those are the ones known as "premature optimizations", which
sit at the root of all evil

--
Alan

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


Re: Namespace troubles

2007-11-16 Thread Alan

> class MyFrame(wx.Frame):
> def __init__(self, parent, id, title):
> wx.Frame.__init__(self, parent, id, title, size=(600,500))
>
> nb = wx.Notebook(self)
> self.page1 = Form1(nb, -1)
> nb.AddPage(self.page1, "Choose Patient")
> self.page1.SetFocus()
>
> def patient_lookup(self, first_ltrs):
> self.page2 = Selectable.Repository(nb, -1, first_ltrs)
> nb.AddPage(self.page2, "Patient Lookup")
> self.page2.SetFocus()
>


> I'm getting an error from the patient_lookup function:  "global name
> 'nb' is not defined".  I don't understand how a function in the same
> class cannot see the wx.Notebook instance "nb".  I know it exists
> somewhere I just haven't found the name for it.  I've tried
> "frame.nb", "self.nb", f = GetTopLevelParent(self) then f.nb.  How can
> an instance of something just disappear?
>
> Thanks for any help.
>
> Mike

nb is a local variable within the __init__() method only.

This is the same as, e.g.:

def foo():
i = 0

def bar():
print i

The use of i in bar() is an error, because it is only assigned in
foo()


If you want to make it available to all methods within a class then
you need to attach it to the instance of that class, e.g.:

class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(600,500))
self.nb = wx.Notebook(self)
self.page1 = Form1(nb, -1)
self.nb.AddPage(self.page1, "Choose Patient")
self.page1.SetFocus()

def patient_lookup(self, first_ltrs):
self.page2 = Selectable.Repository(nb, -1, first_ltrs)
self.nb.AddPage(self.page2, "Patient Lookup")
self.page2.SetFocus()


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


Re: Sorting Countries by Region

2007-11-16 Thread Alan
On Nov 16, 8:28 pm, martyw <[EMAIL PROTECTED]> wrote:
>
> i would create a class to capture country information, e.g.


What is the advantage of this:

>  def __cmp__(self, other):
>  if self.name < other.name:
>  return -1
>  elif self.name > other.name:
>  return 1
>  else:
>  return 0
>

over
def __cmp__(self,other):
    return cmp(self.name,other.name)

?

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


Re: What is python?????

2007-11-16 Thread Alan
On Nov 16, 8:29 pm, [EMAIL PROTECTED] wrote:
> I still don't get it and I've been haunting this group for months...
>
> Mike

Go on then  ...

What ?

The punchline, do the punchline

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


Re: John Bokma harassment

2006-05-24 Thread Alan
With apologies to Voltaire:
If Xah Lee did not exist, it would be necessary for John Bokma to
invent him.

Xah and Bokma are both idiots, they truly deserve each other.  The
sooner you killfile these two clowns, the happier you'll be.

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


waiting on an event blocks all signals

2008-05-17 Thread alan
This ignores CTRL-C on every platform I've tested:

python -c "import threading; threading.Event().wait()"
^C^C^C^C

It looks to me like all signals are masked before entering wait(). Can
someone familiar with the internals explain and/or justify this
behavior? Thanks,

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


Re: waiting on an event blocks all signals

2008-05-17 Thread alan
On May 17, 3:06 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Sat, 17 May 2008 12:49:54 -0700, John Schroeder <[EMAIL PROTECTED]> wrote:
> >On Sat, May 17, 2008 at 12:32 PM, alan <[EMAIL PROTECTED]> wrote:
>
> >> This ignores CTRL-C on every platform I've tested:
>
> >> python -c "import threading; threading.Event().wait()"
> >> ^C^C^C^C
>
> >> It looks to me like all signals are masked before entering wait(). Can
> >> someone familiar with the internals explain and/or justify this
> >> behavior? Thanks,
>
> >^C only kills the main thread.  Use Control-Break to kill all threads.
>
> Look at that program.  It's single-threaded.  Where do you think the ^C
> is going? :)
>
> Jean-Paul

Look at this program which is also "single-threaded." Clearly,
python's doing something special. I'm hoping someone can tell me what,
and why.

/*
  pthreadsig.c

  $ gcc pthreadsig.c -lpthread
  $ ./a.out
  ^C
  $
*/

#include 

int main(int argc, char** argv) {
  int rc = 0;

  pthread_mutex_t mtx;
  pthread_cond_t cond;
  pthread_mutex_init(&mtx, 0);
  pthread_cond_init(&cond, 0);

  pthread_mutex_lock(&mtx);
  rc = pthread_cond_wait(&cond, &mtx);
  pthread_mutex_unlock(&mtx);

  return rc;
}
--
http://mail.python.org/mailman/listinfo/python-list


why are functions greater than numbers?

2011-01-24 Thread Alan
Why do function objects compare in this way to numbers?
Thanks,
Alan Isaac


>>> def f(): return
...
>>> f>5
True

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


use class factory to set required class variables?

2011-01-26 Thread Alan
I have a class ``A`` that is intentionally incomplete:
it has methods that refer to class variables that do not exist.
The class ``A`` has several complicated methods, a number
of which reference the "missing" class variables.
Obviously, I do not directly use ``A``.

I have a class factory ``f``` that subclasses ``A`` *only* in
order to define the class variables.

The motivation/problem:
I did this because I need many versions of class ``A``,
which differ only in the class variables, which are not
known until run time.

Q: On the face of it, did I pick a reasonable solution to
my problem?  If so is this a standard pattern?  If not,
can you mention a better approach?

My solution is working for me, but the class ``A``
is bugging me, because of the odd (to me) way in
which it is incomplete.  Obviously, I'm not a
computer science type ...

Thanks,
Alan Isaac

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


Re: use class factory to set required class variables?

2011-01-26 Thread Alan
On Jan 26, 4:37 pm, Alan  wrote:
> I have a class factory ``f``` that subclasses ``A`` *only* in
> order to define the class variables.

I suppose it would be clearer to say that `f` *returns*
subclasses of `A`.  Hopefully that was clear ...

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


can't use multiprocessing with class factory?

2011-01-28 Thread Alan
Can the below example be fixed to work?
Thanks,
Alan Isaac

import multiprocessing as mp

class Test(object):
pass

def class_factory(x):
class ConcreteTest(Test):
_x = x
return ConcreteTest

def f(cls):
print cls._x

if __name__ == '__main__':
pool = mp.Pool(2)
pool.map(f, [class_factory(i) for i in range(4)])

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


Re: can't use multiprocessing with class factory?

2011-01-28 Thread Alan
On Jan 28, 2:23 pm, Robert Kern  wrote:
> Send the (pickleable) factory and the arguments used to construct the 
> instance,
> not the unpickleable instance itself.
>
> def g(factory, i):
>  cls = factory(i)
>  print cls._x
>
> if __name__ == '__main__':
>pool = mp.Pool(2)
>pool.map(g, zip([class_factory] * 4, range(4)))



If I change that to g((factory,i)) it does work.

Thanks!

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


python2.6 atexit not working with programme using threads, but python 2.5 works

2010-06-03 Thread Alan
Hi there,


I got a code here to investigate and one big issue is that it uses threads
and have a cleanup function (that will halt the threads) called via atexit.
That all work fine with python 2.5 but when using python 2.6, if I have
threading running, atexit never calls my cleanup function. If explicitly do
cleanup(...) it works. If I have no threads on, atexit works too.

Any idea of how to debug this would very appreciated.

Thanks,

Alan

Python 2.6.5 (r265:79063, May 13 2010, 15:11:52)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin


-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


threading and atexit: different behaviour in python2.6 from 2.5

2010-06-04 Thread Alan
Hi there,

That's another try to get help about this issue I am facing. To help you to
help me here goes a simple example. This is a very simplification of a very
complex code.

 thread_ping.py  begin
import time
import sys
import atexit
from threading import Thread

class testit(Thread):
   def __init__ (self,ip):
  Thread.__init__(self)
  self.ip = ip
  self.status = 0
   def run(self):
  pingaling = os.popen("ping -q -c2 "+self.ip,"r")
  while 1:
line = pingaling.readline()
if not line: break
igot = re.findall(testit.lifeline,line)
if igot:
   self.status = int(igot[0])

def goodbye(t, report):
print 'Goodbye'
print "Status from ",t.ip,"is",report[t.status]

testit.lifeline = re.compile(r"(\d) packets received")
report = ("No response","Partial Response","Alive")

ip = "209.85.227.104" # www.google.com # try with a failing IP if you want
the test to last a bit longer

t = testit(ip)

atexit.register(goodbye, t, report)

t.start()

exit()
 thread_ping.py  end

If one runs like:

amadeus[2579]:~/TMP% time python2.6 thread_ping.py
Goodbye
Status from  209.85.227.104 is Alive
python2.6 thread_ping.py  0.02s user 0.02s system 3% cpu 1.056 total

(i.e., python2.6 wait till the thread finishes and leave... I don't want
this behaviour, see below)

and

amadeus[2580]:~/TMP% time python2.5 thread_ping.py
Goodbye
Status from  209.85.227.104 is No response
python2.5 thread_ping.py  0.01s user 0.01s system 90% cpu 0.030 total

(i.e., python2.5 promptly quit, as desired)

Could someone tell me how to get python2.6 to have the same behaviour I see
with python2.5 for this example code?

Any hint would be very much appreciated indeed.

Many thanks in advance.

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading and atexit: different behaviour in python2.6 from 2.5

2010-06-07 Thread Alan
Thanks MRAB. setDaemon gave some hope.

Alan

On Fri, Jun 4, 2010 at 16:46,  wrote:

> Alan wrote:
>
>> Hi there,
>>
>> That's another try to get help about this issue I am facing. To help you
>> to help me here goes a simple example. This is a very simplification of a
>> very complex code.
>>
>>  thread_ping.py  begin
>> import time
>> import sys
>> import atexit
>> from threading import Thread
>>
>> class testit(Thread):
>>   def __init__ (self,ip):
>>  Thread.__init__(self)
>>  self.ip = ip
>>  self.status = 0
>>   def run(self):
>>  pingaling = os.popen("ping -q -c2 "+self.ip,"r")
>>  while 1:
>>line = pingaling.readline()
>>if not line: break
>>igot = re.findall(testit.lifeline,line)
>>if igot:
>>   self.status = int(igot[0])
>>
>> def goodbye(t, report):
>>print 'Goodbye'
>>print "Status from ",t.ip,"is",report[t.status]
>>
>> testit.lifeline = re.compile(r"(\d) packets received")
>> report = ("No response","Partial Response","Alive")
>>
>> ip = "209.85.227.104" # www.google.com <http://www.google.com> # try with
>> a failing IP if you want the test to last a bit longer
>>
>> t = testit(ip)
>>
>> atexit.register(goodbye, t, report)
>>
>> t.start()
>>
>> exit()
>>  thread_ping.py  end
>>
>> If one runs like:
>>
>> amadeus[2579]:~/TMP% time python2.6 thread_ping.py
>> Goodbye
>> Status from  209.85.227.104 is Alive
>> python2.6 thread_ping.py  0.02s user 0.02s system 3% cpu 1.056 total
>>
>> (i.e., python2.6 wait till the thread finishes and leave... I don't want
>> this behaviour, see below)
>>
>> and
>>
>> amadeus[2580]:~/TMP% time python2.5 thread_ping.py
>> Goodbye
>> Status from  209.85.227.104 is No response
>> python2.5 thread_ping.py  0.01s user 0.01s system 90% cpu 0.030 total
>>
>> (i.e., python2.5 promptly quit, as desired)
>>
>> Could someone tell me how to get python2.6 to have the same behaviour I
>> see with python2.5 for this example code?
>>
>> Any hint would be very much appreciated indeed.
>>
>> Many thanks in advance.
>>
>>  The script won't exit while there are non-daemon threads running. You
> can make a thread a daemon by setting its 'daemon' attribute to True
> before starting the thread. If you want the script to be backwards
> compatible with Python 2.5 then use the 'setDaemon' method instead.
>
> I don't know why the script exited in Python 2.5 even though a
> non-daemon thread was still running.
>



-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


python2.5 x python2.6 in interactive mode

2010-06-07 Thread Alan
Hi there,

I have a code with a 'exit()' at the end. We run it usually as:

python2.5 -i code.py

and if everything is fine, the 'exit()' is called and there's no interactive
terminal.

However, doing the same above with python2.6 and I got:

amadeus[2738]:~/TMP% python2.6 -i thread_ping.py
Traceback (most recent call last):
  File "thread_ping.py", line 42, in 
exit()
  File "/sw/lib/python2.6/site.py", line 334, in __call__
raise SystemExit(code)
SystemExit: None
>>>

So, everything is fine except that it ended up in the interactive python
terminal. Is there a way of having the very behaviour I have with python 2.5
for my code in python 2.6?

Many thanks in advance,

Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


drag & drop in a python GUI application

2010-07-02 Thread Alan
Hello there,

I know drag & drop is not possible with TK. Which widget could I use for my
python application to be able to work with drag & drop?

Thanks,

Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


python3: help with subprocess

2010-07-14 Thread Alan
Hi there,

Module commands is gone in python3, so I am trying subprocess. So please I
would appreciate if someone can tell me how to do this better:

before I had:

cmd = 'uname -a'
out = commands.getoutput(cmd)

'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

now:

out = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout =
sub.PIPE).communicate()[0][:-1]

b'Darwin amadeus.local 10.4.0 Darwin Kernel Version 10.4.0: Fri Apr 23
18:28:53 PDT 2010; root:xnu-1504.7.4~1/RELEASE_I386 i386 i386 MacBookPro5,2
Darwin'

Yes, it's ugly. the [:-1] above is to get read of the last '\n' which with
getoutputs I didn't have. But what's giving headache is this "b'..." in the
beginning.

Can someone explain, point me to where I can now about it and how to make
this better? I wanted a plain string in out.

Many thanks in advance,

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


python3: help with pickle

2010-07-15 Thread Alan
Hi there,

This is more an exercise to myself to understand python3. I took a code I
wrote (acpype) and I am trying to make it compatible with either python 3 or
2.

I am trying to make a pickle file compatible with either python 3 and 2 as I
believe it should be possible.

I've looked at http://docs.python.org/py3k/library/pickle.html but still,
when I create a pickle file for an object with python 2.7 and then I try to
load it in python3, I got this:

Python 3.1.2 (r312:79147, Jul  7 2010, 10:55:24)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from acpype import * # this acpype package contains needed class ACTopol
>>> import pickle
>>> o = pickle.load(open('AAA.acpype/AAA.pkl','rb'))
Traceback (most recent call last):
  File "", line 1, in 
  File "/sw/lib/python3.1/pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
TypeError: ('__init__() takes at least 2 positional arguments (1 given)',
, ())
>>>

Now trying the contrary, pickle file is created with python3, I got this
when trying to load it with python 2.7:

Python 2.7 (r27:82500, Jul  7 2010, 10:48:15)
[GCC 4.2.1 (Apple Inc. build 5659)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from acpype import *
>>> import pickle
>>> o = pickle.load(open('AAA.pkl','rb'))
Traceback (most recent call last):
  File "", line 1, in 
  File "/sw/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
  File "/sw/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/sw/lib/python2.7/pickle.py", line 1083, in load_newobj
obj = cls.__new__(cls, *args)
AttributeError: class ACTopol has no attribute '__new__'

Apart that, everything else seems to work. Just one note more: when loading
the pickle file 2.7 in python 2.7, type(o) is , while
pickle 3 in python 3, type(o) is 

Many thanks in advance,

Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


python3: signal.signal/singal.alarm

2010-07-15 Thread Alan
Hi there,

I have this, say timeTol = 5 (5 seconds) and 'cmd' takes minutes to execute
:

import subprocess as sub

...

p = sub.Popen(cmd, shell=True, stderr = sub.STDOUT, stdout =
sub.PIPE)

pid = p.pid

signal.signal(signal.SIGALRM, signal_handler)

signal.alarm(timeTol)

And it works on python 2.x.

However, on python 3.x, the signal_handler is only called when 'p =
sub.Popen...' has finished (after minutes) and signal.alarm appears to not
be called at 5 sec. Can someone please explain me this behaviour and how to
solve this?

Many thanks in advance,

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


python3: signal.signal/singal.alarm not working as expected

2010-08-02 Thread Alan
Hi there,

I have this example code to illustrate a problem I am having with python3.
It works fine with python 2.6 and 2.7 but does not with python 3.1.

Please, can someone tell me why or how to fix this example?


from __future__ import print_function
import os, subprocess, signal

def signal_handler( signum, frame ):

print( "PID: %s" % pid )
print( "Timed out! Process %s killed, max exec time (%ss) exceeded" %
(pid, timeTol ) )
os.kill( int( pid ), 15 )
raise Exception( "Taking too long to finish... aborting!" )

if __name__ == '__main__':

timeTol = 5

cmd = 'find /'

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(timeTol)

p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout
= subprocess.PIPE)
pid = p.pid

out = str( p.communicate()[0].decode() )
print(out)


Many thanks,

Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


please, help with python 3.1

2010-08-02 Thread Alan
Hello List,

Please, can someone at least try this code below in python 3 and report me
back whether it works or not? Because for me this code works in python 2.6
but not with python 3.1. Thanks!


from __future__ import print_function
import os, subprocess, signal

def signal_handler( signum, frame ):

print( "PID: %s" % pid )
print( "Timed out! Process %s killed, max exec time (%ss) exceeded" %
(pid, timeTol ) )
os.kill( int( pid ), 15 )
raise Exception( "Taking too long to finish... aborting!" )

if __name__ == '__main__':

timeTol = 5

cmd = 'find /'

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(timeTol)

p = subprocess.Popen(cmd, shell=True, stderr = subprocess.STDOUT, stdout
= subprocess.PIPE)
pid = p.pid

out = str( p.communicate()[0].decode() )
print(out)


Alan

-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


errors and exception

2010-08-16 Thread Alan
Hello,

I am using things like:

except Exception as inst:

and

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

Things that seems to be new in python 2.6 and higher, however reading
http://docs.python.org/tutorial/errors.html and this not clear when this new
syntaxes appeared.

My trouble is that I want to make something similar above compatible with
python 2.5, but when running python2.5 I got:

except Exception as msg:
  ^
SyntaxError: invalid syntax

If there's a way (e.g. from __future__ ..., inherited modified Exception
class, etc) that could give a solution to keep my code in python 2.6 syntax
as above but compatible with python 2.5, that would be appreciated.

Many thanks in advance,

Alan
-- 
Alan Wilter S. da Silva, D.Sc. - CCPN Research Associate
Department of Biochemistry, University of Cambridge.
80 Tennis Court Road, Cambridge CB2 1GA, UK.
>>http://www.bio.cam.ac.uk/~awd28<<
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Any speech to text conversation python library for Linux and mac box

2013-06-13 Thread Alan Gauld

On 13/06/13 04:59, Ranjith Kumar wrote:

Hello all,
I'm looking for speech to text conversation python library for linux and
mac box, I found few libraries but non of them supports any of these
platform.


This list is for people learning the python language and standard library.

If you are looking for exotic libraries you should have more success 
posting on the general Python mailing list or newsgroup (comp.lang.python)


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

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


Help me with the script? How to find items in csv file A and not in file B and vice versa

2013-06-18 Thread Alan Newbie
Hello,
Let's say I want to compare two csv files: file A and file B. They are both 
similarly built - the first column has product IDs (one product per row) and 
the columns provide some stats about the products such as sales in # and $.

I want to compare these files - see which product IDs appear in the first 
column of file A and not in B, and which in B and not A.
Finally, it would be very great if the result could be written into two new CSV 
files - one product ID per row in the first column. (no other data in the other 
columns needed)

This is the script I tried:
==

import csv

#open CSV's and read first column with product IDs into variables pointing to 
lists
A = [line.split(',')[0] for line in open('Afile.csv')]
B = [line.split(',')[0] for line in open('Bfile.csv')]

#create variables pointing to lists with unique product IDs in A and B 
respectively 
inAnotB = list(set(A)-set(B))
inBnotA = list(set(B)-set(A))

print inAnotB
print inBnotA

c = csv.writer(open("inAnotB.csv", "wb"))
c.writerow([inAnotB])


d = csv.writer(open("inBnotA.csv", "wb"))
d.writerow([inBnotA])

print "done!" 

=

But it doesn't produce the required results.
It prints IDs in this format:
247158132\n

and nothing to the csv files.

You could probably tell I'm a newbie.
Could you help me out?

here's some dummy data:
https://docs.google.com/file/d/0BwziqsHUZOWRYU15aEFuWm9fajA/edit?usp=sharing

https://docs.google.com/file/d/0BwziqsHUZOWRQVlTelVveEhsMm8/edit?usp=sharing

Thanks a bunch in advance! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help me with the script? How to find items in csv file A and not in file B and vice versa

2013-06-18 Thread Alan Newbie
thanks a lot :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pymongo Error

2012-06-19 Thread Alan Gauld

On 19/06/12 06:22, Ranjith Kumar wrote:


I tried Django with Mongodb while running manage.py syncdb I endup with
this error


You might be better off trying a mongo forum./mailing list since this 
list is for Python beginners and focuses on the Python language and std 
library. Django is not in the standard library but is sufficiently 
common that you may get a response there. But Mongo is a wee bit 
specialised so it will be pure luck if you find a Mongo user who can 
answer...



django.db.utils.DatabaseError: Ordering can't span tables on
non-relational backends (content_type__app_label)


Given we can't actually see the command you are trying to execute
its virtually impossible to know what Mongo/Django/Python is complaining 
about. We would need to know a lot more about your data structure and 
your query. What is it you are trying to order for example? Does it span 
tables?


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



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


Re: Sudden doubling of nearly all messages

2012-07-22 Thread Alan Ristow

On 07/21/2012 12:48 PM, Dave Angel wrote:

Has anybody else noticed the sudden double-posting of nearly all
messages in the python mailing list?

[snip]

I'm using Thunderbird 14.0 on Linux 11.04, with mail configured for
non-digest mode.  I read the messages in threaded mode.

I'm pretty sure it is Thunderbird-related -- I have had this issue 
before as well. Unfortunately, I cannot remember how I solved it. It 
seems like there was a particular box that needed to be checked or 
unchecked in the IMAP settings for the mail server, but I can't be sure 
anymore.


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


codecs.register_error for "strict", unicode.encode() and str.decode()

2012-07-26 Thread Alan Franzoni
Hello,
I think I'm missing some piece here.

I'm trying to register a default error handler for handling exceptions
for preventing encoding/decoding errors (I know how this works and that
making this global is probably not a good practice, but I found this
strange behaviour while writing a proof of concept of how to let Python
work in a more forgiving way).

What I discovered is that register_error() for "strict" seems to work in
the way I expect for string decoding, not for unicode encoding.

That's what happens on Mac, Python 2.7.1 from Apple:

melquiades:tmp alan$ cat minimal_test_encode.py
# -*- coding: utf-8 -*-

import codecs

def handle_encode(e):
return ("ASD", e.end)

codecs.register_error("strict", handle_encode)

print u"à".encode("ascii")

melquiades:tmp alan$ python minimal_test_encode.py
Traceback (most recent call last):
  File "minimal_test_encode.py", line 10, in 
u"à".encode("ascii")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in
position 0: ordinal not in range(128)


OTOH this works properly:

melquiades:tmp alan$ cat minimal_test_decode.py
# -*- coding: utf-8 -*-

import codecs

def handle_decode(e):
    return (u"ASD", e.end)

codecs.register_error("strict", handle_decode)

print "à".decode("ascii")

melquiades:tmp alan$ python minimal_test_decode.py
ASDASD


What piece am I missing? The doc at 
http://docs.python.org/library/codecs.html says " For
encoding /error_handler/ will be called with a UnicodeEncodeError
<http://docs.python.org/library/exceptions.html#exceptions.UnicodeEncodeError> 
instance,
which contains information about the location of the error.", is there
any reason why the standard "strict" handler cannot be replaced?


Thanks for any clue.

File links:
https://dl.dropbox.com/u/249926/minimal_test_decode.py
https://dl.dropbox.com/u/249926/minimal_test_encode.py

-- 
Alan Franzoni
contact me at public@[mysurname].eu

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


Re: 10 sec poll - please reply!

2012-11-20 Thread Alan Meyer

On 11/20/2012 11:29 AM, mherrmann...@gmail.com wrote:

> ... generate_keystrokes?  ...

Not bad.  "gen_keystrokes", or even "keystrokes" might also do.

I suggest using a name that is unique enough that you can grep through 
piles of code and find where it's used.  "type" fails that test. 
"generate_keystrokes" passes with flying colors, but may be overkill.


Alan

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


Re: 10 sec poll - please reply!

2012-11-20 Thread Alan Bawden
Since the event being generated is commonly called a "keystroke", and since
my dictionary defines the noun "stroke" as being: "the act of striking", a
good verb to choose for the action itself would seem to be "strike":

strike('a')
-- 
http://mail.python.org/mailman/listinfo/python-list


Inserting Unicode chars in Entry widget

2012-12-29 Thread Alan Graham
Hello Python experts,

I want to insert Unicode chars in an Entry widget by pushing on buttons;
one for each Unicode character I need. I have made the Unicode buttons.
I just need a simple function that will send the Unicode character to
the Entry widget.
Is there a better approach?

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


Re: [Offtopic] Line fitting [was Re: Numpy outlier removal]

2013-01-11 Thread Alan Spence

On 09 Jan 2013, at 00:02:11 Steven D'Aprano  wrote:

> The point I keep making, that everybody seems to be ignoring, is that 
> eyeballing a line of best fit is subjective, unreliable and impossible to 
> verify. How could I check that the line you say is the "best fit" 
> actually *is* the *best fit* for the given data, given that you picked 
> that line by eye? Chances are good that if you came back to the data a 
> month later, you'd pick a different line!

It might bring more insight to the debate if you talk about parameter error and 
model error.  Steven is correct if you consider only parameter error.  However 
model error is often the main problem, and here using visual techniques might 
well improve your model selection even if it's not a real model but a visually 
based approximation to a model.  However, if you only do it by eye, you end up 
in a space which is not rigorous from a modelling perspective and other issues 
can arise from this.  Visual techniques might also help deal with outliers but 
again in an unrigorous manner.  Visual techniques can also bring in real world 
knowledge (but this is really the same point as model selection).

With regard to the original post on outliers, Steven made a lot of excellent 
points.  However there are at least two important issues which he didn't 
mention. (1) You must think carefully and hard about the outliers. For example, 
can they recur, or have actions in the real world been taken that mean they 
can't happen again?  Are they actually data errors?  How you deal with them 
might be changed by these types of consideration.  (2) It is best to fit your 
model with and without the outliers and see what impact it has on the real 
world application you're doing the analysis for.  It's also good to try more 
than one set of excluded outliers to see just how stable the results are 
depending on how many outliers you remove. If the results change much, be very 
careful how you use the results.

Alan

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


Re: Converting a string to a number by using INT (no hash method)

2013-01-22 Thread Alan Spence
On 22 Jan 2013, at 19:28, Ferrous Cranus  wrote:

> Τη Τρίτη, 22 Ιανουαρίου 2013 9:02:48 μ.μ. UTC+2, ο χρήστης Michael Torrie 
> έγραψε:
>> On 01/22/2013 11:37 AM, Ferrous Cranus wrote:
>> 
>>> == pin = int(
>> 
>>> htmlpage.encode("hex"), 16 ) % 1 
>> 
>>> ==
>> 
>>> 
>> 
>>> Can you please explain the differences to what you have posted
>> 
>>> opposed to this perl coding?
>> 
>>> 
>> 
>>> == foreach my
>> 
>>> $ltr(@ltrs){ $hash = ( $hash + ord($ltr)) %1; 
>> 
>>> ==
>> 
>>> 
>> 
>>> I want to understand this and see it implemented in Python.
>> 
>> 
>> 
>> It isn't quite the thing.  The perl code is merely a checksum of the
>> 
>> ascii value of the characters in the file name, that is then chopped
>> 
>> down to a number < 1.  The Python code is taking the ascii value of
>> 
>> each character in the file name, converting it to a hexadecimal pair of
>> 
>> digits, stringing them all out into a long string, then converting that
>> 
>> to a number using the hexadecimal number parser. This results in a
>> 
>> *very* large number, 8-bits per letter in the original file name, and
>> 
>> then chops that down to 1.  Technically neither method is a hash and
>> 
>> neither will generate unique numbers.
>> 
>> 
>> 
>> Here's the python algorithm used on a short word:
>> 
>> 'hello' => '68656c6c6f' (h = 0x68', e=0x65', 0x6c', 0=0x6f)
>> 
>> => 0x68656c6c6f => 448378203247
>> 
>> mod that with 1 and you get 3247
>> 
>> 
>> 
>> If you would simply run the python interpreter and try these things out
>> 
>> you could see how and why they work or not work.  What is stopping you
>> 
>> from doing this?
> 
> 
> May i sent you my code by mail so for you see whats wrong and 
> http://superhost.gr produces error?
> 
> 1. this is not a script that iam being paid for.
> 2, this is not a class assignemnt
> 
> I just want to use that method of gettign this to work.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

All pages, strings and objects map to:

http://redwing.hutman.net/~mreed/warriorshtm/ferouscranus.htm

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


Re: Common LISP-style closures with Python

2012-02-05 Thread Alan Ristow

On 02/05/2012 05:19 AM, Antti J Ylikoski wrote:


Yes, I do know that, but then it would not be a closure :-)


Forgive me if this is terribly naive, but what is the advantage of using 
a closure as opposed to, say, some other function that returns the same 
value in the same context, but is not a closure?


Alan

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


Is this the right list?

2012-02-15 Thread Alan McKay
Hey folks,

I looked all through the list of mailing lists on the
mail.python.orgserver and this seems to be the only one that might
apply to me other than
maybe the German list which did not seem to have any specific python issue
associated with it other than that you should write German on it.

I am having a problem moving an application from RHEL 5.7 to Ubuntu 11.11,
and the problem is around .py program.

It is a web based program, and seems to use a strange combination of
mod_python and python CGI as best I can tell.

Would this be the right list to ask?

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


Re: Is this the right list?

2012-02-16 Thread Alan McKay
>
> Welcome to the list.  There are lots of friendly folks here who will try
> to help.
>
>

I noticed that already - thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Python / Apache config issue

2012-02-16 Thread Alan McKay
OK, since you all said to send it, here it is :-)  Though I think it may be
an apache issue, I'll send it anyway.

I'm using the software called "Open Freezer" which is used to track
reagents and other chemicals in research labs.

I also posted this here on their discussion forums but have not heard
anything yet.  In general their install and config instructions are pretty
incomplete and even asking the authors direct questions sometimes does not
get very good answers

https://sourceforge.net/p/openfreezer/discussion/openfreezer/thread/789d5cdb/

It was working fine on Ubuntu 11.04 and RHEL 5.7 but I'm having issues on
Ubuntu 11.11 - in all cases the versions of python that come with the
respective OS

In the working version on Ubuntu 11.04 the entire apache instance was
dedicated to this app - something I cannot do on the RHEL and Ubuntu 11.11
machines

---snip---

The specific problem I am having is that I go to "Search Projects", and
then select a project and hit "Go", and it does not execute the python. In
one configuration, it downloads the .py script instead of executing it. In
the other configuration it tells me 404 cannot find it. I had this working
fine on RHEL 5.7 but now it is broken on Ubuntu (with the same config file)

Details below.

I had the basic CGI functions working fine on RHEL but had to move to the
latest version of Ubuntu server and am having trouble. One different aspect
of both my RHEL and Ubuntu setups is that I cannot dedicate the entire
Apache instance to Open Freezer, so my URL is not
http://MYIP/
it
is 
http://MYIP/openfreezer/
 .

On RHEL my openfreezer.conf file looks like this. Note there is no
VirtualHost because as mentioned I cannot dedicate this apache instance to
just open freezer, and I also do not have control over DNS so I cannot
assign a 2nd DNS name to this server.

Alias"/openfreezer""/var/www/OpenFreezer"
Alias"/openfreezercgi""/var/www/OpenFreezer/cgi"

Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
#AddHandler python26-mod_python .py
#AddHandler mod_python .py
PythonDebug On
#PythonHandler mod_python.publisher

AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler mod_python .py
#PythonDebug On
PythonHandler mod_python.cgihandler
PythonPath "['/var/www/OpenFreezer/cgi'] + sys.path"


This works fine on RHEL 5.7 with apache 2.2.3 . I select a project, hit
"Go" and it executes cgi/project_request_handler.py as it should. But with
the exact same config file on Ubuntu it instead tries to download the .py
instead of execute it. But I also try putting a couple of test programs in
my CGI directory. This first one tries to download as well with the above
config :

test.py
def index(req):
return "Test successful";


But this second one executes correctly :

testcgi.py
#!/usr/bin/python
print "Content-type: text/html"
print
print ""
print "
Hello!"
print ""

So I talk to the other guy here who started out working on this for us,
because he had it running on Ubuntu as well (a slightly older version -
11.04 versus my 11.11). He has apache 2.2.16 and I have 2.2.20

His config file looks like this - note that he does have the entire apache
server dedicated to Open Freezer so his URL is
http://HISIP/


ServerAdmin webmaster@localhost
ServerName localhost

DocumentRoot /var/www/OpenFreezer/

Options FollowSymLinks
AllowOverride All


Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
AddHandler mod_python .py
PythonDebug On
#PythonHandler mod_python.publisher




AllowOverride All
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
#AddHandler mod_python .py
#PythonDebug On
#PythonHandler mod_python.cgihandler


#
#
#

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"

Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.1/255.0.0.0 ::1/128



If I strip out the two Directory sections from that and make mine look the
same, then instead of trying to download the .py file what I get is this
error :

Not Found
The requested URL /openfreezer/cgi/project_request_handler.py was not
found on this server

and checking the apache error.log tha

Re: Is Programing Art or Science?

2012-04-03 Thread Alan Mackenzie
Hi, Xah,

In comp.emacs Xah Lee  wrote:

> For these computing jockeys, there remains the question of why Knuth
> named his books the ?Art? of Computer Programing, or why some
> computing luminaries litter the caution that programing is as much a
> art as science. What elite dimwits need to realize is that these
> authors are not defining or correcting, but breaking precepts among
> the automatons in programing industry.

He was using art in the sense of "the exercise of human skill (as
distinguished from nature)".  That's the second definition in my
dictionary.  When people talk about, for example, the art of painting
water colours, they mean the techniques of mixing paints, depicting
objects on paper, etc.  They are not referring to the artistic value of
the painting painted.

> yours humbly,
> 
> Xah

-- 
Alan Mackenzie (Nuremberg, Germany).

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


Making helper methods more concise

2012-04-16 Thread Alan Ristow
Hi all,

I have defined a class that includes a number of helper methods that
are useful to me, but pretty redundant. Something like so, where I
maintain a list of tuples:

class A(object):
def __init__(self):
self.listing = []

# This method does the work.
def append_text(self, text, style):
self.listing.append((text, style))

# The rest of the methods are just helpers.
def append_paragraph(self, text):
self.append_text(text, 'Paragraph')

def append_header(self, text):
self.append_text(text, 'Header')

def append_title(self, text):
self.append_title(text, 'Title')

obj = A()
obj.append_title('On Learning Something New About Python')
obj.append_header('A Question Is Posed')
obj.append_paragraph('Where is lorem ipsum when you need it?')


To me, this code is simple, clear, and easy to maintain, but
incredibly redundant. That's fine, I have no problem with that, but it
got me thinking: Is there a way to make the code more concise?

I know that concise is not necessarily better, but I am asking
primarily to educate myself rather than to improve this particular
piece of code -- the code only inspired the question. I'm trying to
wrap my head around decorators (aside from the simplest ones) and
metaclasses at the moment, so feel free to throw those sorts of
solutions into the mix if something like that would be appropriate.

Thanks,

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


Re: Learn Technical Writing from Unix Man in 10 Days

2012-04-29 Thread Alan Mackenzie
Hello, Xah.

In comp.emacs Xah Lee  wrote:
> Learn Technical Writing from Unix Man in 10 Days

> Quote from man apt-get:

>remove
>remove is identical to install except that packages are
> removed
>instead of installed.

> Translation:

>kicking
>kicking is identical to kissing except that receiver is kicked
>instead of kissed.

Ha ha ha ha!!

You don't need to go as far as apt-get to see this.  Even worse is C-h f
car in Emacs.  Imagine it before the last paragraph got added.  This only
happened after a fairly long thread on emacs-devel.

There are far too many man pages which are suboptimal, to say the least.

> further readings:

[  ]

> DISAPPEARING URL IN DOC

> so, i was reading man git. Quote:

>Formatted and hyperlinked version of the latest git documentation
> can
>be viewed at http://www.kernel.org/pub/software/scm/git/docs/.

> but if you go to that url, it shows a list of over one hundred fourty
> empty dirs.

> I guess unix/linux idiots can't be bothered to have correct
> documentation. Inability to write is one thing, but they are unable to
> maintain a link or update doc?

Maintaining links is actually quite hard.  After the struggle to document
"remove", one typically has insufficient energy left over to check all
the links.

> does this ever happens to Apple's docs? If it did, i don't ever recall
> seeing it from 18 years of using Mac.

Have you ever tried to set up CUPS, the printing system?  At one point,
you're supposed to enter the "URI" of the printer, without any explanation
of what the URI of a local printer is.  At another point you're prompted
to enter "Name".  Name of what?  If you click on the "help", you get
taken to a search box, not proper docs.  Typing "name" into the search
box isn't useful.  And so it goes on.

CUPS is an Apple product.

> more records of careless dead link:

[  ]

-- 
Alan Mackenzie (Nuremberg, Germany).

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


Re: Pydev configuration

2012-05-09 Thread Alan Ristow

On 05/09/2012 01:16 PM, hamiljf wrote:

I suppose this is the nearest thread... editor configuration and all.
I'm using PyDev in a MyEclipse environment and it works fine, except for one
tiny but horrible niggle.

The editor function I can't find is block indent/exdent... like you can
block comment/uncomment it would be really handy to be able to do the same
with indentation.  I cannot believe the function isn't there, but I cannot
find it.


Select the code block you want to indent and hit Tab. To do the reverse, 
hit Shift-Tab.


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


ucs2 and ucs4 python

2012-05-15 Thread Alan Kesselmann
Hello

I tried using one compiled library and got this error:
ImportError: /home/alan/Downloads/pdftron/PDFNetC64/Lib/
_PDFNetPython2.so: undefined symbol: PyUnicodeUCS2_AsUTF8String

I googled around and found some info about the meaning of the error.
The creators of PDFNet suggested i install UCS2 python next to my UCS4
version to try their library.

Can someone point me towards a resource or two which will tell me how
to do this - im not very good with whole linux/servers stuff. Im using
ubuntu linux - if that makes any difference.

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


Re: Fall in love with bpython

2011-07-27 Thread Alan Gauld

Karim wrote:


I use bpython interpreter. This is a very good interactive CLI.


I had never heard of it and had to google for it.
It appears to be a curses based CLI for *nix and MacOS



I want to create a CLI with the same features than bpython.
But the cmd std module seems no to be used in this project...


Why not read the bpython source to see what they used?
Thats the big advantage of open source - its open!
(Although they don't make the source explicitly available,
I'm assuming the tar file contains the source- it might
even be in Python!)

They use pygments to parse the source as you type.
That would be worth investigating too...


HTH,

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


Re: list comprehension to do os.path.split_all ?

2011-07-28 Thread Alan Meyer

On 7/28/2011 4:18 PM, gry wrote:

[python 2.7] I have a (linux) pathname that I'd like to split
completely into a list of components, e.g.:
'/home/gyoung/hacks/pathhack/foo.py'  -->   ['home', 'gyoung',
'hacks', 'pathhack', 'foo.py']

os.path.split gives me a tuple of dirname,basename, but there's no
os.path.split_all function.

I expect I can do this with some simple loop, but I have such faith in
the wonderfulness of list comprehensions, that it seems like there
should be a way to use them for an elegant solution of my problem.
I can't quite work it out.  Any brilliant ideas?   (or other elegant
solutions to the problem?)

-- George


This is not properly portable to all OS, but you could simply split on 
the slash character, e.g.,


pathname.split('/')

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


Re: Only Bytecode, No .py Files

2011-07-29 Thread Alan Meyer

On 07/26/2011 11:19 AM, Eldon Ziegler wrote:

Is there a way to have the Python processor look only for bytecode
files, not .py files? We are seeing huge numbers of Linux audit messages
on production system on which only bytecode files are stored. The audit
subsystem is recording each open failure.

Thanks,
Eldon Ziegler


Here are two suggestions:

1. Put a dummy python file in the directory that does very little, 
perhaps something like:


   print("%s: You should not be seeing this" % sys.argv[0])

Give it the name of one of the .pyc, e.g., if foo.pyc, then foo.py.

Give the bytecode file a later date, e.g., "touch foo.pyc" (assuming you 
can do that without messing up other aspects of your system.)


If that works, then copy the dummy file to each of the other required 
.py names in the directory.  You'll then have to touch *.pyc to ensure 
that the pyc's have later dates.  After that, you won't have to do 
anything when you replace a .pyc file.  When you add a new .pyc you'll 
need to do the copy and touch again.


2. Use a log truncator to truncate the audit log.

I don't remember the name of one at the moment, but I believe there is 
at least one open source program that will monitor named files and 
truncate them from the beginning to a fixed maximum size.


I don't like this method as much as the first because it might result in 
something important being truncated.


Alan

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


Re: Another win for profiling.

2011-07-29 Thread Alan Meyer

On 07/29/2011 07:46 AM, Roy Smith wrote:

It's often said that you shouldn't try to guess what's slow, but use
profiling tools to measure what's slow.  I had a great example of that
yesterday.  ...


Yes.

My first experience of profiling was about 25 years ago.  I was 
experimenting with Borland's Turbo Profiler on C code.  I thought to 
myself, What kind of clueless programmer doesn't know where his code is 
spending its time?  How useful could this be?


Then I ran the profiler and found out how clueless I really was.  The 
profiler showed me that I could change one line in a thousand line 
program and cut the run time by 50%.


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


Re: Composition instead of inheritance

2011-05-02 Thread Alan Meyer

On 4/28/2011 1:15 PM, Ethan Furman wrote:

For anybody interested in composition instead of multiple inheritance, I
have posted this recipe on ActiveState (for python 2.6/7, not 3.x):

http://code.activestate.com/recipes/577658-composition-of-classes-instead-of-multiple-inherit/


Comments welcome!

~Ethan~


That looks pretty clever.  I tried adding this method to Spam:

def test_eggs_02(self):
print('testing eggs_02 from spam')

and it did just what we wanted.

I'm going to have to study this one.

Thanks.

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


Re: Python/New/Learn

2022-05-05 Thread Alan Gauld
On 05/05/2022 02:36, Patrick 0511 wrote:
> Hello, I'm completely new here and don't know anything about python. 

Do you know any other programming languages?
That makes a huge difference in what you should start with!

> Can someone tell me how best to start? 
> So what things should I learn first?

Others have already made recommendations.

I'll add that there is a dedicated python ttutor list for
those just learning to ask questions. It is slightly more
tolerant of "silly" questions and rookie mistakes than
the main list here.

You'll also find most of the discussions there will be
closer to your level than the more advanced topics that
get addressed here.

Finally, I have a tutorial aimed at complete beginners,
see the link below...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

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


Re: tail

2022-05-09 Thread Alan Bawden
Marco Sulla  writes:

   On Mon, 9 May 2022 at 19:53, Chris Angelico  wrote:
   ...
   Nevertheless, tail is a fundamental tool in *nix. It's fast and
   reliable. Also the tail command can't handle different encodings?

It definitely can't.  It works for UTF-8, and all the ASCII compatible
single byte encodings, but feed it a file encoded in UTF-16, and it will
sometimes screw up.  (And if you don't redirect the output away from
your terminal, and your terminal encoding isn't also set to UTF-16, you
will likely find yourself looking at gibberish -- but that's another
problem...)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: min, max with position

2022-06-04 Thread Alan Bawden
"Michael F. Stemper"  writes:

   Are there similar functions that return not only the minimum
   or maximum value, but also its position?

>>> specialmin(l)
(0,1.618033)
>>> specialmax(l)
3.141593
>>>

I believe that what you are looking for is usually called "argmax" and
"argmin" (see ).  These don't exist in
the standard Python library as far as I can tell, but numpy does have
"argmax" and "argmin" routines.

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: on a statement followed by an expression

2022-06-04 Thread Alan Bawden
Meredith Montgomery  writes:

   How can I execute a statement followed by a value in a single line?

   def roberry_via_reduce(rs):
 return my_reduce(rs, lambda d, r: ``increment and return d'', {})

The grammar or Python is deliberately designed so that the body of a
lambda expression cannot contain any statements.  So your original code,
where you defined a separate `count_in' procedure, is probably what you
want.

Although using `reduce' is kind of silly in this case because you aren't
computing a new dictionary every time, but instead you are mutating the
_same_ dictionary every time.  Your original code that used a `for' loop
is actually much clearer.

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: random.SystemRandom().randint() inefficient

2022-07-27 Thread Alan Bawden
Cecil Westerhof  writes:

   Yes, I try to select a random element, but it has also to be removed,
   because an element should not be used more as once.

Instead of using pop to do that why not something like:

def lazy_shuffle(seq):
"""
Generate the elements of the given sequence in a random order.
"""
# Delete the next line if you want to use a different version of
# randrange:
from random import randrange
# Delete the next line if SEQ is already a mutable sequence and you
# are willing to have it destroyed by this process:
seq = list(seq)
n = len(seq)
while n:
i = randrange(n)
yield seq[i]
n -= 1
if i < n:
seq[i] = seq[n]

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: random.SystemRandom().randint() inefficient

2022-07-27 Thread Alan Bawden
Cecil Westerhof  writes:

   Alan Bawden  writes:

   > Cecil Westerhof  writes:
   >
   >Yes, I try to select a random element, but it has also to be removed,
   >because an element should not be used more as once.
   >
   > Instead of using pop to do that why not something like:
   >
   > def lazy_shuffle(seq):
   > """
   > Generate the elements of the given sequence in a random order.
   > """
   > # Delete the next line if you want to use a different version of
   > # randrange:
   > from random import randrange
   > # Delete the next line if SEQ is already a mutable sequence and you
   > # are willing to have it destroyed by this process:
   > seq = list(seq)
   > n = len(seq)
   > while n:
   > i = randrange(n)
   > yield seq[i]
   > n -= 1
   > if i < n:
   > seq[i] = seq[n]

   That looks interesting.
   But there is on problem. (I think.)
   The list is only partly eaten and I will eat a lot of sequences. So a
   lot of sequences will be left in the runtime.
   Or is there a way to destroy the lazy_shuffle when it is not needed
   anymore?

You don't have to worry about that.  That's what Garbage Collection is
for.  After you drop the last reference to the generator, the GC will
destroy it for you.  Welcome to Python.

BTW, what I wrote might be slightly faster if you replace it with:

while n:
i = randrange(n)
yield seq[i]
n -= 1
seq[i] = seq[n]

That will save you some time spent testing and branching.

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: an oop question

2022-10-31 Thread Alan Gauld
On 30/10/2022 14:01, Julieta Shem wrote:

> I wrote the classes
> 
>   class Empty:
> ...
>   class Pair:
> ...
> 
> (*) How to build a stack?
> 
> These Lisp-like sequences are clearly a stack.  

That is a very important observation. A Pair IS-A Stack(sort of).
If you had a stack you could create a Pair from it certainly.

> So far so good, but when it comes to building a better user interface
> for it I have no idea how to do it.  I think one of the purposes of OOP
> is to organize code hierarchically so that we can reuse what we wrote.

One of the purposes of classes certainly. I'm not so sure it's a purpose
of OOP. They are not the same thing. A class is a programming construct
OOP is a programming style. Classes facilitate OOP but can be used
outside of OOP too.

> So I tried to make a Stack by inheriting Pair.

But you said above that a Pair was a Stack. Inheritance implies an
IS-A relationship, so Stack inheriting Pair would mean that a Stack
was a Pair. That is not really true.

A Stack could use a Pair (or many of them) but it is not a Pair.

Trying to use inheritance inappropriately is one of the
biggest (and commonest) mistakes in OOP. It invariably leads
to complications. If in doubt use delegation instead.


> class Stack(Pair):
> pass
> 
>>>> Stack(1, Empty())
> Stack(1, Empty())
> 
> Then I wrote pop and push.
> 
>>>> Stack(1, Empty()).pop()
> 1
> 
>>>> Stack(1, Empty()).push(2)
> Stack(2, Stack(1, Empty()))
> 
> So far so good.  Now let me show you what I can't do.
> 
> (*) The difficulty of encapsulating a union
> 
> The Lisp-like sequences we're building here are union-like data
> structures.  A /sequence/ is either Empty() or Pair(..., /sequence/).  I
> have not found a way to represent this either-or datastructure with a
> class.  For example, there is no way right now to build an empty Stack
> by invoking the Stack constructor.
> 
>>>> Stack()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: Pair.__init__() missing 2 required positional arguments: 'first' 
> and 'rest'
> 

The usual Python approach to such things is to put some default
values(often None but could be an Empty instance in your case)
in the init() method parameter list. Then test if the inputs
are None and if so take the appropriate action.

> class Pair:
>   def __init__(self, first=Empty(), rest=Empty()):

Like this.

> if not isinstance(rest, Pair) and not isinstance(rest, Empty):
>   raise ValueError("rest must be Empty or Pair")
> self.first = first
> self.rest = rest
>   def fromIterable(it):
> if len(it) == 0:
>   return Empty()
> else:
>   return Pair(it[0], Pair.fromIterable(it[1:]))
>   def __str__(self):
> return "{}({!r}, {})".format(self.__class__.__name__, self.first, 
> str(self.rest))
>   def __repr__(self):
> return str(self)
>   def __len__(self):
> return 1 + self.rest.__len__()
> 
> class Empty:
>   def __len__(self):
> return 0
>   def __str__(self):
> return  "Empty()"
>   def __repr__(self):
> return self.__str__()
>   def __new__(clss):
> if not hasattr(clss, "saved"):
>   clss.saved = super().__new__(clss)
> return clss.saved
> 
> class Stack(Pair):
>   def pop(self):
> return self.first
>   def push(self, x):
> return Stack(x, self)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: an oop question

2022-11-02 Thread Alan Gauld
On 01/11/2022 17:58, Julieta Shem wrote:

> nowhere in trying to detect in high-precision what is OOP and what is
> not. 

Stefan has given a good answer but essentially OOP is a program
that is structured around objects communicating by sending
messages to one another.

Objects are, in most (but not all) languages implemented using classes.
A class is just a record or structure that can contain data and
functions. In most (but not all) implementations of OOP messages
are implemented as calls to the functions within an objects class.


>  The same for classes.  I always liked to think of C structures as
> some class. 

Provided that we allow pointers to functions within the struct then yes.
Indeed the difference between structs and classes in C++ is very thin.

And with the recent introduction of data classes in Python the
boundaries are blurred here too. In pure OOP a class with only
data would be pointless(since the data should ideally be hidden
or "private"!)

> structure Whatever si the class itself.  Is this use of C outside of
> OOP?  I say it is not because my notion of OOP is that --- a way to make
> objects and have methods operate on them, changing them or not.

It's how many early attempts at OOP in C worked, including C++.
Others, such as Objective C and cFlavours took a different approach.

But conceptually methods do not "operate on objects"
methods are how objects respond to messages. Eah object has its own
method of handling a particular message. (This is polymorphism)
In most (but not all) practical implementations methods are
usually implemented as functions and so it seems like a message
is just a synonym for acalling a method, but is more than that, it
implies some kind of dynamic lookup. (for example when the method is
implemented in a paremt class rather than the directly referenced one.

But the functions that represent methods do indeed operate on their
own object - ie self.

> To me what distinguishes functional from imperative is, 

Not that imperative programming is not the same as OOP. Or at
least it encompasses much more than OOP. Most OOP programs are
written in imperative languages but it is possible to have
functional OOP programs too. (If we consider the state data
to be a single compound value that can only be changed by
the object internally, or a new object with different
state values returned.)

>> IS-A relationship, so Stack inheriting Pair would mean that a Stack
>> was a Pair. That is not really true.
> 
> That's another interesting observation.  I do not have much
> understanding of how to really think of these things

Read up on the Liskoff substitution principle as one approach to
determining what an IS-A relationship means. Its not the only
approach but it is less vague than some others!

>> to complications. If in doubt use delegation instead.
> 
> What is delegation?

A fancy OOP term to mean containment.
Specifically a method delegates the work top some internal
object. eg. You can build a stack by containg a list within
it. The stack delegates much of the work to the list object.
In fact, in Python a stack can be a very thin wrapper over
a list!

> Any book recomendations on getting this thing mathematics-clear?

The best book is IMHO Bertrand Meyer's book "Object Oriented
Software Construction". It uses his own language,. Eiffel, but
gives an excellent description of applied OOP and all of its
features (Eiffel is perhaps the most feature complete OOPL of
all - but, being proprietary (and somewhat buggy!) it has
never quite caught on)

But for a mathematical basis you need to look outside programming
at systems engineering and the work done on cellular automata.
In a pure OOP program each object should act as an independant
cell communicating by asynchronous messages. Exactly as in
cellular automata theory. ..

Unfortunately, there is a huge gap between pure OOP theory and
practical OOP languages! And just as big a gap between OOP language
potential and real-world OOP usage.  Very few purely OOP programs
exist (maybe excepting in Smalltalk - see Stefan's posts again). :-(

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [correction]an oop question

2022-11-02 Thread Alan Gauld
On 02/11/2022 20:21, Dennis Lee Bieber wrote:

>>  shows that in Python we do *not* need subclassing/inheritance
>>  for polymorphism!
>>
>   To me, that is not really an example of polymorphism, but more an
> example of Python's "duck typing".

But duck typing is a perfectly good implementation of polymorphism.
The term just means that different objects respond to the same
message in different ways. Nothing more, nothing less. Inheritance
just happens to be the most common way of building that, especially
in statically typed languages.

> 
>   I'd implement the example hierarchy as
> 
>>>> class Language:
> ...   def f(self):
> ...   print(self.greeting)

And that would be perfectly valid too.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: an oop question

2022-11-03 Thread Alan Gauld
On 03/11/2022 00:25, Julieta Shem wrote:

>> |OOP to me means only messaging, local retention and protection and
>> |hiding of state-process, and extreme late-binding of all things.
> 
> I'm wondering how Python fails to satisfy his definition.

Python doesn't do any form of data protection/hiding. All
attributes are public by default.

In Smalltalk all attributes are private, with no way to
make them public... Actually in C++/Java terms I believe
they are "protected" because subclasses can access
them(I think?).

Also Python is not a purely OOP language, in that you can write
functional and procedural code in Python if you wish. In
Smalltalk thats notionally impossible because everything
is an object. And all programming statements are messages
to objects.

Even an if/else test is a message to the boolean object:

(5>3) ifTrue: 
  ifFalse: 

ifTrue is a message to the boolean result of the expression
which has a parameter of a block of code. It executes the
block if the boolean is true.
ifFalse is likewise a message to the same boolean object
but only executes its block if the boolean is false.

(Apologies if the syntax is out, its been a while since I
wrote any Smalltalk!)

Similarly loops are implemented as messages:

 whileTrue: 
 to:  do: 

So in Smalltalk absolutely everything is a message to an object.

Python by comparison is much more traditional in form.

It is possible to write procedural, non OOP code in
Smalltalk but you really have to fight the system to
do so.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: an oop question

2022-11-03 Thread Alan Gauld
On 03/11/2022 18:29, Chris Angelico wrote:
> On Fri, 4 Nov 2022 at 05:21, Julieta Shem  wrote:
>>
>> Chris Angelico  writes:
>>
>>> On Thu, 3 Nov 2022 at 21:44, Alan Gauld  wrote:
>>>> Also Python is not a purely OOP language, in that you can write
>>>> functional and procedural code in Python if you wish. In
>>>> Smalltalk thats notionally impossible because everything
>>>> is an object. And all programming statements are messages
>>>> to objects.
>>>
>>> In Python, everything is an object. Doesn't that equally mean that
>>> Python is purely OOP?
>>
>> I think Alan Gauld pointed out that even syntax is an object in
>> Smalltalk --- or was.  An if-statement in Python is not an object.
> 
> Okay, fair; although I would be highly surprised if syntax is actually
> an object 

The syntax isn't, it is a specification, but the AST certainly
is and you can instantiate it and examine it from code.

But the context here was Why *Alan Kay* doesn't include Python
with Smalltalk as being OOP. There are plenty others who would
call it so.

But as for everything being an object, that's true but it doesn't
alter the fact that the default mode of python programming is not
to structure the code as a set of communicating objects (even if
at some level everything is an object) but as a set of
hierarchical functions.

And fundamentally that's what Kay means by OOP. The program (not
the language!) is built around objects. One of the greatest
barriers to the adoption of OOP is the confusion between OOP
and OOPL. And sadly the majority of attention has been on OOPL
rather than OOP...

> the concept "pass this message to this object" an object? Is the
> message itself an object? Is it objects all the way down?

At some point you hit C/Assembler. But it is astonishing just
how far down the objects go in Smalltalk.

But the control flow etc are fully OOP as per my last message.
It if quite possible to subclass Boolean and override the
whileTrue method to do something completely different to
the normal while loop behaviour. Is it wise? No. But it
is definitely possible!

> At some point, any language with objects in it is "object oriented" to
> some extent, and after that, it's all a spectrum. 

And this is exactly the problem. In the 80s we had a fairly clean
concensus of what OOP meant and several different language approaches
to that. But when C++ became popular(the defacto standard) peple started
focussing on the language features and totally missed that Object
Oriented Programming means writing programs that consist of objects
communicating by messages. The language features(even classes) are
merely implementation details. (I suspect this was partly driven
by the fact that many university lecturers at the time didn't
really grok OOP and teaching language features was much easier
than teaching a new way of thinking about problems!)

This was compounded when someone (Booch maybe?) came up with a set
of criteria to determine whether a language was a "true OOPL" or
merely "Object Based" (Ada and VB they're looking at you!) But
frankly that was an irrelevance to OOP. You can do OOP (and I
have!) in assembler and in COBOL - you just need to follow
some agreed ground rules. It's a lot easier with an OOPL but
it's not required.

> multidimensional thing that's so tangled up that it guarantees that
> people can happily debate for years to come.
Exactly so. During the 90's there came to be at least 3 different
camps of OOP evangelists and the OOP world slowly coalesced on
a kind of hybrid amalgam with multiple names for the same feature
and disagrements about which features are required or not to
really be OOP. And as a result the whole concept of OOP has
been muddied to the point that almost nobody does it anymore
apart from (possibly) the Smalltalk crowd who have always
smugly sat above the general throng content in the knowledge
that theirs is the one true OOP! :-)

Which brings us back to Alan Kay...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Does one have to use curses to read single characters from keyboard?

2022-12-12 Thread Alan Gauld
On 11/12/2022 21:07, dn wrote:
> On 11/12/2022 23.09, Chris Green wrote:
>> Is the only way to read single characters from the keyboard to use
>> curses.cbreak() or curses.raw()?  If so how do I then read characters,
>> it's not at all obvious from the curses documentation as that seems to
>> think I'm using a GUI in some shape or form.
>>
>> All I actually want to do is get 'Y' or 'N' answers to questions on
>> the command line.
>>
>> Searching for ways to do this produces what seem to me rather clumsy
>> ways of doing it.
> 
> You may like to re-ask this question over on the Python-Tutor list. The 
> ListAdmin over there (literally) wrote the book on Python+curses...
> 
> 
> Did such research include the keyboard module?
> https://pypi.org/project/keyboard/
> 
> This project includes an (Enter-free) "hot-key" feature which firstly 
> detects the specific key or key-combination, and then calls an action 
> if/when True.
> (amongst other functionality)
> 
> Quick read tutorial: 
> https://www.thepythoncode.com/article/control-keyboard-python
> 
> Disclaimer: have had it on my 'radar', but never actually employed.
> (if you have considered, will be interested to hear conclusions...)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Does one have to use curses to read single characters from keyboard?

2022-12-13 Thread Alan Gauld
On 12/12/2022 17:45, Alan Gauld wrote:

Absolutely nothing apparently!

But in practce I did pen some esponses to Davids post. However
this list seems to strip out what I've written, its happened
a few times now. Not every time but enough that I rarely post
here.

But I'll try once more...

> On 11/12/2022 21:07, dn wrote:
>> On 11/12/2022 23.09, Chris Green wrote:
>>> Is the only way to read single characters from the keyboard to use
>>> curses.cbreak() or curses.raw()?

>> You may like to re-ask this question over on the Python-Tutor list. The 
>> ListAdmin over there (literally) wrote the book on Python+curses...

Thanks for the plug David, but...

While my book is, I think, the only one specifically for curses with
Python, it's hardly a definitive tome on the subject, rather a
beginner's tutorial. An expanded HowTo if you like..

>> Did such research include the keyboard module?
>> https://pypi.org/project/keyboard/

There are several such modules, including a good one by Fred Lundh.
They are cross platform and probably the best solution for the
OP if he doesn't mind using a third party module. I think Fred's
was called terminal? But its been a while I normally just use curses
for anything terminal related.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: String to Float, without introducing errors

2022-12-17 Thread Alan Gauld
On 17/12/2022 11:51, Paul St George wrote:
> I have a large/long array of numbers in an external file. The numbers look 
> like this:
> 
> -64550.727
> -64511.489
> -64393.637
> -64196.763
> -63920.2

> When I bring the numbers into my code, they are Strings. To use the 
> numbers in my code, I want to change the Strings to Float type 
> because the code will not work with Strings but I do not want 
> to change the numbers in any other way.

That may be impossible. Float type is not exact and the conversion
will be the closest binary representation of your decimal number.
It will be very close but it may be slightly different when you
print it, for example. (You can usually deal with that by using
string formatting features.)

Another option is to use the decimal numeric type. That has other
compromises associated with it but, if retaining absolute decimal
accuracy is your primary goal, it might suit you better.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: NoneType List

2022-12-31 Thread Alan Gauld
On 31/12/2022 05:45, Goran Ikac wrote:

> b = a.append(3)


> I mean: why b = a.append(something) is the None type, and how to make a new
> list that contains all the items from a and some new items?

append() like many other collection methods in Python works
in place and returns None. But the action has succeeded
and 3 will have been appended to list 'a'.

So, to create a new list that contains all the old items you could do:

newlist = []   # an empty list
for item in oldlist:
newlist.append(item)

This is so common Python has a shorthand form to do this:

newlist = [item for item in oldlist]

called a list comprehension.

And there is an even shorter way using something called slicing:

newlist = oldlist[:]# copy oldlist to new.


However, as an ex-Smalltalk programmer, I do wish that Python
returned self from these methods rather than None so that
we could chain them. But sadly it doesn't.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: NoneType List

2023-01-02 Thread Alan Gauld
On 02/01/2023 02:14, avi.e.gr...@gmail.com wrote:
> I used PASCAL before C and I felt like I was wearing a straitjacket at times
> in PASCAL when I was trying to write encryption/decryption functions and had
> to find ways to fiddle with bits. Similar things were easy in C, and are
> even easier in many more recent languages such as Python. 

That's true of pure Pascal. But Thomas was talking about Turbo Pascal
which had extra functions and features for all those "real world" type
things. (And you could insert some inline assembler if all else failed)
It also relaxed the ludicrously strict typing slightly. Turbo Pascal
made Pascal a joy and I still use Delphi for Windows programming today.

TP also introduced classes to Pascal (although Apple had already done
so for the Mac and Borland basically ported the syntax to the PC).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Usenet vs. Mailing-list (was: evaluation question)

2023-01-31 Thread Alan Gauld
On 28/01/2023 21:36, Dennis Lee Bieber wrote:

>   Now -- last time I checked the gmane server says posting is prohibited.
> I used to use gmane as it retrieved directly from the mailing list 

I still use gmane but its no posting thing is a pain because responding
(or posting new stuff) is a now more complicated than before. So
I have to be very highly motivated to jump through the hoops.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-26 Thread Alan Gauld
On 26/02/2023 00:54, Greg Ewing via Python-list wrote:
> On 26/02/23 10:53 am, Paul Rubin wrote:
>> I'm not on either list but the purpose of the tutor list is to shunt
>> beginner questions away from the main list.

I'm not sure that's why we set it up but it is
certainly a large part of our remit. But protecting newbies
from overly complex responses and covering wider topics
(beyond pure Pyhon) is also a large part of our purpose.

> There's a fundamental problem with tutor lists. They rely on
> experienced people, the ones capable of answering the questions,
> to go out of their way to read the tutor list -- something that
> is not of personal benefit to them.

In practice, the "tutors" tend to be split between folks
who inhabit both lists and those who only interact on the tutor
list. eg. I lurk here and only occasionally partake.

But the problem with this particular thread is that, if directed
to the tutor list, the OP would simply be told that "that's the
way Python works". The tutor list is not for discussing
language enhancements etc. It is purely about answering questions
on how to use the language (and standard library) as it exists.
(We also cover beginner questions about programming in general.)

So this thread is most definitely in the right place IMHO.

-- 
Alan G
Tutor list moderator


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


Re: Regular Expression bug?

2023-03-02 Thread Alan Bawden
jose isaias cabrera  writes:

   On Thu, Mar 2, 2023 at 2:38 PM Mats Wichmann  wrote:

   This re is a bit different than the one I am used. So, I am trying to match
   everything after 'pn=':

   import re
   s = "pm=jose pn=2017"
   m0 = r"pn=(.+)"
   r0 = re.compile(m0)
   s0 = r0.match(s)
   >>> print(s0)
   None

Assuming that you were expecting to match "pn=2017", then you probably
don't want the 'match' method.  Read its documentation.  Then read the
documentation for the _other_ methods that a Pattern supports.  Then you
will be enlightened.

- Alan
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which more Pythonic - self.__class__ or type(self)?

2023-03-03 Thread Alan Gauld
On 02/03/2023 20:54, Ian Pilcher wrote:
> Seems like an FAQ, and I've found a few things on StackOverflow that
> discuss the technical differences in edge cases, but I haven't found
> anything that talks about which form is considered to be more Pythonic
> in those situations where there's no functional difference.

I think avoiding dunder methods is generally considered more Pythonic.

But in this specific case using isinstance() is almost always
the better option. Testing for a specific class is likely to break
down in the face of subclasses. And in Python testing for static types
should rarely be necessary since Python uses duck typing
and limiting things to a hard type seriously restricts your code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Python list insert iterators

2023-03-03 Thread Alan Bawden
Guenther Sohler  writes:

   Hi Python community,

   I have a got an example list like

   1, 2, 3, 4, 5, 6, 7, 8, 9, 10
T   T

   and i  eventually want to insert items in the given locations
   (A shall go between 2 and 3,  B shall go between 6 and 7)

   Right now i just use index numbers to define the place:

   A shall insert in position 2
   B shall insert in position 6

   However when i insert A in position 2, the index for successful insertion
   of B gets wrong
   (should now be 7 instead of 6)

   No, it's not an option to sort the indexes and start inserting from the
   back.

If you are definitely inserting from the front, then you can use
negative indexes, since the positions relative to the end of the list
won't be changing.

If you must insert in a random order, that won't help, but you haven't
told us what your real constraints are.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Alan Gauld
On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote:
> 
> Of course each language has commonly used idioms 
> 

That's the point, the correct term is probably "idiomatic"
rather than "pythonic" but it is a defacto standard that
idiomatic Python has become known as Pythonic. I don't
think that's a problem. And at least we aren't in the C++
situation where almost everything that was idiomatic up
until 1999 is now deemed an anti-pattern and they have
standard library modules to try and guide you to use the
"correct" idioms!

But being Pythonic is still a much more loose term and
the community less stressed about it than their C++
cousins where it has almost reached a religious fervour!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Lambda returning tuple question, multi-expression

2023-03-09 Thread Alan Gauld
On 08/03/2023 21:56, aapost wrote:
> When making a UI there are a lot of binding/trace operations that need 
> to occur that lead to a lot of annoying 1 use function definitions. I 
> don't really see lambda use like below.

Lambdas are very common in GUI callbacks but I admit I've never seen
tuples used to create multiple expressions. That's a neat trick I
hadn't thought of and will probably use.

> Giving 2 working lambda examples using a returned tuple to accomplish 
> multiple expressions - what sort of gotchas, if any, might make the 
> following bad practice if I am missing something?

Not bad practice per-se but you are still limited to expressions, no
loops for example (although you could fake it with a list comp,
but that gets ugly fast!)

Also layout is all important here. It could get very messy to read if
indentation isn't clear. You only have to look at some Javascript code
with function definitions as arguments to functions to see how clunky
that can be.

Similarly debugging so much code passed as arguments might be an
issue - no easy way to step into the lambda.

But as an alternative to writing many typical event handlers it's
definitely a valid approach that I'll be trying.

> b = tk.Button(master=main, text="Enable")
> b.config(
>  command=lambda: (
>  e1.config(state="normal"),
>  e2.config(state="normal"),
>  e3.config(state="normal")
>  )
> )

You could of course single line that with:

b = tk.Button(master=main,
  text="Enable",
  command=lambda: (
  e1.config(state="normal"),
  e2.config(state="normal"),
  e3.config(state="normal")
  )
  )

It's not a radical change from using a lamba as a
callback but it does extend the use case to cover
a common GUI scenario.

I like it. I wish I'd thought of it years ago.
Thanks for sharing.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Fwd: Friday finking: IDE 'macro expansions'

2023-03-17 Thread Alan Gauld
Oops! I meant to send this to the group not just Dave.


 Forwarded Message 

On 16/03/2023 22:55, dn via Python-list wrote:

> Do you make use of your IDE's expansionist tendencies, and if-so, which 
> ones?

When I'm writing Java/C++/C# yes, I need all the IDE help I can get.
Netbeans or Eclipse being my tools of choice. And in my Windows days
I used Delphi and Smalltalk/V which both pretty much only exist within
their own IDEs and I used their features extensively.

When writing Python I use IDLE, or vim for bigger jobs.
IDLE does have some suggestions and auto tricks but I don't
always use them. In vim I use auto-indent and that's about it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Fwd: Friday finking: IDE 'macro expansions'

2023-03-18 Thread Alan Gauld
On 17/03/2023 17:55, Thomas Passin wrote:

>> I used Delphi and Smalltalk/V which both pretty much only exist within
>> their own IDEs and I used their features extensively.
> 
> Back when Delphi first came out, when I first used it, I don't remember 
> any IDE; one just used a text editor.

I think you might be meaning TurboPascal, Delphi's forerunner. It just
had a compiler and text editor. But Delphi from day 1 was an IDE
designed to compete with Visual Basic. Everything was geared around the
GUI builder. You could write code outside the IDE but it was orders of
magnitude more difficult.

The Lazarus open source project is based on Delphi's IDE.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Fwd: Friday finking: IDE 'macro expansions'

2023-03-18 Thread Alan Gauld
On 18/03/2023 12:15, Peter J. Holzer wrote:

>> I think you might be meaning TurboPascal, Delphi's forerunner. It just
>> had a compiler and text editor.
> 
> I'd still classify Turbo Pascal as an IDE. It wasn't a standalone
> compiler you would invoke on source files you wrote with some other

It had both (although I'm not sure when that was introduced, the
original didn't). Mostly you used the IDE/editor but there was a
command line compiler that you could run (and a make-like project
tool too in the later versions). I started with TurboPascal on DOS
at Uni generating COM files then later used TP versions 4, 5.5(with
added OOP!) and 6 professionally, creating EXE file DOS programs.

Up until I switched to a Mac, a year ago, I still had TP6 and used
it to maintain some old TurboVision DOS programs.

But I used Delphi from version 1 through to 7(?) for all my Windows
programming and still have version 3 installed (via VirtualBox on
Linux) to keep some old shareware apps of mine running.

I often think there are a lot of similarities between
Delphi/Object Pascal and Python in the OOP area.

> it, see the errors directly in the source code. I think it even had a
> debugger which would also use the same editor window (Turbo C did).

I think the debugger came in v3, but i could be wrong. I don't
recall there being one at uni...

> Turbo Pascal predated GUIs, so it wouldn't have a GUI builder. 

No, it did have a windowing toolkit(TurboVision) but no visual UI
builder. That was the big new feature of Delphi.

> application (i.e. not a learning project) with a traditional desktop GUI
> for 20 years) so the presence or absence of a GUI builder isn't an
> essential criterion on whether something is or is not an IDE.

Indeed, but it was intrinsic to Delphi (even though you could
write non GUI apps too, but they required extra effort.)
Eclipse et al have GUI builders available as extras, in Delphi
(and Lazurus) it is hard to avoid.

BTW Delphi (v11) and the other Borland tools are still going strong,
albeit at extortionately high prices: $1000~3000 for the pro
versions!  (But there is still a free community version with
just the basics.) See http://www.embarcadero.com
And it's targeted at multi-platforms now: Windows, MacOS, Android, iOS
although it only runs on Windows.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Windows installer from python source code without access to source code

2023-03-31 Thread Alan Gauld
On 31/03/2023 13:00, Jim Schwartz wrote:
> I want a windows installer to install my application that's written in
> python, but I don't want the end user to have access to my source code.  

Others have commented that at some level it will always be thre but on a
more pragmatic level tools like py2exe bundle up a Python app as an exe
file which might be all you need?

I'm sure if a user dug deep enough they could still find the source (or
something close) but to deter casual browsing it might be what you want.

Caveat: I've never used py2exe in anger and my experiements were before
Python3 so ive no idea what it does today! But a quick check suggests it
still exists and works with python3 code - last major release was in Nov
2022.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Windows Gui Frontend

2023-04-01 Thread Alan Gauld
On 01/04/2023 18:21, Jim Schwartz wrote:
> Are there any ide’s that will let me design the screen and convert it to 
> python?  

There is nothing remotely like the VB or Delphi GUI builders.
There are some tools somewhat similar to the Java Swing and
FX GUI builders with varying degrees of bugginess.

And there are a few bespoke GUI type tools such as Dabo for
building specific types of applications.

But most Python GUI developers seem to prefer to just hard
code the Python, once you get used to it there's not much
time saving with the GUI tools.

The real time consuming stuff in building GUIs is getting
the basic design right and keeping all the controls,
keyboard bindings and menus in sync. State management
in other words.

I did a deep dive examination of GUI builders back around
v2.6 and came away less than enthused. Things may have
improved since then but I've seen no real evidence of
that.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Weak Type Ability for Python

2023-04-13 Thread Alan Gauld
On 13/04/2023 20:35, Chris Angelico wrote:

> REXX - where everything is a string,

> It was quite the experience back in the day (as OS/2's native
> scripting language), 

I briefly met REXX on a mainframe, but I did play with OS/2 for
a year or two. Back when it looked like it might be a rival to M$

OS/2 running NeXTstep now that would have been a platform
for the 90s...  both so near yet so far.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: Weak Type Ability for Python

2023-04-13 Thread Alan Gauld
On 14/04/2023 00:25, avi.e.gr...@gmail.com wrote:

> Is there any concept in Python of storing information in some way, such as
> text, and implementing various ideas or interfaces so that you can query if
> the contents are willing and able to be viewed in one of many other ways?

Are you talking about something like a C union type (or a Pascal
variant record)? I'm not aware of any such feature in Python but
have often thought it would be a nice to have for the rare cases
where its useful.

> Or it may be storing text in some format but the object is willing to
> transform the text into one of several other formats when needed. The text
> may also have attributes such as whether it is in English or Hungarian or is
> mixed-language.

Or are you meaning something like an extension to the
struct module that can interpret a bytestring in any way
defined by a format string?

> basis. But do some languages have some support within the language itself?

The closest to what you seem to mean is, I think, the C union
type, at least in my experience. But you have to define all
the ways you can interpret the type up front in the type
definition.

> My reason for asking, is based on the discussion. If I want to use plus with
> an integer and a string, it may be reasonable for the interpreter to ask one
> or the other operand if they are able to be seen another way.

You can achieve that in a slightly different way in Tcl which
allows you to redefine all the operators (commands in Tcl-speak)
in the language so redefining plus is easy. Doing it based on
type is more tricky but doable.

> Unfortunately, if they BOTH are flexible, how do you decide whether to add
> them as numbers or concatenate them as strings?

Yes, that's where it becomes a designer's arbitrary choice.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: tksheet - Copy and Paste with headers

2023-04-16 Thread Alan Gauld

> 在 2023/4/15 2:33, angela vales 写道:
>> I have recently created a tkinter app and need the ability to copy and 
> paste data from tksheet table into an Excel file. 

First thanks for drawing my attention to tksheet. I've long
been desiring a decent table widget in tkinter and was on the
verge of trying to create one of my own. tksheet looks like
it will do all I need.

As to copy/paste I couldn't see any explicit mention but
it does say the underlying data is in a Tk Canvas so it may
be that copy/paste will just work, did you try it? What
happened if you paste into a text editor in the first
instance? And Excel in the second?

If all else fails you can probably write handlers and bind
to Ctrl-C and Ctrl-V to do something yourself that mimics
cut/paste.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: PyCharm's strict PEP and not so strict?

2023-04-19 Thread Alan Gauld
On 19/04/2023 10:51, Kevin M. Wilson via Python-list wrote:
>  I'm in a bit of a quandary, I want some strict syntax errors to be flagged,

OK, You might want to use a "linter" in that case because most
tools use the interpreter itself to flag syntax errors.


>  but the use of single quotes vs double quotes! 
> NOT what I need from the 'checker', you dig? 

Not really. What is the problem. Use of single versus double quotes
is straightforward - use one or the other and make sure they
match(opening and closing) You can nest one type inside the
other if you need literal quotes. And of course the same applies
to triple quotes except you can include newlines inside those.

What kind of problems are you experiencing with quotes?
If we have some specific examples we can give specific answers.

> "stones" for bull, how do I set up the kind of "checking" I want?

That's not a phrase with which I'm familiar but my guess
is you need to install a linter tool and then, possibly
configure it to flag or hide particular error/warning types
to your personal taste. Each tool is different so you
will need to read the docs on how to configure it
(and how to plumb it into your IDE).

Personally I've never felt the need for any stricter error
checking than the interpreter provides so I can't offer
anything beyond the generic suggestion to use a linter.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Python curses missing form library?

2023-04-24 Thread Alan Gauld
On 24/04/2023 17:26, Grant Edwards wrote:
> Does the Python curses support in the standard library not include
> support for the curses form library? It seems to include support for
> the panel library, but I can't find any mention of the form library.

I don't believe so. If you are building terminal based form-type
apps the best bet seems to be urwid. I haven't used it in anger
but the beginner docs I saw looked promising.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [pygettext] --package-name and --package-version unknown

2023-05-04 Thread Alan Gauld
On 04/05/2023 22:38, c.bu...@posteo.jp wrote:
> Hello,
> 
> am I right to assume that "pygettext" is part of the official Python3 
> "package"? So it is OK to aks here?
> 

No it doesn't appear to be. It is not listed in the standard library.
It is mentioned in the documentation for gettext which is part of the
standard library.

It does seem to be part of the Python i18n toolkit however.
There are extensive comments in the .py file.

https://github.com/python/cpython/tree/main/Tools/i18n/pygettext.py

> I would like to modify the header that pygettext does create in each 
> po-file.

Sorry, I've never used pygettext so can't help there.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: What to use instead of nntplib?

2023-05-16 Thread Alan Gauld
On 15/05/2023 22:11, Grant Edwards wrote:
> I got a nice warning today from the inews utility I use daily:
> 
> DeprecationWarning: 'nntplib' is deprecated and slated for removal in 
> Python 3.13
> 
> What should I use in place of nntplib?

I'm curious as to why nntplib is deprecated? Surely there are still a
lot of nntp servers around, both inside and outside corporate firewalls?
Is there a problem with the module or is it just perceived as no longer
required?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: What to use instead of nntplib?

2023-05-16 Thread Alan Gauld
On 16/05/2023 10:06, Cameron Simpson wrote:

>> I'm curious as to why nntplib is deprecated? Surely there are still a
>> lot of nntp servers around, both inside and outside corporate firewalls?
>> Is there a problem with the module or is it just perceived as no longer
>> required?
> 
> See PEP 594: https://peps.python.org/pep-0594/

Thanks Cameron.
A scary list; I must have a dozen projects from the late 90s still
live that are using many of these! I'm glad I'm retired and won't
be the one who has to fix 'em :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Silly (maybe) question re imported module(s)

2023-05-19 Thread Alan Gauld
On 19/05/2023 07:44, Grizzy Adams via Python-list wrote:

> when typed in console or editor and run with F5 (which saves before it can 
> run) 
> 
> But sometimes saved work (albeit small) when imported does not work any longer

Looks like you are using IDLE? If so, it's possible that in the original
case you had some values set from a previous run that were picked up but
when you reimport later those values are missing. It would help if you
can post any error messages since they should give clues(like name
errors for example).

Also describe how you are "importing" the modules. are you typing

>>> import mymodule

at the interactive prompt or are you using the File->Open menu
to load them into the editor? (It sounds like the latter)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Silly (maybe) question re imported module(s)

2023-05-19 Thread Alan Gauld
On 19/05/2023 13:36, Grizzy Adams wrote:

>> Looks like you are using IDLE? 
> 
> Yes
> 
> 
> From consol
> 
>>>> import cube
>>>> cubes
> Traceback (most recent call last):
>   File "", line 1, in 
> cubes
> NameError: name 'cubes' is not defined

You imported cube but tried to use cubes. I'm guessing
cubes is defined inside cube so you would need

cube.cubes

> File->Open mymodule.module into the editor, then F5 to run all is well
> 
>>>>
>  RESTART: D:\Shades\Tools\Python\Temp\cube.py 
>>>> cubes
> [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]


cubes looks like it should be a function but in that case there
should be parens after it. So I'm not sure how that is working!

I'd expect that you need to do:

import cube
cube.cubes()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Silly (maybe) question re imported module(s)

2023-05-19 Thread Alan Gauld
On 19/05/2023 19:46, Grizzy Adams wrote:

> Tried that
>  RESTART: D:\Shades\Tools\Python\Temp\cube.py 
>>>> cubes()
> Traceback (most recent call last):
>   File "", line 1, in 
> cubes()
> TypeError: 'list' object is not callable

Ah, now I understand. cubes is a literal list defined in the module.


> But that was spot on, thanks 
> 
>>>> import cube
>>>> cube.cubes
> [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

Glad to help.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Question about generators

2021-03-05 Thread Alan Bawden
   >>>
   >>> s = []
   >>> s.append(((b, c) for b, c in a))
   >>> s
   [ at 0x019FC3F863C0>]
   >>>

   TIA for any insights.

Replace "append" above with "extend" and observe the results.  Then
ponder the difference between append and extend.  I suspect that the
heart of your confusion actually has nothing to do with generators.

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: .title() - annoying mistake

2021-03-20 Thread Alan Bawden
The real reason Python strings support a .title() method is surely
because Unicode supports upper, lower, _and_ title case letters, and
tells you how to map between them.  Consider:

   >>> '\u01f1'.upper()
   '\u01f1'

This is the "DZ" character.

   >>> '\u01f1'.lower()
   '\u01f3'

This is the "dz" character.

   >>> '\u01f1'.title()
   '\u01f2'

This is the "Dz" character.

When you write that code to capitalize your book titles, you should be
calling .title() rather than .upper() if you are doing it right.

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: .title() - annoying mistake

2021-03-20 Thread Alan Bawden
Sibylle Koczian  writes:

   Am 20.03.2021 um 09:34 schrieb Alan Bawden:
   >
   > When you write that code to capitalize your book titles, you should be
   > calling .title() rather than .upper() if you are doing it right.
   >
   But that's exactly what he's doing, with a result which is documented, but
   not really satisfactory.

Sorry, what I wrote was ambiguous.  What I _meant_ was that when you
replace x.title() with my_title(x) , then in the definition of my_title
you will be calling both .lower() and .title() on individual characters,
but you will probably _never_ be calling .upper().

-- 
Alan Bawden
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange disassembly

2021-06-19 Thread Alan Bawden
Chris Angelico  writes:

   >>> sys.version
   '3.10.0b2+ (heads/3.10:33a7a24288, Jun  9 2021, 20:47:39) [GCC 8.3.0]'
   >>> def chk(x):
   ... if not(0 < x < 10): raise Exception
   ...
   >>> dis.dis(chk)
 2   0 LOAD_CONST   1 (0)
 2 LOAD_FAST0 (x)
 4 DUP_TOP
 6 ROT_THREE
 8 COMPARE_OP   0 (<)
10 POP_JUMP_IF_FALSE   11 (to 22)
12 LOAD_CONST   2 (10)
14 COMPARE_OP   0 (<)
16 POP_JUMP_IF_TRUE14 (to 28)
18 LOAD_GLOBAL  0 (Exception)
20 RAISE_VARARGS1
   >>   22 POP_TOP
24 LOAD_GLOBAL  0 (Exception)
26 RAISE_VARARGS1
   >>   28 LOAD_CONST   0 (None)
30 RETURN_VALUE
   >>>

   Why are there two separate bytecode blocks for the "raise Exception"?
   I'd have thought that the double condition would still be evaluated as
   one thing, or at least that the jump destinations for both the
   early-abort and the main evaluation should be the same.

Looks like in 3.8 it compiles more like the way you expected.

I didn't try 3.9, but it looks like a recent change to te compiler.
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Re: sum() vs. loop

2021-10-12 Thread Alan Gauld


On 10/10/2021 09:49, Steve Keller wrote:
> I have found the sum() function to be much slower than to loop over the
> operands myself:
>
> def sum_products(seq1, seq2):
> return sum([a * b for a, b in zip(seq1, seq2)])
>
> def sum_products2(seq1, seq2):
> sum = 0
> for a, b in zip(seq1, seq2):
> sum += a * b
> return sum
>
> In a program I generate about 14 million pairs of sequences of ints each
> of length 15 which need to be summed. The first version with sum() needs
> 44 seconds while the second version runs in 37 seconds.
>
> Can someone explain this difference?

I'm no expert on Python innards but it looks to me like the first
version loops over the length of the list twice, once to generate
the list of products and the second time to add them together.

The pure Python version only loops once because it does the addition
in transit.

Presumably, especially for large numbers, a single python loop
is faster than 2 C loops?

But that's purely my speculation.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


  1   2   3   4   5   6   7   8   9   10   >