Re: "Strong typing vs. strong testing"

2010-09-30 Thread Ian Collins

On 09/30/10 06:38 PM, Lie Ryan wrote:


The /most/ correct version of maximum() function is probably one written
in Haskell as:

maximum :: Integer ->  Integer ->  Integer
maximum a b = if a>  b then a else b

Integer in Haskell has infinite precision (like python's int, only
bounded by memory), but Haskell also have static type checking, so you
can't pass just any arbitrary objects.

But even then, it's still not 100% correct. If you pass a really large
values that exhaust the memory, the maximum() could still produce
unwanted result.

Second problem is that Haskell has Int, the bounded integer, and if you
have a calculation in Int that overflowed in some previous calculation,
then you can still get an incorrect result. In practice, the
type-agnostic language with *mandatory* infinite precision arithmetic
wins in terms of correctness. Any language which only has optional
infinite precision arithmetic can always produce erroneous result.

Anyone can dream of 100% correct program; but anyone who believes they
can write a 100% correct program is just a dreamer. In reality, we don't
usually need 100% correct program; we just need a program that runs
correctly enough most of the times that the 0.001% chance of
producing erroneous result becomes irrelevant.

In summary, in this particular case with maximum() function, static
checking does not help in producing the most correct code; if you need
to ensure the highest correctness, you must use a language with
*mandatory* infinite precision integers.


Or using the new suffix return syntax in C++0x.  Something like

template 
[] maximum( T0 a, T1 b) { return a > b ? a : b; }

Where the return type is deduced at compile time.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread TheFlyingDutchman

> > Yes.  Nonetheless, the maximum() function does exactly what it is intended
> > to do *with the inputs it receives*.  The failure is outside the function;
> > it did the right thing with the data actually passed to it, the problem
> > was a user misunderstanding as to what data were being passed to it.
>
> > So there's a bug -- there's code which does not do what it was intended
> > to do.  However, that bug is in the caller, not in the maximum()
> > function.
>
> > This is an important distinction -- it means we can write a function
> > which performs that function reliably.  Now we just need to figure out
> > how to call it with valid data... :)
>
> We lost some important context somewhere along the line:
>
> > > > in C I can have a function maximum(int a, int b) that will always
> > > > work. Never blow up, and never give an invalid answer. If someone
> > > > tries to call it incorrectly it is a compile error.
>
> Please take note of the second sentence.
>
> One way or another, this claim is plainly false.  The point I was trying
> to make is not so much that the claim is false (someone else was already
> doing that), but that it can be demonstrated to be false without having
> to rely on any run-time input.
>

The second sentence is not disproved by a cast from one datatype to
another (which changes the value) that happens before maximum() is
called.





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


Re: System idle time under Linux

2010-09-30 Thread Lawrence D'Oliveiro
In message , Hugo 
Léveillé wrote:

> Sorry, I am not a linux guy. Did not know it was a text file

That’s why I said to check the proc(5) man page for further details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Paul Rubin
>> > > > in C I can have a function maximum(int a, int b) that will always
>> > > > work. Never blow up, and never give an invalid answer. If someone
>> > > > tries to call it incorrectly it is a compile error.
> The second sentence is not disproved by a cast from one datatype to
> another (which changes the value) that happens before maximum() is called.

int maximum(int a, int b);

int foo() {
  int (*barf)() = maximum;
  return barf(3);
}

This compiles fine for me.  Where is the cast?  Where is the error message?
Are you saying barf(3) doesn't call maximum?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal J. Bourguignon
Ian Collins  writes:

> On 09/30/10 06:38 PM, Lie Ryan wrote:
>>
>> The /most/ correct version of maximum() function is probably one written
>> in Haskell as:
>>
>> maximum :: Integer ->  Integer ->  Integer
>> maximum a b = if a>  b then a else b
>>
>> Integer in Haskell has infinite precision (like python's int, only
>> bounded by memory), but Haskell also have static type checking, so you
>> can't pass just any arbitrary objects.
>>
>> But even then, it's still not 100% correct. If you pass a really large
>> values that exhaust the memory, the maximum() could still produce
>> unwanted result.
>>
>> Second problem is that Haskell has Int, the bounded integer, and if you
>> have a calculation in Int that overflowed in some previous calculation,
>> then you can still get an incorrect result. In practice, the
>> type-agnostic language with *mandatory* infinite precision arithmetic
>> wins in terms of correctness. Any language which only has optional
>> infinite precision arithmetic can always produce erroneous result.
>>
>> Anyone can dream of 100% correct program; but anyone who believes they
>> can write a 100% correct program is just a dreamer. In reality, we don't
>> usually need 100% correct program; we just need a program that runs
>> correctly enough most of the times that the 0.001% chance of
>> producing erroneous result becomes irrelevant.
>>
>> In summary, in this particular case with maximum() function, static
>> checking does not help in producing the most correct code; if you need
>> to ensure the highest correctness, you must use a language with
>> *mandatory* infinite precision integers.
>
> Or using the new suffix return syntax in C++0x.  Something like
>
> template 
> [] maximum( T0 a, T1 b) { return a > b ? a : b; }
>
> Where the return type is deduced at compile time.

Indeed.  This is generic programming.   And it happens that in Lisp (and
I assume in languages such as Python), sinte types are not checked at
compilation time, all the functions you write are always generic
functions.

In particular, the property "arguments are not comparable" is not
something that can be determined at compilation time, since the program
may add a compare method for the given argument at run-time (if the
comparison operator used is a generic function).

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: System idle time under Linux

2010-09-30 Thread Ifrit
Hugo Léveillé heeft het volgende neergekrabbeld:

> 
> Thanks, will take a closer look on that
> 
> But to get me started, how would you get, via python, the info from that

From a unix command prompt use the cat command to view their contents. 
You'll notice that they plain text files with very informative content:

 # cat /proc/stat
cpu  3799492 103198 3546212 82899838 1183162 137849 118698 0 0
cpu0 1071799 22089 1141874 20155255 262512 2714 1704 0 0
cpu1 926425 27349 694583 21016324 302881 2488 4253 0 0
cpu2 938331 29131 736412 2111 202243 123636 104475 0 0
cpu3 862937 24629 973343 20614926 415526 9011 8266 0 0
intr 153564472 28 10 0 0 0 0 0 7 1 3018879 0 0 173 0 0 0 62 55962320 0 0 0 0 
0 9620148 749 0 0 0 0 0 0 0 0 0 0 3136950 4742352 320982 1 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0
ctxt 478141455
btime 1285609820
processes 45111
procs_running 1
procs_blocked 0
softirq 195073836 0 34148873 30536 22265404 4426357 0 55946604 22390786 
370319 55494957

-- 
Ifrit
http://nl.wikipedia.org/wiki/Ifriet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: System idle time under Linux

2010-09-30 Thread Ifrit
Ifrit heeft het volgende neergekrabbeld:

> Hugo Léveillé heeft het volgende neergekrabbeld:
> 
>> 
>> Thanks, will take a closer look on that
>> 
>> But to get me started, how would you get, via python, the info from that
> 
> From a unix command prompt use the cat command to view their contents.
> You'll notice that they plain text files with very informative content:
> 
>  # cat /proc/stat

And the man proc command gives info on the format of the content:

/proc/stat

  kernel/system statistics.  Varies with architecture.  Common 
entries include:

  cpu  3357 0 4313 1362393
 The  amount of time, measured in units of USER_HZ 
(1/100ths of a second on most architectures,
 use sysconf(_SC_CLK_TCK) to obtain the right value), 
that the system spent in user mode,  user
 mode  with  low priority (nice), system mode, and the 
idle task, respectively.  The last value
 should be USER_HZ times the second entry in the uptime 
pseudo-file.

 In Linux 2.6 this line includes three additional 
columns: iowait - time  waiting  for  I/O  to
 complete  (since  2.5.41); irq - time servicing 
interrupts (since 2.6.0-test4); softirq - time
 servicing softirqs (since 2.6.0-test4).

 Since Linux 2.6.11, there is an eighth column, steal - 
stolen time, which is the time spent in
 other operating systems when running in a virtualized 
environment

 Since  Linux 2.6.24, there is a ninth column, guest, 
which is the time spent running a virtual
 CPU for guest operating systems under the control of 
the Linux kernel.

  page 5741 1808
 The number of pages the system paged in and the number 
that were paged out (from disk).

  swap 1 0
 The number of swap pages that have been brought in and 
out.

  intr 1462898
 This line shows counts of interrupts serviced since 
boot time, for each of the possible system
 interrupts.   The first column is the total of all 
interrupts serviced; each subsequent column
 is the total for a particular interrupt.

  disk_io: (2,0):(31,30,5764,1,2) (3,0):...
 (major,disk_idx):(noinfo, read_io_ops, blks_read, 
write_io_ops, blks_written)
 (Linux 2.4 only)

  ctxt 115315
 The number of context switches that the system 
underwent.

  btime 769041601
 boot time, in seconds since the Epoch (January 1, 
1970).

  processes 86031
 Number of forks since boot.

  procs_running 6
 Number of processes in runnable state.  (Linux 2.5.45 
onwards.)

  procs_blocked 2
 Number of processes blocked waiting for I/O to 
complete.  (Linux 2.5.45 onwards.)

-- 
Ifrit
http://nl.wikipedia.org/wiki/Ifriet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread RG
In article 
<5bf24e59-1be0-4d31-9fa7-c03a8bf9b...@y12g2000prb.googlegroups.com>,
 TheFlyingDutchman  wrote:

> > > Yes.  Nonetheless, the maximum() function does exactly what it is intended
> > > to do *with the inputs it receives*.  The failure is outside the function;
> > > it did the right thing with the data actually passed to it, the problem
> > > was a user misunderstanding as to what data were being passed to it.
> >
> > > So there's a bug -- there's code which does not do what it was intended
> > > to do.  However, that bug is in the caller, not in the maximum()
> > > function.
> >
> > > This is an important distinction -- it means we can write a function
> > > which performs that function reliably.  Now we just need to figure out
> > > how to call it with valid data... :)
> >
> > We lost some important context somewhere along the line:
> >
> > > > > in C I can have a function maximum(int a, int b) that will always
> > > > > work. Never blow up, and never give an invalid answer. If someone
> > > > > tries to call it incorrectly it is a compile error.
> >
> > Please take note of the second sentence.
> >
> > One way or another, this claim is plainly false.  The point I was trying
> > to make is not so much that the claim is false (someone else was already
> > doing that), but that it can be demonstrated to be false without having
> > to rely on any run-time input.
> >
> 
> The second sentence is not disproved by a cast from one datatype to
> another (which changes the value) that happens before maximum() is
> called.

You can't have it both ways.  Either I am calling it incorrectly, in 
which case I should get a compiler error, or I am calling it correctly, 
and I should get the right answer.  That I got neither does in fact 
falsify the claim.  The only way out of this is to say that 
maximum(8589934592, 1) returning 1 is in fact "correct", in which case 
we'll just have to agree to disagree.

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


Re: how to get partition information of a hard disk with python

2010-09-30 Thread Anssi Saari
Nobody  writes:

> On Wed, 22 Sep 2010 00:31:04 +0200, Hellmut Weber wrote:
>
>> I'm looking for a possibility to access the partiton inforamtion of a
>> hard disk of my computer from within a python program.
>
> Have you considered parsing /proc/partitions?

One could also just read the partition table directly, it's on the
first sector usually. (Assuming a PC without a GUID partition
table...) The partition table is just 64 bytes at offset 446 into the
sector. In unixlikes you can just open the disk with file.open()...
Then again, unixlikes other than Linux have somewhat different ideas
about partitioning...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread TheFlyingDutchman
On Sep 30, 1:02 am, Paul Rubin  wrote:
> >> > > > in C I can have a function maximum(int a, int b) that will always
> >> > > > work. Never blow up, and never give an invalid answer. If someone
> >> > > > tries to call it incorrectly it is a compile error.
> > The second sentence is not disproved by a cast from one datatype to
> > another (which changes the value) that happens before maximum() is called.
>
>     int maximum(int a, int b);
>
>     int foo() {
>       int (*barf)() = maximum;
>       return barf(3);
>     }
>
> This compiles fine for me.  Where is the cast?  Where is the error message?
> Are you saying barf(3) doesn't call maximum?

With Tiny C on my system, your code does not cause maximum to give an
incorrect value, or to blow up:

int maximum(int a, int b)
{
  printf("entering maximum %d %d\n",a,b);
  if ( a > b )
return a;
  else
return b;
}

int foo()
{
   int (*barf)() = maximum;
   return barf(3);
}

int main (int argc, char *argv[])
{
  printf("maximum is %d\n",foo());
}

- output ---
entering maximum 3 4198400
maximum is 4198400
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Lie Ryan
On 09/30/10 16:09, TheFlyingDutchman wrote:
> 
>>
>> That argument can be made for dynamic language as well. If you write in
>> dynamic language (e.g. python):
>>
>> def maximum(a, b):
>> return a if a > b else b
>>
>> The dynamic language's version of maximum() function is 100% correct --
>> if you passed an uncomparable object, instead of a number, your call of
>> it is incorrect; you just didn't pass the right sort of data. And that's
>> your problem as a caller.
>>
>> In fact, since Python's integer is infinite precision (only bounded by
>> available memory); in practice, Python's version of maximum() has less
>> chance of producing erroneous result.
> 
> "in C I can have a function maximum(int a, int b) that will always
> work. Never blow up, and never give an invalid answer. "
> 
> Dynamic typed languages like Python fail in this case on "Never blows
> up".

How do you define "Never blows up"?

Personally, I'd consider maximum(8589934592, 1) returning 1 as a blow
up, and of the worst kind since it passes silently.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread TheFlyingDutchman
On Sep 30, 1:40 am, RG  wrote:
> In article
> <5bf24e59-1be0-4d31-9fa7-c03a8bf9b...@y12g2000prb.googlegroups.com>,
>
>
>
>
>
>  TheFlyingDutchman  wrote:
> > > > Yes.  Nonetheless, the maximum() function does exactly what it is 
> > > > intended
> > > > to do *with the inputs it receives*.  The failure is outside the 
> > > > function;
> > > > it did the right thing with the data actually passed to it, the problem
> > > > was a user misunderstanding as to what data were being passed to it.
>
> > > > So there's a bug -- there's code which does not do what it was intended
> > > > to do.  However, that bug is in the caller, not in the maximum()
> > > > function.
>
> > > > This is an important distinction -- it means we can write a function
> > > > which performs that function reliably.  Now we just need to figure out
> > > > how to call it with valid data... :)
>
> > > We lost some important context somewhere along the line:
>
> > > > > > in C I can have a function maximum(int a, int b) that will always
> > > > > > work. Never blow up, and never give an invalid answer. If someone
> > > > > > tries to call it incorrectly it is a compile error.
>
> > > Please take note of the second sentence.
>
> > > One way or another, this claim is plainly false.  The point I was trying
> > > to make is not so much that the claim is false (someone else was already
> > > doing that), but that it can be demonstrated to be false without having
> > > to rely on any run-time input.
>
> > The second sentence is not disproved by a cast from one datatype to
> > another (which changes the value) that happens before maximum() is
> > called.
>
> You can't have it both ways.  Either I am calling it incorrectly, in
> which case I should get a compiler error, or I am calling it correctly,
> and I should get the right answer.  That I got neither does in fact
> falsify the claim.  The only way out of this is to say that
> maximum(8589934592, 1) returning 1 is in fact "correct", in which case
> we'll just have to agree to disagree.
>
1) long trying_to_break_maximum = 8589934592;
2) /* compiler adds */
   int created_to_allow_maximum_call = (int) trying_to_break_maximum;
3) maximum(created_to_allow_maximum_call, 1);

I think we have to agree to disagree, because I don't see the lack of
a compiler error at step 2 as a problem with the maximum() function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: utf-8 and ctypes

2010-09-30 Thread Diez B. Roggisch
Brendan Miller  writes:

> 2010/9/29 Lawrence D'Oliveiro :
>> In message , Brendan
>> Miller wrote:
>>
>>> It seems that characters not in the ascii subset of UTF-8 are
>>> discarded by c_char_p during the conversion ...
>>
>> Not a chance.
>>
>>> ... or at least they don't print out when I go to print the string.
>>
>> So it seems there’s a problem on the printing side. What happens when you
>> construct a UTF-8-encoded string directly in Python and try printing it the
>> same way?
>
> Doing this seems to confirm something is broken in ctypes w.r.t. UTF-8...
>
> if I enter:
> str = "日本語のテスト"

What is this? Which encoding is used by your editor to produce this
byte-string?

If you want to be sure you have the right encoding, you need to do this:

 - put a coding: utf-8 (or actually whatever your editor uses) in the
   first or second line
 - use unicode literals. That are the funny little strings with a "u" in
   front of them. They will be *decoded* using the declared encoding.
 - when passing this to C, explicitly *encode* with utf-8 first.

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


install 3.1

2010-09-30 Thread roronron
My python installed but the gui gives me syntax error on any code I type 
or paste in. Newbie needs help.

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


Re: install 3.1

2010-09-30 Thread Chris Rebert
On Thu, Sep 30, 2010 at 2:02 AM, roronron  wrote:
> My python installed but the gui gives me syntax error on any code I type
> or paste in. Newbie needs help.

Post the full, exact text of the error message.
See also: http://www.catb.org/esr/faqs/smart-questions.html

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


Re: System idle time under Linux

2010-09-30 Thread John Pinner
On Sep 29, 7:36 pm, Hugo Léveillé  wrote:
> Good point
>
> One I am looking for, is time since last user mouse or keyboard action.
> So I guess I am looking for the exact same thing a screensaver is
> looking for

The command

who -Hu).


will give you idle time for each logged-in user

( H - print headers; u - list users )

and you could run this command via subprocess, then read and parse its
output.

Alternatively you could parse the same file(s) as who - I think it
reads /var/run/utmp - but that would be a lot more work, as it is a
binary file (run man utmp to see its format, use the struct module to
decode)

Best wishes,

John
--


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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal Costanza

On 30/09/2010 08:09, TheFlyingDutchman wrote:




That argument can be made for dynamic language as well. If you write in
dynamic language (e.g. python):

def maximum(a, b):
 return a if a>  b else b

The dynamic language's version of maximum() function is 100% correct --
if you passed an uncomparable object, instead of a number, your call of
it is incorrect; you just didn't pass the right sort of data. And that's
your problem as a caller.

In fact, since Python's integer is infinite precision (only bounded by
available memory); in practice, Python's version of maximum() has less
chance of producing erroneous result.


"in C I can have a function maximum(int a, int b) that will always
work. Never blow up, and never give an invalid answer. "

Dynamic typed languages like Python fail in this case on "Never blows
up".


They don't "blow up". They may throw an exception, on which you can act. 
You make it sound like a core dump, which it isn't.



Pascal

--
My website: http://p-cos.net
Common Lisp Document Repository: http://cdr.eurolisp.org
Closer to MOP & ContextL: http://common-lisp.net/project/closer/
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Ian Collins

On 09/30/10 09:02 PM, Paul Rubin wrote:


 int maximum(int a, int b);

 int foo() {
   int (*barf)() = maximum;
   return barf(3);
 }

This compiles fine for me.  Where is the cast?  Where is the error message?
Are you saying barf(3) doesn't call maximum?


Try a language with stricter type checking:

CC /tmp/u.c
"/tmp/u.c", line 7: Error: Cannot use int(*)(int,int) to initialize 
int(*)().

"/tmp/u.c", line 8: Error: Too many arguments in call to "int(*)()".

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


Re: how to get partition information of a hard disk with python

2010-09-30 Thread Nobody
On Thu, 30 Sep 2010 11:41:48 +0300, Anssi Saari wrote:

>>> I'm looking for a possibility to access the partiton inforamtion of a
>>> hard disk of my computer from within a python program.
>>
>> Have you considered parsing /proc/partitions?
> 
> One could also just read the partition table directly, it's on the
> first sector usually. (Assuming a PC without a GUID partition
> table...) The partition table is just 64 bytes at offset 446 into the
> sector. In unixlikes you can just open the disk with file.open()...
> Then again, unixlikes other than Linux have somewhat different ideas
> about partitioning...

Apart from the portability issues, you usually need elevated privileges
to read the disk directly, while /proc/partitions is normally readable by
anyone.

OTOH, many of the tasks for which partition information is necessary would
require root privilege anyhow.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread TheFlyingDutchman

>
> > "in C I can have a function maximum(int a, int b) that will always
> > work. Never blow up, and never give an invalid answer. "
>
> > Dynamic typed languages like Python fail in this case on "Never blows
> > up".
>
> How do you define "Never blows up"?

Never has execution halt.

I think a key reason in the big rise in the popularity of interpreted
languages is that when execution halts, they normally give a call
stack and usually a good reason for why things couldn't continue. As
opposed to compiled languages which present you with a blank screen
and force you to - fire up a debugger, or much much worse, look at a
core dump - to try and discern all the information the interpreter
presents to you immediately.

>
> Personally, I'd consider maximum(8589934592, 1) returning 1 as a blow
> up, and of the worst kind since it passes silently.

If I had to choose between "blow up" or "invalid answer" I would pick
"invalid answer".

In this example RG is passing a long literal greater than INT_MAX to a
function that takes an int and the compiler apparently didn't give a
warning about the change in value as it created the cast to an int,
even with the option -Wall (all warnings). I think it's legitmate to
consider that an option for a warning/error on this condition should
be available. As far the compiler generating code that checks for a
change in value at runtime when a number is cast to a smaller data
type, I think that's also a legitimate request for a C compiler option
(in addition to other runtime check options like array subscript out
of bounds).

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


gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Joel Hedlund
I'm having a weird problem with the 'External Tools' plugin for gedit,
that seems to get weirder the more I dig into it. When I start gedit
by clicking a launcher (from the Ubuntu menu, panel or desktop)
everything is dandy and the 'External Tools' plugin works as expected.
When gedit is launched from the terminal, the 'External Tools' plugin
is greyed out in the plugin list and I get this traceback on stderr:

$ gedit
Traceback (most recent call last):
  File "/usr/lib/gedit-2/plugins/externaltools/__init__.py", line 24,
in 
from manager import Manager
  File "/usr/lib/gedit-2/plugins/externaltools/manager.py", line 27,
in 
import hashlib
  File "/usr/lib/python2.6/hashlib.py", line 136, in 
md5 = __get_builtin_constructor('md5')
  File "/usr/lib/python2.6/hashlib.py", line 63, in
__get_builtin_constructor
import _md5
ImportError: No module named _md5

** (gedit:8714): WARNING **: Error loading plugin 'External Tools'

The same thing happens if I try to activate the plugin from a gedit
launched from the terminal (if it's already been deactivated from a
gedit launched from the menu).

My analysis is that gedit tries to import the externaltools package,
which imports hashlib, which tries to import _hashlib but fails and
falls back to _md5 which also fails, which apparently /should not
happen/, or so google tells me. One of _hashlib and _md5 should always
exist.

However, importing _hashlib in a python interpreter works just fine,
i.e:

$ python -c 'import _hashlib'

returns nothing. What also puzzles me is that I don't seem to have
_hashlib* anywhere on my system (am I supposed to?) and getting the
__file__ attribute off the module doesn't work, and help(_hashlib)
says FILE is (built-in).

>>> import _hashlib
>>> _hashlib.__file__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute '__file__'

Google drops vague hints that there may be a a virtualenv that one
might have to rebuild, but in that case I have no idea where to
begin.

I've tried reinstalling the ubuntu packages gedit, gedit-common and
gedit-plugins, but to no avail. And the machine runs a fully updated
ubuntu karmic koala (10.4) that has survived numerous dist-upgrades,
if that's of any use to anybody.

I'd appreciate any input on this, even if it's just new bushes to
whack for scaring the problem out into the light.

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


Re: if the else short form

2010-09-30 Thread Sion Arrowsmith
Andreas Waldenburger   wrote:
>
>[ ... ]
>Boolean values behave like the values 0 and 1, respectively, in
>almost all contexts, the exception being that when converted to a
>string, the strings "False" or "True" are returned, respectively.

Hmm. So the original problem of:

button = gtk.Button(("False,", "True,")[fill==True])

could also rewritten as:

button = gtk.Button(str(bool(fill))+",")

-- 
\S

   under construction

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


will Gnome 3.0 kill pygtk?

2010-09-30 Thread Tracubik
Hi!
It seem that the new version of gnome 3.0 will dismiss pygtk support.

link: 

[1] http://live.gnome.org/TwoPointNinetyone/   (search killing pygtk)

[2] http://live.gnome.org/GnomeGoals/PythonIntrospectionPorting


i'm studying pygtk right now, am i wasting my time considering that my 
preferred platform is linux/gnome?

thanks
Nico

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


Re: if the else short form

2010-09-30 Thread bruno.desthuilli...@gmail.com
On 29 sep, 19:20, Seebs  wrote:
> On 2010-09-29, Tracubik  wrote:
> > button = gtk.Button(("False,", "True,")[fill==True])

> Oh, what a nasty idiom.
>

Well, it's not very different from dict-based dispatch , which is the
core of OO polymorphic dispatch in quite a few dynamic OOPLs.

Anyway, it's a common Python idiom and one that's not specially hard
to grasp so I don't see any legibility problem here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: System idle time under Linux

2010-09-30 Thread Hugo Léveillé

Ok after some testing, what the who -Hu is giving me is the idle time of
each running open shell. The first line always return a "?" as the IDLE
time.

ex:

NAME LINE TIME IDLE  PID COMMENT
vg0619hl :0   2010-09-30 06:10   ? 13091
vg0619hl pts/12010-09-30 06:27 00:11   14084 (:0.0)
vg0619hl pts/22010-09-30 06:54   . 14084 (:0.0)




On Thu, 30 Sep 2010 02:26 -0700, "John Pinner" 
wrote:
> On Sep 29, 7:36 pm, Hugo Léveillé  wrote:
> > Good point
> >
> > One I am looking for, is time since last user mouse or keyboard action.
> > So I guess I am looking for the exact same thing a screensaver is
> > looking for
> 
> The command
> 
> who -Hu).
> 
> 
> will give you idle time for each logged-in user
> 
> ( H - print headers; u - list users )
> 
> and you could run this command via subprocess, then read and parse its
> output.
> 
> Alternatively you could parse the same file(s) as who - I think it
> reads /var/run/utmp - but that would be a lot more work, as it is a
> binary file (run man utmp to see its format, use the struct module to
> decode)
> 
> Best wishes,
> 
> John
> --
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
  Hugo Léveillé
  hu...@fastmail.net

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


sys.setrecursionlimit() and regular expressions

2010-09-30 Thread Santiago Caracol
Hello,

in my program I use recursive functions. A recursion limit of 10 would
be by far sufficient. Yet, I also use some (not very complicated)
regular expressions, which only compile if I set the recursion limit
to 100, or so. This means, of course, an unnecessary loss of speed.

Can I use one recursion limit for my functions and another one for the
re module?

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


Re: PyCObject & malloc creating memory leak

2010-09-30 Thread Tom Conneely
Thanks for your reply, you've given me plenty to think about

On Sep 29, 11:51 pm, Antoine Pitrou  wrote:
>
> > My original plan was to have the data processing and data acquisition
> > functions running in separate processes, with a multiprocessing.Queue
> > for passing the raw data packets. The raw data is read in as a char*,
> > with a non constant length, hence I have allocated memory using
> > PyMem_Malloc and I am returning from the acquisition function a
> > PyCObject containing a pointer to this char* buffer, along with a
> > destructor.
>
> That sounds overkill, and I also wonder how you plan to pass that
> object in a multiprocessing Queue (which relies on objects being
> pickleable). Why don't you simply create a PyString object instead?

Could you elaborate on why you feel this is overkill? Also, your right
about
passing the PyCObjects through a Queue, something which I hadn't
really
considered, so I've switched to using python strings as you
suggested,
an overhead I hoped to avoid but you can't win them all I suppose.

> > So if I call these functions in a loop, e.g. The following will
> > generate ~10GB of data
>
> >     x = MyClass()
> >     for i in xrange(0, 10 * 2**20):
> >         c = x.malloc_buffer()
> >         x.retrieve_buffer(c)
>
> > All my memory disapears, until python crashes with a MemoryError. By
> > placing a print in the destructor function I know it's being called,
> > however it's not actually freeing the memory. So in short, what am I
> > doing wrong?
>
> Python returns memory to the OS by calling free(). Not all OSes
> actually relinquish memory when free() is called; some will simply set
> it aside for the next allocation.
> Another possible (and related) issue is memory fragmentation. Again, it
> depends on the memory allocator.

Yes, I know that's the case but the "freed" memory should be used for
the
next allocation, or atleast at some point before python runs out of
memory.
Anyway, this is besides the point as I've switched to using strings.

Again thanks for taking the time to help me out,
Tom Conneely

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


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Joel Hedlund
bah, I meant to say I'm running "a fully updated ubuntu lucid lynx
(10.4)".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.setrecursionlimit() and regular expressions

2010-09-30 Thread Peter Otten
Santiago Caracol wrote:

> in my program I use recursive functions. A recursion limit of 10 would
> be by far sufficient. Yet, I also use some (not very complicated)
> regular expressions, which only compile if I set the recursion limit
> to 100, or so. This means, of course, an unnecessary loss of speed.

Why do you think so? The recursion limit has no effect on the speed of your 
script. It's just a number that the interpreter checks against.

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



Re: sys.setrecursionlimit() and regular expressions

2010-09-30 Thread Santiago Caracol

> Why do you think so? The recursion limit has no effect on the speed of your
> script. It's just a number that the interpreter checks against.

Yes, sorry. I was just about to explain that. The 'of course' in my
post was silly.

In MY program, the recursion limit is relevant for performance,
because I use constructs of the following kind:

def analyze(sentence):
try:
...
except RuntimeError:
...

I.e. I try to apply certain recursive rules to a sentence. If this
doesn't lead to any results (up to recursion limit N),
then I skip the analysis.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Peter Otten
Joel Hedlund wrote:

> I'm having a weird problem with the 'External Tools' plugin for gedit,
> that seems to get weirder the more I dig into it. When I start gedit
> by clicking a launcher (from the Ubuntu menu, panel or desktop)
> everything is dandy and the 'External Tools' plugin works as expected.
> When gedit is launched from the terminal, the 'External Tools' plugin
> is greyed out in the plugin list and I get this traceback on stderr:
> 
> $ gedit
> Traceback (most recent call last):
>   File "/usr/lib/gedit-2/plugins/externaltools/__init__.py", line 24,
> in 
> from manager import Manager
>   File "/usr/lib/gedit-2/plugins/externaltools/manager.py", line 27,
> in 
> import hashlib
>   File "/usr/lib/python2.6/hashlib.py", line 136, in 
> md5 = __get_builtin_constructor('md5')
>   File "/usr/lib/python2.6/hashlib.py", line 63, in
> __get_builtin_constructor
> import _md5
> ImportError: No module named _md5
> 
> ** (gedit:8714): WARNING **: Error loading plugin 'External Tools'
> 
> The same thing happens if I try to activate the plugin from a gedit
> launched from the terminal (if it's already been deactivated from a
> gedit launched from the menu).
> 
> My analysis is that gedit tries to import the externaltools package,
> which imports hashlib, which tries to import _hashlib but fails and
> falls back to _md5 which also fails, which apparently /should not
> happen/, or so google tells me. One of _hashlib and _md5 should always
> exist.
> 
> However, importing _hashlib in a python interpreter works just fine,
> i.e:
> 
> $ python -c 'import _hashlib'
> 
> returns nothing. What also puzzles me is that I don't seem to have
> _hashlib* anywhere on my system (am I supposed to?) and getting the
> __file__ attribute off the module doesn't work, and help(_hashlib)
> says FILE is (built-in).
> 
 import _hashlib
 _hashlib.__file__
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'module' object has no attribute '__file__'
> 
> Google drops vague hints that there may be a a virtualenv that one
> might have to rebuild, but in that case I have no idea where to
> begin.
> 
> I've tried reinstalling the ubuntu packages gedit, gedit-common and
> gedit-plugins, but to no avail. And the machine runs a fully updated
> ubuntu karmic koala (10.4) that has survived numerous dist-upgrades,
> if that's of any use to anybody.
> 
> I'd appreciate any input on this, even if it's just new bushes to
> whack for scaring the problem out into the light.

You could add

import sys
print sys.executable

at the top of 

/usr/lib/gedit-2/plugins/externaltools/__init__.py

Maybe there's some confusion about what python interpreter should be used.

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


Re: sequence multiplied by -1

2010-09-30 Thread Antoon Pardon
On Sun, Sep 26, 2010 at 03:20:18PM +, Grant Edwards wrote:
> On 2010-09-26, Paul Rubin  wrote:
> > Steven D'Aprano  writes:
> >> There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam", 
> 
> > Why would it not be ["spam","spam","spam"] or even "ssspppaaammm"?
> 
> Because 
> 
> 3 * "spam" == "spam" + "spam" + "spam"
> 
> Just like
> 
> 3 * 6 = 6 + 6 + 6
> 
> So now I suppose "+" for string concatenation is a bad thing.

Well I find it an unfortunate choice. The problem is, that it is not that
unusual to want some class to have the possibility of both addition and
concatenation. But since we only one symbol for both operations, you will
have to loose some consistency over this.

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


PyRTF object model

2010-09-30 Thread Rustom Mody
I am trying to use PyRTF.

I gather that an RTF doc consists of a list of sections, a section
consists of a list of paras,
paras seem to be just text (not sure on that one)

Some questions:

When does one end one section and start another?
How does one handle lists (as in numbered, bulleted etc)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.setrecursionlimit() and regular expressions

2010-09-30 Thread Peter Otten
Santiago Caracol wrote:

> 
>> Why do you think so? The recursion limit has no effect on the speed of
>> your script. It's just a number that the interpreter checks against.
> 
> Yes, sorry. I was just about to explain that. The 'of course' in my
> post was silly.
> 
> In MY program, the recursion limit is relevant for performance,
> because I use constructs of the following kind:
> 
> def analyze(sentence):
> try:
> ...
> except RuntimeError:
> ...
> 
> I.e. I try to apply certain recursive rules to a sentence. If this
> doesn't lead to any results (up to recursion limit N),
> then I skip the analysis.

Here's a depth limitation decorator that you can apply selectively. In the 
example below you can have as many gamma() calls as the interpreter's 
recursion limit permits, but only a total of 10 calls of alpha() and beta().

import random

class TooDeep(Exception):
pass

_limit = 10

def limited(f):
def g(*args, **kw):
global _limit
if not _limit:
raise TooDeep
_limit -= 1
try:
return f(*args, **kw)
finally:
_limit += 1
return g

@limited
def alpha(n):
print "alpha", n
beta(n+1)

@limited
def beta(n):
print "beta", n
gamma(n+1)

def gamma(n):
print "gamma", n
random.choice([alpha, beta, gamma])(n+1)

if __name__ == "__main__":
try:
alpha(0)
except TooDeep as e:
print e

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Nick Keighley
On 27 Sep, 20:29, p...@informatimago.com (Pascal J. Bourguignon)
wrote:
> namekuseijin  writes:



> > Fact is:  almost all user data from the external words comes into
> > programs as strings.  No typesystem or compiler handles this fact all
> > that graceful...
>
> I would even go further.
>
> Types are only part of the story.  You may distinguish between integers
> and floating points, fine.  But what about distinguishing between
> floating points representing lengths and floating points representing
> volumes?  Worse, what about distinguishing and converting floating
> points representing lengths expressed in feets and floating points
> representing lengths expressed in meters.

fair points

> If you start with the mindset of static type checking, you will consider
> that your types are checked and if the types at the interface of two
> modules matches you'll think that everything's ok.  And six months later
> you Mars mission will crash.

do you have any evidence that this is actually so? That people who
program in statically typed languages actually are prone to this "well
it compiles so it must be right" attitude?

> On the other hand, with the dynamic typing mindset, you might even wrap
> your values (of whatever numerical type) in a symbolic expression
> mentionning the unit and perhaps other meta data, so that when the other
> module receives it, it may notice (dynamically) that two values are not
> of the same unit, but if compatible, it could (dynamically) convert into
> the expected unit.  Mission saved!

they *may* do this but do they *actually* do it? My (limited)
experience of dynamically typed languges is everynow and again you
attempt to apply an operator to the wrong type of operand and kerblam!
If your testing is inadaquate then it's inadaquate whatever the
typiness of your language.

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


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Joel Hedlund
How do I catch output to stdout/stderr when launching from a launcher?

I added this to /usr/lib/gedit-2/plugins/externaltools/__init__.py:

import sys
f = open('/tmp/eraseme.txt', 'w')
print >> f, "The executable is %r." % sys.executable
f.close()

In both cases (launcher/termial) the contents of eraseme.txt are:
The executable is '/usr/bin/python'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyCObject & malloc creating memory leak

2010-09-30 Thread Tom Conneely
I'm posting this last message as I've found the source of my initial
memory leak problem, unfortunately it was an embarrassingly basic
mistake. In my defence I've got a horrible cold, but I'm just making
excuses.

I begin by mallocing the memory, which gives me a pointer "foo" to
that memory:
char *foo = PyMem_Malloc(1024 * sizeof(char));

then assign a value to it:
foo = "foo";

of course what this actually does is change the pointer to point to a
new memory address containing a constant "foo". Hence, when I free the
memory in the PYCObject's destructor, the pointer is for the constant
"foo", not the memory I initially allocated.

I only posted this to help people searching, sorry for the noise.

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


Re: toy list processing problem: collect similar terms

2010-09-30 Thread namekuseijin
On 29 set, 11:04, w_a_x_man  wrote:
> On Sep 26, 9:24 am, p...@informatimago.com (Pascal J. Bourguignon)
> wrote:
>
>
>
> > Xah Lee  writes:
> > > here's a interesting toy list processing problem.
>
> > > I have a list of lists, where each sublist is labelled by
> > > a number. I need to collect together the contents of all sublists
> > > sharing
> > > the same label. So if I have the list
>
> > > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > > r) (5 s t))
>
> > > where the first element of each sublist is the label, I need to
> > > produce:
>
> > > output:
> > > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > > a Mathematica solution is here:
> > >http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> > > R5RS Scheme lisp solution:
> > >http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_...
> > > by Sourav Mukherjee
>
> > > also, a Common Lisp solution can be found here:
> > >http://groups.google.com/group/comp.lang.lisp/browse_frm/thread/5d1de...
>
> > It's too complex. Just write:
>
> > (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
> >               (2 o p) (4 q r) (5 s t
>
> >   (mapcar (lambda (class) (reduce (function append) class :key (function 
> > rest)))
> >            (com.informatimago.common-lisp.list:equivalence-classes list 
> > :key (function first)))
>
> >    )
>
> > --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> > --
> > __Pascal Bourguignon__                    http://www.informatimago.com/
>
> Ruby:
>
> [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
> 'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
> [5, 's', 't']].
> group_by{|x| x.first}.values.map{|x| x.map{|y| y[1..-1]}.flatten}
>
>     ==>[["s", "t"], ["a", "b"], ["c", "d", "i", "j"],
>  ["e", "f", "k", "l", "o", "p"],
>  ["g", "h"], ["m", "n", "q", "r"]]

cool, it comes with order all fucked up.  This is something I was
criticized for before, though not all that important to most
functional processing.  Not the case here, though.

here's a scheme version that is hopefully better than the given one:

(define (dig in)

  (if (null? in) '()

(let* ((n (first-of-first in))

   (all-n (filter in (lambda (x)  (eq? n (first x)

   (all-but-n (filter in (lambda (x) (not (eq? n (first
x)))

   (pair

  (fold all-n
 (lambda (i o) (pair (second i) (pair (third i) o

  (dig all-but-n)


; given these aliases to lisp n00bs

(define pair cons)

(define first car)

(define rest cdr)

(define first-of-first caar)

(define second cadr)

(define third caddr)


; and these well-known functions
 (non-tail-recursive for benefit of n00bs)
(define (fold ls f) ; AKA reduce

  (if (null? ls) '()

  (f (first ls) (fold (rest ls) f


(define (filter ls f)

  (fold ls (lambda (i o) (if (f i) (pair i o) o



; testing
(let ((in '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
(2 o p) (4 q r) (5 s t
  (display (dig in))
  (newline))

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Nick Keighley
On 30 Sep, 11:14, TheFlyingDutchman  wrote:
> > > "in C I can have a function maximum(int a, int b) that will always
> > > work. Never blow up, and never give an invalid answer. "
>
> > > Dynamic typed languages like Python fail in this case on "Never blows
> > > up".
>
> > How do you define "Never blows up"?
>
> Never has execution halt.
>
> I think a key reason in the big rise in the popularity of interpreted
> languages is that when execution halts, they normally give a call
> stack and usually a good reason for why things couldn't continue. As
> opposed to compiled languages which present you with a blank screen
> and force you to - fire up a debugger, or much much worse, look at a
> core dump - to try and discern all the information the interpreter
> presents to you immediately.
>
>
>
> > Personally, I'd consider maximum(8589934592, 1) returning 1 as a blow
> > up, and of the worst kind since it passes silently.
>
> If I had to choose between "blow up" or "invalid answer" I would pick
> "invalid answer".

there are some application domains where neither option would be
viewed as a satisfactory error handling strategy. Fly-by-wire, petro-
chemicals, nuclear power generation. Hell you'd expect better than
this from your phone!

> In this example RG is passing a long literal greater than INT_MAX to a
> function that takes an int and the compiler apparently didn't give a
> warning about the change in value as it created the cast to an int,
> even with the option -Wall (all warnings). I think it's legitmate to
> consider that an option for a warning/error on this condition should
> be available. As far the compiler generating code that checks for a
> change in value at runtime when a number is cast to a smaller data
> type, I think that's also a legitimate request for a C compiler option
> (in addition to other runtime check options like array subscript out
> of bounds).

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


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Joel Hedlund
FOUND IT!

I added the line

print >> f, '\n'.join(sorted(sys.path))

and diff:ed the files produced from terminal/launcher.

When using the launcher, changes to PYTHONPATH done in ~/.bashrc are
not picked up, and I apparently had an old reference to /usr/lib/
python2.4 sitting in there. Removed it, reloaded .bashrc, plugin now
works.

The question still remains why gnome disregards ~/.bashrc, but that's
a whole other topic. Thanks a bunch, you guys are ever so helpful.

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


Re: will Gnome 3.0 kill pygtk?

2010-09-30 Thread Neil Hodgson
Tracubik:

> i'm studying pygtk right now, am i wasting my time considering that my 
> preferred platform is linux/gnome?

   I expect the dynamic binding will be very similar to the current
static binding but easier to keep up-to-date. There's already some use
of dynamic binding in the recent PyGTK 2.22.0:

http://www.daa.com.au/pipermail/pygtk/2010-September/019013.html

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


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Joel Hedlund
I guess the moral of the story is don't always dist-upgrade.

Reformat once in a while to remove old forgotten garbage. Clear the
blood clots from your systems, so to say.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: will Gnome 3.0 kill pygtk?

2010-09-30 Thread Diez B. Roggisch
Tracubik  writes:

> Hi!
> It seem that the new version of gnome 3.0 will dismiss pygtk support.
>
> link: 
>
> [1] http://live.gnome.org/TwoPointNinetyone/   (search killing pygtk)
>
> [2] http://live.gnome.org/GnomeGoals/PythonIntrospectionPorting
>
>
> i'm studying pygtk right now, am i wasting my time considering that my 
> preferred platform is linux/gnome?

The important bit is that it will not ditch Python-support.

I can't comment at the actual differences between pygtk and the upcoming
reflection-based approach, but I doubt learning pygtk now is a
waste. First of all, it will be quite a while until pygtk (and gnome
2.x) are really gone.

And even if, the concepts stay the same, so unless pygtk adds an extra
layer of abstraction (which AFAIK it doesn't), your knownledge is still
usable - if not translatable one-to-one.

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


Re: Python becoming orphaned over ssh

2010-09-30 Thread David
On Wed, Sep 29, 2010 at 6:49 PM, John Nagle  wrote:
>   Python's signal handling for multithread and multiprocess programs
> leaves something to be desired.
>

Thanks for the confirmation (that I'm not missing something obvious).

I've reported a bug for this behavior in the Python issue tracker.

In the meanwhile, I've made a workaround function called
"check_call_and_monitor_ppids", that behaves like
subprocess.check_call, except that it regularly checks if the parent
pid "chain" (up to init process) changes during execution, and then
terminates the subprocess and raises an exception.

Actually I tried this before, and it didn't work. But strangely, it
seems to work fine so long as I don't try to print any warning
messages to stderr or stdout from the Python script (though, the
called tool itself may print to stdout or stderr without problems).
Quite peculiar...

Anyway, I hope that one of the Python developers will fix this sometime.

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


Re: PyCObject & malloc creating memory leak

2010-09-30 Thread Antoine Pitrou
On Thu, 30 Sep 2010 04:06:03 -0700 (PDT)
Tom Conneely  wrote:
> Thanks for your reply, you've given me plenty to think about
> 
> On Sep 29, 11:51 pm, Antoine Pitrou  wrote:
> >
> > > My original plan was to have the data processing and data acquisition
> > > functions running in separate processes, with a multiprocessing.Queue
> > > for passing the raw data packets. The raw data is read in as a char*,
> > > with a non constant length, hence I have allocated memory using
> > > PyMem_Malloc and I am returning from the acquisition function a
> > > PyCObject containing a pointer to this char* buffer, along with a
> > > destructor.
> >
> > That sounds overkill, and I also wonder how you plan to pass that
> > object in a multiprocessing Queue (which relies on objects being
> > pickleable). Why don't you simply create a PyString object instead?
> 
> Could you elaborate on why you feel this is overkill? Also, your right
> about
> passing the PyCObjects through a Queue, something which I hadn't
> really
> considered, so I've switched to using python strings as you
> suggested,
> an overhead I hoped to avoid but you can't win them all I suppose.

Well, there should be no overhead. Actually, a string should be cheaper
since:
- the string contents are allocated inline with the PyObject header
- while your PyCObject contents were allocated separately (two
  allocations rather than one)

Regards

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal Bourguignon
TheFlyingDutchman  writes:

> In this example RG is passing a long literal greater than INT_MAX to a
> function that takes an int and the compiler apparently didn't give a
> warning about the change in value as it created the cast to an int,
> even with the option -Wall (all warnings). I think it's legitmate to
> consider that an option for a warning/error on this condition should
> be available. As far the compiler generating code that checks for a
> change in value at runtime when a number is cast to a smaller data
> type, I think that's also a legitimate request for a C compiler option
> (in addition to other runtime check options like array subscript out
> of bounds).

I think that it's a legitimate request, in this age and day, for a C
programmer to require that it be NOT an option to a C compiler not to
give any error for this and similar cases.

(And we should just kill all the programs that don't pass this check,
which I'm afraid would be a big number, which I understand, is the
reason why C compilers don't change).

-- 
__Pascal Bourguignon__
http://www.informatimago.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarification of notation

2010-09-30 Thread Bruce W.

So, this kind of notation would be different:
args[0][2]
verses args[[0][2]]
the latter is multidimensional.  Can you think of example of using this 
type of list?
I  don't know why this had me a bit confused.  I've got to get into 
programming more...  I had done more in the past.

Bruce

Chriebert wrote:

On Wed, Sep 29, 2010 at 7:32 PM, Bruce Whealton
 wrote:
  

Hello all,
I recently started learning python.  I am a bit thrown by a certain
notation that I see.  I was watching a training course on lynda.com and this
notation was not presented.  For lists, when would you use what appears to
be nested lists, like:
[[], [], []]
a list of lists?



Lists are for working with a group of data. Sometimes each datum
happens to itself be a list; thus, one naturally ends up with a
list-of-lists.

Say I have, for each school in my school district, a list of its
students' test scores. I want to compute each school's average score.
So I put all the lists of scores into a nested list. I then iterate
over the nested list, taking the average of each inner list of scores.
(Do the analogous thing at higher and higher levels of aggregation
(e.g. county, state, country) and you naturally get progressively more
nested lists.)

  

Would you, and could you combine a dictionary with a list in this fashion?



Yes, of course:
{'a' : [1,2,3]}
[{'a' : 1}, {'b' : 2}]

Just note that lists can't be dictionary keys due to their mutability.
{[1,2,3] : "one two three"} # ERROR

  

Next, from the documentation I see and this is just an example (this kind of
notation is seen elsewhere in the documentation:

str.count(sub[, start[, end]])
This particular example is from the string methods.



  

I know that it would
suggest that some of the arguments are optional, so perhaps if there are 2
items the first is the sub, and the second is start?  Or did I read that
backwards?



No, you read it exactly correctly. The []s here indicate levels of
optional-ness and have nothing to do with the list datatype.

Basically, if you want to pass an optional argument, you have to have
also specified any less-nested arguments (unless you use keyword
rather than positional arguments).
str.count(a) # sub = a
str.count(a, b) # sub = a, start = b
str.count(a, b, c) # sub = a, start = b, end = c

Usually, it's straightforward left-to-right as you specify more
arguments (doing otherwise requires kludges or black magic). However,
there are rare exceptions, the most common one being range()/xrange():

range(...)
range([start,] stop[, step]) -> list of integers

Thus:
range(a) # stop = a  (*not* start = a, as would be normal)
range(a, b) # start = a, stop = b
range(a, b, c) # start = a, stop = b, step = c

Cheers,
Chris
--
http://blog.rebertia.com

  


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


Re: PyRTF object model

2010-09-30 Thread Eric Brunel
In article ,
 Rustom Mody  wrote:

> I am trying to use PyRTF.
> 
> I gather that an RTF doc consists of a list of sections, a section
> consists of a list of paras,
> paras seem to be just text (not sure on that one)

They also include a style, not only text.

> Some questions:
> 
> When does one end one section and start another?

You don't 'end a section. You just create a new one and append it to 
your document's sections:

my_document = PyRTF.Document()
my_section1 = PyRTF.Section()
my_document.Sections.append(my_section1)
my_section2 = PyRTF.Section()
my_document.Sections.append(my_section2)

> How does one handle lists (as in numbered, bulleted etc)?

Not sure on this one. I've had to do it, but could handle it via regular 
paragraph style properties and insert the bullets or numbers 
explicitely, so I did it just like that. For example, your can create a 
PyRTF.ParagraphPropertySet with the options left_indent to 1133 twips = 
2cm, first_line_indent to -567 twips = -1cm and set a tab at 1cm with 
the option:
tabs=[PyRTF.TabPropertySet(width=567)]
Then you create a PyRTF.ParagraphStyle using this 
PyRTF.ParagraphPropertySet and pass it as the first argument when you 
create your PyRTF.Paragraph. Then, you just insert tour bullet or number 
in the paragraph explicitely, followed by a tab.
There might be a better way to do it.

BTW, as you might have noticed, the documentation for PyRTF is quite 
minimal to say the least, so the only way to figure out what can be done 
is by reading the PyRTF source codeŠ

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


Re: toy list processing problem: collect similar terms

2010-09-30 Thread namekuseijin
On 30 set, 09:35, namekuseijin  wrote:
> On 29 set, 11:04, w_a_x_man  wrote:
>
>
>
> > On Sep 26, 9:24 am, p...@informatimago.com (Pascal J. Bourguignon)
> > wrote:
>
> > > Xah Lee  writes:
> > > > here's a interesting toy list processing problem.
>
> > > > I have a list of lists, where each sublist is labelled by
> > > > a number. I need to collect together the contents of all sublists
> > > > sharing
> > > > the same label. So if I have the list
>
> > > > ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q
> > > > r) (5 s t))
>
> > > > where the first element of each sublist is the label, I need to
> > > > produce:
>
> > > > output:
> > > > ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))
>
> > > > a Mathematica solution is here:
> > > >http://xahlee.org/UnixResource_dir/writ/notations_mma.html
>
> > > > R5RS Scheme lisp solution:
> > > >http://xahlee.org/UnixResource_dir/writ/Sourav_Mukherjee_sourav.work_...
> > > > by Sourav Mukherjee
>
> > > > also, a Common Lisp solution can be found here:
> > > >http://groups.google.com/group/comp.lang.lisp/browse_frm/thread/5d1de...
>
> > > It's too complex. Just write:
>
> > > (let ((list '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
> > >               (2 o p) (4 q r) (5 s t
>
> > >   (mapcar (lambda (class) (reduce (function append) class :key (function 
> > > rest)))
> > >            (com.informatimago.common-lisp.list:equivalence-classes list 
> > > :key (function first)))
>
> > >    )
>
> > > --> ((S T) (Q R M N) (G H) (O P K L E F) (I J C D) (A B))
>
> > > --
> > > __Pascal Bourguignon__                    http://www.informatimago.com/
>
> > Ruby:
>
> > [[0, 'a', 'b'], [1, 'c', 'd'], [2, 'e', 'f'], [3, 'g', 'h'], [1,
> > 'i', 'j'], [2, 'k', 'l'], [4, 'm', 'n'], [2, 'o', 'p'], [4, 'q', 'r'],
> > [5, 's', 't']].
> > group_by{|x| x.first}.values.map{|x| x.map{|y| y[1..-1]}.flatten}
>
> >     ==>[["s", "t"], ["a", "b"], ["c", "d", "i", "j"],
> >  ["e", "f", "k", "l", "o", "p"],
> >  ["g", "h"], ["m", "n", "q", "r"]]
>
> cool, it comes with order all fucked up.  This is something I was
> criticized for before, though not all that important to most
> functional processing.  Not the case here, though.
>
> here's a scheme version that is hopefully better than the given one:

(define (dig in)
  (if (null? in) '()
    (let* ((n         (first-of-first in))
           (all-n     (filter in (lambda (x)      (eq? n (first x)
           (all-but-n (filter in (lambda (x) (not (eq? n (first
x)))
       (pair
          (fold all-n
             (lambda (i o) (pair (second i) (pair (third i) o
          (dig all-but-n)

; given these aliases to lisp n00bs
(define pair cons)
(define first car)
(define rest cdr)
(define first-of-first caar)
(define second cadr)
(define third caddr)

; and these well-known functions (non-tail-recursive for benefit of
n00bs)
(define (fold ls f) ; AKA reduce
  (if (null? ls) '()
      (f (first ls) (fold (rest ls) f
(define (filter ls f)
  (fold ls (lambda (i o) (if (f i) (pair i o) o

; testing
(let ((in '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n)
            (2 o p) (4 q r) (5 s t
  (display (dig in))
  (newline))

;frakkin text editor...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gedit 'External Tools' plugin hashlib weirdness

2010-09-30 Thread Peter Otten
Joel Hedlund wrote:

> FOUND IT!

Heureka!

> I added the line
> 
> print >> f, '\n'.join(sorted(sys.path))
> 
> and diff:ed the files produced from terminal/launcher.
> 
> When using the launcher, changes to PYTHONPATH done in ~/.bashrc are
> not picked up, and I apparently had an old reference to /usr/lib/
> python2.4 sitting in there. Removed it, reloaded .bashrc, plugin now
> works.

I'm surprised that /usr/lib/python2.4 doesn't appear in the traceback.
 
> The question still remains why gnome disregards ~/.bashrc, but that's
> a whole other topic. Thanks a bunch, you guys are ever so helpful.

I think the breakage you've experienced could be the answer.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal Bourguignon
Nick Keighley  writes:

> On 27 Sep, 20:29, p...@informatimago.com (Pascal J. Bourguignon)
> wrote:
>> If you start with the mindset of static type checking, you will consider
>> that your types are checked and if the types at the interface of two
>> modules matches you'll think that everything's ok.  And six months later
>> you Mars mission will crash.
>
> do you have any evidence that this is actually so? That people who
> program in statically typed languages actually are prone to this "well
> it compiles so it must be right" attitude?

Yes, I can witness that it's in the mind set.  

Well, the problem being always the same, the time pressures coming from
the sales people (who can sell products of which the first line of
specifications has not been written yet, much less of code), it's always
a battle to explain that once the code is written, there is still a lot
of time needed to run tests and debug it.  I've even technical managers,
who should know better, expecting that we write bug-free code in the
first place (when we didn't even have a specification to begin with!).


>> On the other hand, with the dynamic typing mindset, you might even wrap
>> your values (of whatever numerical type) in a symbolic expression
>> mentionning the unit and perhaps other meta data, so that when the other
>> module receives it, it may notice (dynamically) that two values are not
>> of the same unit, but if compatible, it could (dynamically) convert into
>> the expected unit.  Mission saved!
>
> they *may* do this but do they *actually* do it? My (limited)
> experience of dynamically typed languges is everynow and again you
> attempt to apply an operator to the wrong type of operand and kerblam!
> If your testing is inadaquate then it's inadaquate whatever the
> typiness of your language.

Unfortunately, a lot of programmers in dynamic programming languages
have been formed with static programming languages bring with them their
old mindset.  Moreover, when the syntax of the newer dynamic programming
languages is explicitely designed similar to an older static programming
language,  in order to attract these programmers toward the better
technologies, this does not help changing the mindset either.

Unfortunately, you can write FORTRAN code in any programming language.

But my point is that at least with dynamic programming languages,
there's an alternative mindset and it is easier to implement such
a scheme than with static programming languages.

In Lisp, which stresses the symbolic computing part (S-expr are Symbolic
Expressions), it is almost trivial to implement.


-- 
__Pascal Bourguignon__
http://www.informatimago.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sequence multiplied by -1

2010-09-30 Thread Emile van Sebille

On 9/30/2010 5:10 AM Antoon Pardon said...

On Sun, Sep 26, 2010 at 03:20:18PM +, Grant Edwards wrote:

On 2010-09-26, Paul Rubin  wrote:

Steven D'Aprano  writes:

There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam",



Why would it not be ["spam","spam","spam"] or even "ssspppaaammm"?


Because

3 * "spam" == "spam" + "spam" + "spam"

Just like

3 * 6 = 6 + 6 + 6

So now I suppose "+" for string concatenation is a bad thing.


Well I find it an unfortunate choice. The problem is, that it is not that
unusual to want some class to have the possibility of both addition and
concatenation. But since we only one symbol for both operations, you will
have to loose some consistency over this.



Which is actually a good thing for a class that wants to have both 
concatenation and addition -- which would it do with only one symbol?


Emile

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


Re: Python becoming orphaned over ssh

2010-09-30 Thread Jean-Paul Calderone
On Sep 30, 9:08 am, David  wrote:
> On Wed, Sep 29, 2010 at 6:49 PM, John Nagle  wrote:
> >   Python's signal handling for multithread and multiprocess programs
> > leaves something to be desired.
>
> Thanks for the confirmation (that I'm not missing something obvious).
>
> I've reported a bug for this behavior in the Python issue tracker.
>
> In the meanwhile, I've made a workaround function called
> "check_call_and_monitor_ppids", that behaves like
> subprocess.check_call, except that it regularly checks if the parent
> pid "chain" (up to init process) changes during execution, and then
> terminates the subprocess and raises an exception.
>
> Actually I tried this before, and it didn't work. But strangely, it
> seems to work fine so long as I don't try to print any warning
> messages to stderr or stdout from the Python script (though, the
> called tool itself may print to stdout or stderr without problems).
> Quite peculiar...
>
> Anyway, I hope that one of the Python developers will fix this sometime.
>
> David.

Python ignores SIGPIPE by default.  The default SIGPIPE behavior is to
exit.  This is sort of what people on POSIX expect.  If you're talking
to another process over a pipe and that process goes away, and then
you write to the pipe, you get a SIGPIPE and you exit (of course, if
it takes you 20 minutes before you do another write, then it's 20
minutes before you exit).

But with SIGPIPE ignored, a Python process won't do exactly this.
Instead, you'll get an exception from the write.  If you don't handle
the exception, then it'll propagate to the top-level and you'll exit.
Just like with a "normal" process.  Except you also get the option to
doing something other than exiting.  Pretty nice.

But signal dispositions are inherited by child processes.  So you run
ping from your short Python program, and it inherits SIGPIPE being
ignored.  And it's written in C, not Python, so when it writes to the
pipe, there's no exception.  So ping never gets any indication that it
should exit.  No Python writes ever happen in this scenario.  The SSH
supplied stdout is shared with the ping process, which writes to it
directly.

You can fix this by resetting the signal disposition of SIGPIPE for
the ping process:

#!/usr/bin/python
import signal

def reset():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)

from subprocess import check_call
check_call(['ping', 'www.google.com'], preexec_fn=reset)

Very likely the subprocess module should be resetting the disposition
of signals that Python itself has fiddled with (and resetting any
other unusual state that the child is going to inherit, but nothing
else comes immediately to mind).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-09-30 Thread Emile van Sebille

On 9/30/2010 3:21 AM Sion Arrowsmith said...

Andreas Waldenburger  wrote:


[ ... ]
Boolean values behave like the values 0 and 1, respectively, in
almost all contexts, the exception being that when converted to a
string, the strings "False" or "True" are returned, respectively.


Hmm. So the original problem of:

button = gtk.Button(("False,", "True,")[fill==True])

could also rewritten as:

button = gtk.Button(str(bool(fill))+",")



I think I'd prefer

button = gtk.Button("%s," % bool(fill))

Emile




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


Re: Determine sockets in use by python

2010-09-30 Thread Jean-Paul Calderone
On Sep 29, 4:08 pm, Jim Mellander  wrote:
>
> On Wed, Sep 29, 2010 at 11:05 AM, Gary Herron  wrote:
> > On 09/29/2010 09:50 AM, Jim Mellander wrote:
>
> >> Hi:
>
> >> I'm a newbie to python, although not to programming.  Briefly, I am
> >> using a binding to an external library used for communication in a
> >> client-server context, with the server in python.  Typically, I would
> >> set this up with event callbacks, and then enter a select loop, which,
> >> most the time idles and processes input events when the socket shows
> >> activity, kinda like:
>
> >> while True:
> >>     socket.select((my_socket),(),())
> >>     process_event()
>
> >> Unfortunately, the API does not expose the socket to the script level,
> >> and the developer recommends a busy loop:
>
> >> while True:
> >>     sleep(1)
> >>     process_event()
>
> >> which I hope to avoid, for many reasons.  If the socket can be exposed
> >> to the script level, then the problem would be solved.
>
> >> Failing that, it would be nice to be able to pythonically determine
> >> the sockets in use and select on those.  Does anyone have any
> >> suggestions on how to proceed?
>
> >> Thanks in advance
>
> > It's certain that any answer to this will depend on which operating system
> > you are using.  So do tell: What OS?
>
> Hi Gary:
>
> Certainly not windows  I'm developing on OS/X but for production
> probably Linux and FreeBSD
>
> (I'm hoping for something a bit more portable than running 'lsof' and
> parsing the output, but appreciate any/all advice)
>

Linux has /proc/self/fd and OS X has /dev/fd.  Those both suppose you
have some way of determining which file descriptor corresponds to the
socket or sockets that the library is using, of course.  Vastly better
would be to convince the author to expose that information via a real
API.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread TheFlyingDutchman

>
> > If I had to choose between "blow up" or "invalid answer" I would pick
> > "invalid answer".
>
> there are some application domains where neither option would be
> viewed as a satisfactory error handling strategy. Fly-by-wire, petro-
> chemicals, nuclear power generation. Hell you'd expect better than
> this from your phone!
>

I wasn't speaking generally, just in the case of which of only two
choices RG's code should be referred to - "blowing up" or "giving an
invalid answer".

I think error handling in personal computer and website software has
improved over the years but there is still some room for improvement
as you will still get error messages that don't tell you something you
can relay to tech support more than that an error occurred or that
some operation can't be performed.

But I worked with programmers doing in-house software who were
incredibly turned off by exception handling in C++. I thought that
meant that they preferred to return and check error codes from
functions as they had done in C, and for some of them it did seem to
mean that. But for others it seemed that they didn't want to
anticipate errors at all ("that file is always gonna be there!"). I
read a Java book by Deitel and Deitel and they pointed out what might
have lead to that attitude - the homework and test solutions in
college usually didn't require much if any error handling - the
student could assume files were present, data was all there and in the
format expected, user input was valid and complete, etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


eval string

2010-09-30 Thread Brandon Harris
 Needing to pass a string command into a third party program and having 
issues creating a string to do what I need.


here's what I have so far.

eval('import sys; 
sys.stderr.write(\'\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\n\n\n\');')


Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
sys.stderr.write('
 ^
SyntaxError: EOL while scanning string literal


so I've changed it up every way I can think and I get other errors.

eval('import sys; 
sys.stderr.write("\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted!!!\n\n\n");')


Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
import sys; sys.stderr.write("
 ^
SyntaxError: invalid syntax


Brandon L. Harris

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


Re: Clarification of notation

2010-09-30 Thread Dave Angel



On 2:59 PM, Bruce W. wrote:

So, this kind of notation would be different:
args[0][2]
verses args[[0][2]]
the latter is multidimensional.  Can you think of example of using 
this type of list?
I  don't know why this had me a bit confused.  I've got to get into 
programming more...  I had done more in the past.

Bruce



The data in a multidimensional list (list of lists) would look like:

[ [3,5], [4,2,99] ]

But a reference to it would be
args[1][2]

DaveA

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


Re: eval string

2010-09-30 Thread Peter Otten
Brandon Harris wrote:

>   Needing to pass a string command into a third party program and having
> issues creating a string to do what I need.
> 
> here's what I have so far.
> 
> eval('import sys;
> sys.stderr.write(\'\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!
\nCompleted!!!\nCompleted!!!\nCompleted!!!\n\n\n\');')
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "", line 1
>  sys.stderr.write('
>   ^
> SyntaxError: EOL while scanning string literal
> 
> 
> so I've changed it up every way I can think and I get other errors.
> 
> eval('import sys;
> sys.stderr.write("\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!
\nCompleted!!!\nCompleted!!!\nCompleted!!!\n\n\n");')
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "", line 1
>  import sys; sys.stderr.write("
>   ^
> SyntaxError: invalid syntax
> 
> 
> Brandon L. Harris

Python discriminates between statements and expressions. eval() can only 
deal with expressions, but 'import whatever' is a statement. Try 

exec 'import sys\nsys.stderr.write("completed!\n")' 

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


Re: eval string

2010-09-30 Thread Thomas Jollans
On Thursday 30 September 2010, it occurred to Brandon Harris to exclaim:
>   Needing to pass a string command into a third party program and having
> issues creating a string to do what I need.
> 
> here's what I have so far.
> 
> eval('import sys;
> sys.stderr.write(\'\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!\nComplete
> d!!!\nCompleted!!!\nCompleted!!!\n\n\n\');')
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "", line 1
>  sys.stderr.write('

Neither ' nor " can delimit a multiline string literal. You need triplets.

>   ^
> SyntaxError: EOL while scanning string literal
> 
> 
> so I've changed it up every way I can think and I get other errors.
> 
> eval('import sys;
> sys.stderr.write("\n\n\nCompleted!!!\nCompleted!!!\nCompleted!!!\nCompleted
> !!!\nCompleted!!!\nCompleted!!!\n\n\n");')
> 
> Traceback (most recent call last):
>File "", line 1, in 
>File "", line 1
>  import sys; sys.stderr.write("
>   ^
> SyntaxError: invalid syntax
> 
> 
> Brandon L. Harris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Nick Keighley
On 30 Sep, 15:24, TheFlyingDutchman  wrote:
> > > If I had to choose between "blow up" or "invalid answer" I would pick
> > > "invalid answer".
>
> > there are some application domains where neither option would be
> > viewed as a satisfactory error handling strategy. Fly-by-wire, petro-
> > chemicals, nuclear power generation. Hell you'd expect better than
> > this from your phone!
>
> I wasn't speaking generally, just in the case of which of only two
> choices RG's code should be referred to - "blowing up" or "giving an
> invalid answer".

I think I'd prefer termination if those were my only choices. What's
the rest of the program going to do with the wrong result? When the
program finally gives up the cause is lost in the mists of time, and
those are hard to debug!

> I think error handling in personal computer and website software has
> improved over the years but there is still some room for improvement
> as you will still get error messages that don't tell you something you
> can relay to tech support more than that an error occurred or that
> some operation can't be performed.
>
> But I worked with programmers doing in-house software who were
> incredibly turned off by exception handling in C++. I thought that
> meant that they preferred to return and check error codes from
> functions as they had done in C, and for some of them it did seem to
> mean that. But for others it seemed that they didn't want to
> anticipate errors at all ("that file is always gonna be there!").

that was one of the reasons I liked exceptions. If my library threw an
exception then the caller *had* to do something about it. Even to
ignore it he had to write some code.

> I
> read a Java book by Deitel and Deitel and they pointed out what might
> have lead to that attitude - the homework and test solutions in
> college usually didn't require much if any error handling - the
> student could assume files were present, data was all there and in the
> format expected, user input was valid and complete, etc.

plausible. Going from beginner to  I probably steadily
increased the pessimism of my code. The file might not be there. That
other team might send us syntactically invalid commands. Even if it
can't go wrong it will go wrong. Fortunately my collage stuff included
some OS kernal stuff. There anything that can go wrong will go wrong.

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


Re: eval string

2010-09-30 Thread Peter Otten
Peter Otten wrote:

> exec 'import sys\nsys.stderr.write("completed!\n")'

Oops, you need to escape the backslashes for newlines inside quotes inside 
quotes:

>>> exec 'import sys\nsys.stderr.write("completed!\\n")'
completed!

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Tim Bradshaw

On 2010-09-30 13:36:17 +0100, Nick Keighley said:


there are some application domains where neither option would be
viewed as a satisfactory error handling strategy. Fly-by-wire, petro-
chemicals, nuclear power generation. Hell you'd expect better than
this from your phone!


People always give these kind of scenarios, but actually there are far 
more mundane ones.  In my day job I'm a sysadmin and I spend a bunch of 
time writing code (typically what would nowadays be called "scripts" 
rather than programs, but there's no real difference) which does things 
of the form


for every machine in 
do 

where  is fairly often "modify critical system configuration file".

Programs like that have some absolute, non-negotiable requirements:
- they must never fail silently;
- they must check everything they do however unlikely it seems that it 
would failm
 because they will come across systems which have almost arbitrary 
misconfiguration.

- they should be idempotent if possible;
- if they come across something odd they either need to handle it,
 or put things back the way they were and back out;
- if they absolutely can not put things back, they need to report this 
very clearly
 and carefully preserve any detriitus in such a way that a human can 
pick up the bits;
- whatever they do they need to report in a completely parsable way 
what happened

 (success, failure, already done, backed out, not backed out, and so on).

These are quite mundane everyday things, but the consequences of 
getting them wrong can be quite nasty (the worst ones being "the 
machines will still run, but won't boot").


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


Re: PyRTF object model

2010-09-30 Thread David Robinow
On Thu, Sep 30, 2010 at 8:14 AM, Rustom Mody  wrote:
> I am trying to use PyRTF.
>
> I gather that an RTF doc consists of a list of sections, a section
> consists of a list of paras,
> paras seem to be just text (not sure on that one)
>
> Some questions:
>
> When does one end one section and start another?
> How does one handle lists (as in numbered, bulleted etc)?
 You might find the RTF specification helpful.  One source is:
http://msdn.microsoft.com/en-us/library/aa140277%28office.10%29.aspx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Keith Thompson
RG  writes:
[...]
> You can't have it both ways.  Either I am calling it incorrectly, in 
> which case I should get a compiler error, or I am calling it correctly, 
> and I should get the right answer.  That I got neither does in fact 
> falsify the claim.  The only way out of this is to say that 
> maximum(8589934592, 1) returning 1 is in fact "correct", in which case 
> we'll just have to agree to disagree.

You are calling maximum() incorrectly, but you are doing so in a way
that the compiler is not required to diagnose.

If you want to say that the fact that the compiler is not required
to diagnose the error is a flaw in the C language, I won't
argue with you.  It's just not a flaw in the maximum() function.

If I write:

const double pi = 22.0/7.0;
printf("pi = %f\n", pi);

then I suppose I'm calling printf() incorrectly, but I wouldn't
expect my compiler to warn me about it.

If you're arguing that

int maximum(int a, int b) { return a > b ? a : b; }

is flawed because it's too easy to call it incorrectly, you're
effectively arguing that it's not possible to write correct
code in C at all.

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Problems with wsgi Python3

2010-09-30 Thread hidura
Hello list, i had seriously troubles with the connection between a form and  
the wsgi, i' ve made an application on Python3 and was running perfectly  
but when i try to use the  to pass the data this can't be see on the  
server, so what is your recommendation?, i am open to all the ideas less  
leave to Python2 i can't all the project was write on Python3, i was  
looking into the PEP 444 proposal too.


Here is the code what i used to take the data:

print(urllib.parse.parse_qs(environ['wsgi.input'].read(int(environ['CONTENT_LENGTH'])).decode()))

and here it's what the os.environ.item() prints to me:

('LESSOPEN', '|/usr/bin/lesspipe.sh %s')
('SSH_CLIENT', '190.94.122.180 38415 22')
('CVS_RSH', 'ssh')
('LOGNAME', 'hidura')
('INPUTRC', '/etc/inputrc')
('HOME', '/home/hidura')
('PATH', 
'/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/opt/dell/srvadmin/bin:/home/hidura/bin')
('LD_LIBRARY_PATH', '/home/hidura/webapps/karinapp/apache2/lib')
('LANG', 'en_US.UTF-8')
('TERM', 'xterm')
('SHELL', '/bin/bash')
('SHLVL', '3')
('G_BROKEN_FILENAMES', '1')
('HISTSIZE', '1000')
('_', '/home/hidura/webapps/karinapp/apache2/bin/httpd.worker')
('SSH_CONNECTION', '190.94.122.180 38415 174.121.79.178 22')
('SSH_TTY', '/dev/pts/5')
('HOSTNAME', 'web152.webfaction.com')
('PWD', '/home/hidura')
('MAIL', '/var/spool/mail/hidura')
('LS_COLORS', 
'no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:')
-110550484811701713451664404475--\r
Thanks, i am desperate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems with wsgi Python3

2010-09-30 Thread Diez B. Roggisch
hid...@gmail.com writes:

> Hello list, i had seriously troubles with the connection between a form and 
> the
> wsgi, i' ve made an application on Python3 and was running perfectly but when 
> i
> try to use the  to pass the data this can't be see on the server, so 
> what
> is your recommendation?, i am open to all the ideas less leave to Python2 i
> can't all the project was write on Python3, i was looking into the PEP 444
> proposal too.
>
> Here is the code what i used to take the data:
>
> print(urllib.parse.parse_qs(environ['wsgi.input'].read(int(environ
> ['CONTENT_LENGTH'])).decode()))

What is the ouptut of this? What does

import pprint 
pprint.pprint(environ)

give you?


>
> and here it's what the os.environ.item() prints to me:

That's irrelevant. The WSGI-environ is what is needed.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, TheFlyingDutchman  wrote:
> even with the option -Wall (all warnings).

For various historical reasons, "-Wall" has the semantics you might
expect from an option named "-Wsome-common-warnings-but-not-others".

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, RG  wrote:
> We lost some important context somewhere along the line:

>> > > in C I can have a function maximum(int a, int b) that will always
>> > > work. Never blow up, and never give an invalid answer. If someone
>> > > tries to call it incorrectly it is a compile error.

> Please take note of the second sentence.

I did.  That is entirely correct.

> One way or another, this claim is plainly false.  The point I was trying 
> to make is not so much that the claim is false (someone else was already 
> doing that), but that it can be demonstrated to be false without having 
> to rely on any run-time input.

It is not at all obvious to me that it is, in fact, false.  So far as
I can tell, *if* the function is successfully called, then it will take
two integers, compare them, and return the larger one.  It will never
return something which is not an integer.  It will never raise an exception.
It will never return a value which, if you try to treat it as an integer,
raise an exception.

Now, if you pass the wrong values to it, you will get wrong answers -- but
that's your problem for passing it wrong values.

I would understand an "invalid" answer to be one of the wrong category.  For
instance, if I have a function in Python that I expect to return a string,
and it returns None, I have gotten an answer that is "invalid" -- it's not
a string.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, Paul Rubin  wrote:
> int maximum(int a, int b);
>
> int foo() {
>   int (*barf)() = maximum;
>   return barf(3);
> }

> This compiles fine for me.  Where is the cast?

On the first line of code inside foo().

> Where is the error message?

You chose to use a form that suppresses the error message.

> Are you saying barf(3) doesn't call maximum?

I would say that it is undefined whether or not it calls maximum, because
you called a function through a function pointer of a different sort,
which invoked undefined behavior.

There exist real compiles on which code much like this will coredump
without ever once trying to jump to the address of the maximum function,
because the compiler caught your error.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, RG  wrote:
> You can't have it both ways.  Either I am calling it incorrectly, in 
> which case I should get a compiler error,

You get a warning if you ask for it.  If you choose to run without all
the type checking on, that's your problem.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, Pascal Bourguignon  wrote:
> Nick Keighley  writes:
>> do you have any evidence that this is actually so? That people who
>> program in statically typed languages actually are prone to this "well
>> it compiles so it must be right" attitude?

> Yes, I can witness that it's in the mind set.  

Huh.

So here I am, programming in statically typed languages, and I have never
in my life thought that things which compiled were necessarily right.  Not
even when I was an arrogant teenager.

I guess I don't exist.  *sob*

> Well, the problem being always the same, the time pressures coming from
> the sales people (who can sell products of which the first line of
> specifications has not been written yet, much less of code), it's always
> a battle to explain that once the code is written, there is still a lot
> of time needed to run tests and debug it.

At $dayjob, they give us months between feature complete and shipping,
because they expect us to spend a lot of time testing, debugging, and
cleaning up.  But during that time we are explicitly not adding features...

> But my point is that at least with dynamic programming languages,
> there's an alternative mindset and it is easier to implement such
> a scheme than with static programming languages.

I think this grossly oversimplifies things.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread RG
In article ,
 Keith Thompson  wrote:

> RG  writes:
> [...]
> > You can't have it both ways.  Either I am calling it incorrectly, in 
> > which case I should get a compiler error, or I am calling it correctly, 
> > and I should get the right answer.  That I got neither does in fact 
> > falsify the claim.  The only way out of this is to say that 
> > maximum(8589934592, 1) returning 1 is in fact "correct", in which case 
> > we'll just have to agree to disagree.
> 
> You are calling maximum() incorrectly, but you are doing so in a way
> that the compiler is not required to diagnose.

Yes.  I know.  That was my whole point.  There are ways to call a 
function incorrectly (more broadly, there are errors in code) that a C 
compiler is not required to diagnose.

> If you want to say that the fact that the compiler is not required
> to diagnose the error is a flaw in the C language, I won't
> argue with you.

I'm not even saying it's a flaw in the language.  All I'm saying is that 
the original claim -- that any error in a C program will be caught by 
the compiler -- is false, and more specifically, that it can be 
demonstrated to be false without appeal to unknown run-time input.

As an aside, this particular error *could* be caught (and in fact would 
be caught by other tools like lint), but there are errors that can not 
be caught by any static analysis, and that therefore one should not be 
lulled into a false sense of security by the fact that your code is 
written in a statically typed language and compiled without errors or 
warnings.  That's all.

> If I write:
> 
> const double pi = 22.0/7.0;
> printf("pi = %f\n", pi);
> 
> then I suppose I'm calling printf() incorrectly, but I wouldn't
> expect my compiler to warn me about it.
> 
> If you're arguing that
> 
> int maximum(int a, int b) { return a > b ? a : b; }
> 
> is flawed because it's too easy to call it incorrectly, you're
> effectively arguing that it's not possible to write correct
> code in C at all.

I would say that it is very, very hard to write correct code in C for 
any non-vacuous definition of "correct".  That is the reason that core 
dumps and buffer overflows are so ubiquitous.  I prefer Lisp or Python, 
where core dumps and buffer overflows are virtually nonexistent.  One 
does get the occasional run-time error that might have been caught at 
compile time, but I much prefer that to a core dump or a security hole.

One might hypothesize that the best of both worlds would be a dynamic 
language with a static analyzer layered on top.  Such a thing does not 
exist.  It makes an instructive exercise to try to figure out why.  (For 
the record, I don't know the answer, but I've learned a lot through the 
process of pondering this conundrum.)

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Peter Keller
In comp.lang.lisp TheFlyingDutchman  wrote:
> 
>>
>> More specifically, the claim made above:
>>
>> > in C I can have a function maximum(int a, int b) that will always
>> > work. Never blow up, and never give an invalid answer.
>>
>> is false. ?And it is not necessary to invoke the vagaries of run-time
>> input to demonstrate that it is false.
>>
> I don't think you demonstrated it is false. Any values larger than an
> int get truncated before they ever get to maximum. The problem does
> not lie with the maximum function. It correctly returns the maximum of
> whatever two integers it is provided. Calling it with values that are
> larger than an int, that get converted to an int _before_ maximum is
> called, is an issue outside of maximum.

After thinking for a bit. I believe I can demonstrate a situation
where indeed maximum could return the wrong answer and it isn't due to
being passed incorrect input.

If, in maximum, after the entrance to the function call but right
before the comparison, a signal handler gets invoked, walks the stack,
swaps the two values for a and b, and returns back into maximum. Then
maximum will do the wrong thing.  Since control flow was always in
a subgraph of the control flow graph through maximum, this would
classify as a failure given your strict view. (As an aside, one can
do the same thing with a debugger.)

Blocking the signals around the comparison and assignment of the
result to a temporary variable that you will return won't fix it.
This is because (in C) you must have a sequence point after the
unblocking of the signals and before the assignment of a temporary
variable holding the result to the return register, where, in fact,
another signal could arrive and again corrupt the results. Depending
upon the optimzation values of the compiler, it may or may not adjust
the ordering semantics of the assignment to the return register in
relation to the call to unblock the signals. The assignment of a
result to a return register is not defined to be something in C,
and can happen anywhere. But the C statements you used to write it
must adhere to sequence evaluation.

Since the signal handler could do anything, including completely
replacing the text segments and/r loaded libraries of the code or
move the PC to an arbitrary palce, I don't think you can "fix" this
problem. Ever.

If you think this is a pedantic case which never happens in practice,
I'm the maintainer of a well-known user space checkpointing system
where these types of problems have to be thought about deeply because
they happen.

In addition, there are other modes of error injection: in compute
clusters with very high density memory that is not ECC, you can
actually calculate the probability that a bit will flip at an address
in memory due to cosmic rays. That probability is disturbingly high.

Just an idle search online produced this article:

http://news.cnet.com/8301-30685_3-10370026-264.html

which mentions some statistics. Think 1 billion hours is a lot and
"it'll never happen"?

There are 8760 hours in a year. So, you'd only need 114,156 computers
in a cluster running for one year before amassing 1 billion hours
of computation. That isn't a big number for large financial companies,
google, etc, etc, etc to own.

As a fun statistic, the BlueGene/P supercomputer can have 884,736
processors with associated memory modules. According to the math
in the article, one BlueGene/P should see a max of ~600,000 memory
errors per year.

Sure, you might not think any of this is a problem, because your
home desktop always produces the right answer when balancing your
checkbook, but it is a matter of perception of scale. Lots of large
clusters and data movement houses go to great length to ensure data
integrity. Injecting wrong data 4 hours into a 6 month long workflow
running on thousands of computers really upsets the hell out of people.

I've run into physicists who simply run their buggy software over
and over and over again on the same data and do statistical analysis
on the results. They've come to the realization that they can't
find/fix/verify all the bugs in their code, so they assume they are
there and write systems which try to be mathematically robust to the
nature of the beast. It is cheaper to wait for 1000 runs of a program
to be computed on a cluster than to spend human time debugging a
difficult bug in the code.

So, mathematically, maximum can't fail inside of itself, realistically
while executing on a physical machine, you bet it'll fail. :)

-pete








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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, Lie Ryan  wrote:
> On 09/30/10 16:09, TheFlyingDutchman wrote:
>> Dynamic typed languages like Python fail in this case on "Never blows
>> up".

> How do you define "Never blows up"?

I would say "blow up" would be "raise an exception".

> Personally, I'd consider maximum(8589934592, 1) returning 1 as a blow
> up, and of the worst kind since it passes silently.

So run your compiler with a decent set of warning levels, and watch as
you are magically warned that you're passing an object of the wrong type.

On any given system, one or the other is true:

1.  The constant 8589934592 is of type int, and the function will
"work" -- will give that result.
2.  The constant is not of type int, and the compiler will warn you about
this if you ask.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread RG
In article ,
 Seebs  wrote:

> On 2010-09-30, RG  wrote:
> > You can't have it both ways.  Either I am calling it incorrectly, in 
> > which case I should get a compiler error,
> 
> You get a warning if you ask for it.  If you choose to run without all
> the type checking on, that's your problem.

My example compiles with no warnings under gcc -Wall.

Yes, I know I could have used lint.  But that misses the point.  For any 
static analyzer, because of the halting problem, I can construct a 
program that either contains an error that the analyzer will not catch, 
or for which the analyzer will produce a false positive.

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


Re: install 3.1

2010-09-30 Thread Chris Rebert
> On Thu, Sep 30, 2010 at 4:16 PM, Chris Rebert  wrote:
>> On Thu, Sep 30, 2010 at 2:02 AM, roronron  wrote:
>> > My python installed but the gui gives me syntax error on any code I type
>> > or paste in. Newbie needs help.
>>
>> Post the full, exact text of the error message.
>> See also: http://www.catb.org/esr/faqs/smart-questions.html

On Thu, Sep 30, 2010 at 2:57 AM, ronald brown  wrote:
 print 'Hello, world!'
> SyntaxError: invalid syntax

> Installed 3 times. Used uninstall in program files and control panel.
> Followed directions on video for 3.1

Read the fine docs:
http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function
Python 3 has several backward-incompatible syntax changes. One of them
is that the print statement was removed and replaced with a print()
function.

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


Please help: pylint does not work with Emacs23 on Windows

2010-09-30 Thread Dsrt Egle
Hi,

I am trying to use Pylint with Emacs on Windows XP. My Emacs version
is EmacsW32 23.1, pylint is 0.21.3 with Python 2.5. After easy_install
pylint, I added the code block below to Emacs init file, copied form
Emacs Wiki.


(when (load "flymake" t)
  (defun flymake-pylint-init ()
(let* ((temp-file (flymake-init-create-temp-buffer-copy
   'flymake-create-temp-inplace))
   (local-file (file-relative-name
temp-file
(file-name-directory buffer-file-name
  (list "epylint" (list local-file

  (add-to-list 'flymake-allowed-file-name-masks
   '("\\.py\\'" flymake-pylint-init)))


When I invoke the flymake-mode on a .py file, I can see the flymake
starting the syntax check, the mode status changed to flymake*, and
then goes back to flymake after several seconds. But no error is
reported, and no syntax error highlighting.

I tried to use pylint in command line, and it works with command
"pylint test.py", reporting syntax errors on the same file.

I even tried to clear out my .emacs file, but it doesn't help.

Could someone help me on this? Thanks a lot.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread RG
In article ,
 Seebs  wrote:

> On 2010-09-30, Lie Ryan  wrote:
> > On 09/30/10 16:09, TheFlyingDutchman wrote:
> >> Dynamic typed languages like Python fail in this case on "Never blows
> >> up".
> 
> > How do you define "Never blows up"?
> 
> I would say "blow up" would be "raise an exception".
> 
> > Personally, I'd consider maximum(8589934592, 1) returning 1 as a blow
> > up, and of the worst kind since it passes silently.
> 
> So run your compiler with a decent set of warning levels, and watch as
> you are magically warned that you're passing an object of the wrong type.

My code compiles with no warnings under gcc -Wall.

> On any given system, one or the other is true:
> 
> 1.  The constant 8589934592 is of type int, and the function will
> "work" -- will give that result.
> 2.  The constant is not of type int, and the compiler will warn you about
> this if you ask.

It would be nice if this were true, but my example clearly demonstrates 
that it is not.  And if your response is to say that I should have used 
lint, then my response to that will be that because of the halting 
problem, for any static analyzer that you present, I can construct a 
program that either contains an error that either your analyzer will not 
catch, or for which it will generate a false positive.  It just so 
happens that constructing such examples for standard C is very easy.

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


Re: Please help: pylint does not work with Emacs23 on Windows

2010-09-30 Thread Dsrt Egle
On Sep 30, 9:38 am, Dsrt Egle  wrote:
> Hi,
>
> I am trying to use Pylint with Emacs on Windows XP. My Emacs version
> is EmacsW32 23.1, pylint is 0.21.3 with Python 2.5. After easy_install
> pylint, I added the code block below to Emacs init file, copied form
> Emacs Wiki.
>
>     (when (load "flymake" t)
>       (defun flymake-pylint-init ()
>         (let* ((temp-file (flymake-init-create-temp-buffer-copy
>                            'flymake-create-temp-inplace))
>            (local-file (file-relative-name
>                         temp-file
>                         (file-name-directory buffer-file-name
>           (list "epylint" (list local-file
>
>       (add-to-list 'flymake-allowed-file-name-masks
>                '("\\.py\\'" flymake-pylint-init)))
>
> When I invoke the flymake-mode on a .py file, I can see the flymake
> starting the syntax check, the mode status changed to flymake*, and
> then goes back to flymake after several seconds. But no error is
> reported, and no syntax error highlighting.
>
> I tried to use pylint in command line, and it works with command
> "pylint test.py", reporting syntax errors on the same file.
>
> I even tried to clear out my .emacs file, but it doesn't help.
>
> Could someone help me on this? Thanks a lot.


Question Update: I tried the following at command line prompt with
"pylint" and "epylint". Does this mean that epylint has a problem?

C:\Projects>pylint test_lib.py
No config file found, using default configuration
* Module test_lib
E: 13: invalid syntax

C:\Projects>epylint test_lib.py
'test_lib.py':1: [F] No module named 'test_lib.py'

C:\Projects>epylint
Traceback (most recent call last):
  File "C:\Python25\Scripts\epylint", line 5, in 
pkg_resources.run_script('pylint==0.21.3', 'epylint')
  File "C:\Python25\Lib\site-packages\pkg_resources.py", line 489,
in run_script

self.require(requires)[0].run_script(script_name, ns)
  File "C:\Python25\Lib\site-packages\pkg_resources.py", line
1207, in run_script
execfile(script_filename, namespace, namespace)
  File "c:\python25\lib\site-packages\pylint-0.21.3-py2.5.egg\EGG-
INFO\scripts\epylint", line 3, in 
epylint.Run()
  File "c:\python25\lib\site-packages\pylint-0.21.3-py2.5.egg
\pylint\epylint.py", line 93, in Run
lint(sys.argv[1])
IndexError: list index out of range
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, RG  wrote:
> My code compiles with no warnings under gcc -Wall.

That's nice.  gcc -Wall uses only a small subset of warnings that fit
the usual expectations of C code that's trying to work on common
architectures.

>> 2.  The constant is not of type int, and the compiler will warn you about
>> this if you ask.

> It would be nice if this were true, but my example clearly demonstrates 
> that it is not.

No, it doesn't, because you didn't ask for the relevant kind of warnings.

> And if your response is to say that I should have used 
> lint, then my response to that will be that because of the halting 
> problem, for any static analyzer that you present, I can construct a 
> program that either contains an error that either your analyzer will not 
> catch, or for which it will generate a false positive.  It just so 
> happens that constructing such examples for standard C is very easy.

I'm not sure that that's actually a halting problem case.  The thing about
static typing is that we don't actually HAVE to solve the halting problem;
we only have look at the types of the components, all of which are knowable
at compile time, and we can tell you whether there's any unsafe conversions.

And that's the magic of static typing:  It is not a false positive to
warn you that "2L" is not of type int.  There are things which would be a
false positive in trying to determine whether something will be out of range
in a runtime expression, but which are not false positives in a statically
typed language.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


namespace hacking question

2010-09-30 Thread kj



This is a recurrent situation: I want to initialize a whole bunch
of local variables in a uniform way, but after initialization, I
need to do different things with the various variables.

What I end up doing is using a dict:

d = dict()
for v in ('spam', 'ham', 'eggs'):
d[v] = init(v)

foo(d['spam'])
bar(d['ham'])
baz(d['eggs'])



This is fine, but I'd like to get rid of the tedium of typing all
those extra d['...']s.

I.e., what I would *like* to do is something closer to this:

d = locals()
for v in ('spam', 'ham', 'eggs'):
d[v] = init(v)

foo(spam)
bar(ham)
baz(eggs)

...but this results in errors like "NameError: global name 'spam' is
not defined".

But the problem is deeper than the fact that the error above would
suggest, because even this fails:

spam = ham = eggs = None
d = locals()
for v in ('spam', 'ham', 'eggs'):
d[v] = init(v)

foo(spam) # calls foo(None)
bar(ham)  # calls bar(None)
baz(eggs) # calls baz(None)


In other words, setting the value of locals()['x'] does not set
the value of the local variable x.

I also tried a hack using eval:

for v in ('spam', 'ham', 'eggs'):
eval "%s = init('%s')" % (v, v)

but the "=" sign in the eval string resulted in a "SyntaxError:
invalid syntax".

Is there any way to use a loop to set a whole bunch of local
variables (and later refer to these variables by their individual
names)?

TIA!

kj



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


Re: install 3.1

2010-09-30 Thread Andreas Waldenburger
On Thu, 30 Sep 2010 09:39:08 -0700 Chris Rebert 
wrote:
> On Thu, Sep 30, 2010 at 2:57 AM, ronald brown 
> wrote:
>  print 'Hello, world!'
> > SyntaxError: invalid syntax
> 
> > Installed 3 times. Used uninstall in program files and control
> > panel. Followed directions on video for 3.1
> 
> Read the fine docs:
> http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function
> Python 3 has several backward-incompatible syntax changes. One of them
> is that the print statement was removed and replaced with a print()
> function.
> 
Sort of serious proposal here: Would it make sense to display a big,
fat warning during the install process (and possibly on the first few
invocations of the interpreter) to the effect that "If you're starting
to learn Python, make sure you're using a Python 3 tutorial!".

This seems to throw a lot of people, and I don't see it going away too
soon. So maybe this might help?

/W

-- 
INVALID? DE!

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


Re: namespace hacking question

2010-09-30 Thread bruno.desthuilli...@gmail.com
On 30 sep, 19:07, kj  wrote:
> This is a recurrent situation: I want to initialize a whole bunch
> of local variables in a uniform way, but after initialization, I
> need to do different things with the various variables.
>
> What I end up doing is using a dict:
>
> d = dict()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(d['spam'])
> bar(d['ham'])
> baz(d['eggs'])
>
> This is fine, but I'd like to get rid of the tedium of typing all
> those extra d['...']s.
>
> I.e., what I would *like* to do is something closer to this:
>
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)
>
> foo(spam)
> bar(ham)
> baz(eggs)
>
> ...but this results in errors like "NameError: global name 'spam' is
> not defined".
>
> But the problem is deeper than the fact that the error above would
> suggest, because even this fails:
>
> spam = ham = eggs = None
> d = locals()
> for v in ('spam', 'ham', 'eggs'):
>     d[v] = init(v)

The local namespace is not implemented as a dict - locals() only
returns a dict representation of it, so updating this dict has no
effect on the local namespace. This is documented FWIW.

>
> I also tried a hack using eval:
>
> for v in ('spam', 'ham', 'eggs'):
>     eval "%s = init('%s')" % (v, v)
>
> but the "=" sign in the eval string resulted in a "SyntaxError:
> invalid syntax".

eval only accepts expressions. You'd need exec here - but that's a bit
ugly.

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


Re: namespace hacking question

2010-09-30 Thread MRAB

On 30/09/2010 18:07, kj wrote:




This is a recurrent situation: I want to initialize a whole bunch
of local variables in a uniform way, but after initialization, I
need to do different things with the various variables.

What I end up doing is using a dict:

d = dict()
for v in ('spam', 'ham', 'eggs'):
 d[v] = init(v)

foo(d['spam'])
bar(d['ham'])
baz(d['eggs'])



This is fine, but I'd like to get rid of the tedium of typing all
those extra d['...']s.

I.e., what I would *like* to do is something closer to this:

d = locals()
for v in ('spam', 'ham', 'eggs'):
 d[v] = init(v)

foo(spam)
bar(ham)
baz(eggs)

...but this results in errors like "NameError: global name 'spam' is
not defined".

But the problem is deeper than the fact that the error above would
suggest, because even this fails:

spam = ham = eggs = None
d = locals()
for v in ('spam', 'ham', 'eggs'):
 d[v] = init(v)

foo(spam) # calls foo(None)
bar(ham)  # calls bar(None)
baz(eggs) # calls baz(None)


In other words, setting the value of locals()['x'] does not set
the value of the local variable x.

I also tried a hack using eval:

for v in ('spam', 'ham', 'eggs'):
 eval "%s = init('%s')" % (v, v)

but the "=" sign in the eval string resulted in a "SyntaxError:
invalid syntax".

Is there any way to use a loop to set a whole bunch of local
variables (and later refer to these variables by their individual
names)?


The handling of local variables in CPython is optimised, so changing
locals() won't have any effect, as you discovered.

An alternative is to create a namespace in an instance of a class and
then add attributes to it:

class Namespace(object):
pass

n = Namespace()
for v in ('spam', 'ham', 'eggs'):
setattr(n, v, init(v))

foo(n.spam)
bar(n.ham)
baz(n.eggs)
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem in Gasp !

2010-09-30 Thread Cousin Stanley
n.a.s wrote:

> I want to ask about graphics using Gasp .Attached is exercise 10 
> (houses at night)  
>
> if  i call the draw_house function once it will work properly ,but more than 
> one call,windows and doors disappear from some houses .
>
> Any one can advice?

  A working version that runs using Python2.6 
  under Debian 6 Squeeze can be found at 
 
http://csphx.net/python/house.tar.bz

  A screenshot of the result is included 
  in that archive  

http://csphx.net/image/houses_10.png 


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: if the else short form

2010-09-30 Thread Andreas Waldenburger
On Thu, 30 Sep 2010 03:42:29 -0700 (PDT)
"bruno.desthuilli...@gmail.com"  wrote:

> On 29 sep, 19:20, Seebs  wrote:
> > On 2010-09-29, Tracubik  wrote:
> > > button = gtk.Button(("False,", "True,")[fill==True])
> 
> > Oh, what a nasty idiom.
> >
> 
> Well, it's not very different from dict-based dispatch , which is the
> core of OO polymorphic dispatch in quite a few dynamic OOPLs.
> 
> Anyway, it's a common Python idiom and one that's not specially hard
> to grasp so I don't see any legibility problem here.

But it does violate the "explicit is better than implicit" tenet, don't
you think?

/W

-- 
INVALID? DE!

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Scott L. Burson

Ian Collins wrote:

On 09/30/10 05:57 PM, RG wrote:


I'm not saying one should not use compile-time tools, only that one
should not rely on them. "Compiling without errors" is not -- and
cannot ever be -- be a synonym for "bug-free."


We is why we all have run time tools called unit tests, don't we?



My post that kicked off this thread was not cross-posted, so many of the 
participants may not have seen it.  Here it is again, for your convenience:


-

This might have been mentioned here before, but I just came across it: a 
2003 essay by Bruce Eckel on how reliable systems can get built in 
dynamically-typed languages.  It echoes things we've all said here, but 
I think it's interesting because it describes a conversion experience: 
Eckel started out in the strong-typing camp and was won over.


  https://docs.google.com/View?id=dcsvntt2_25wpjvbbhk

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread RG
In article ,
 Seebs  wrote:

> And that's the magic of static typing:  It is not a false positive to
> warn you that "2L" is not of type int.

We'll have to agree to disagree about that.  The numerical value 2 can 
safely be represented as an int, so I would consider this a false 
positive.

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Scott L. Burson

Pascal J. Bourguignon wrote:

Squeamizh  writes:


In short, static typing doesn't solve all conceivable problems.

We are all aware that there is no perfect software development process
or tool set.  I'm interested in minimizing the number of problems I
run into during development, and the number of bugs that are in the
finished product.  My opinion is that static typed languages are
better at this for large projects, for the reasons I stated in my
previous post.


Here's a post I wrote earlier, before the conversation got cross-posted. 
 To me, this is the essence of the matter.


---

Norbert_Paul wrote:
>
> OK, but sometimes it is handy to have the possibility to make 
compile-time

> assertions which prevent you from committing easily avoidable simple
> mistakes.

Agreed.  I actually don't see this issue in black and white terms; I've 
written lots of Lisp, and I've written lots of code in statically typed 
languages, and they all have advantages and disadvantages.  In the end 
it all comes back to my time: how much time does it take me to ship a 
debugged system?  Working in Lisp, sometimes I don't get immediate 
feedback from the compiler that I've done something stupid, but this is 
generally counterbalanced by the ease of interactive testing, that 
frequently allows me to run a new piece of code several times in the 
time it would have taken me to do a compile-and-link in, say, C++.


So while I agree with you that compiler warnings are sometimes handy, 
and there are occasions, working in Lisp, that I would like to have more 
of them(*), it really doesn't happen to me very often that the lack of 
one is more than a minor problem.


(*) Lisp compilers generally do warn about some things, like passing the 
wrong number of arguments to a function, or inconsistent spelling of the 
name of a local variable.  In my experience, these warnings cover a 
substantial fraction of the stupid mistakes I actually make.


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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Keith Thompson
Seebs  writes:
> On 2010-09-30, Paul Rubin  wrote:
>> int maximum(int a, int b);
>>
>> int foo() {
>>   int (*barf)() = maximum;
>>   return barf(3);
>> }
>
>> This compiles fine for me.  Where is the cast?
>
> On the first line of code inside foo().

Look again; there's no cast in foo().

That first line declare barf as an object of type "pointer to
function returning int", or more precisely, "pointer to function with
an unspecified but fixed number and type of parameters returning int"
(i.e., an old-style non-prototype declaration, still legal but
deprecated in both C90 and C99).  It then initializes it to point
to the "maximum" function.  I *think* the types are sufficiently
"compatible" (not necessarily using that word the same way the
standard does) for the initialization to be valid and well defined.
I might check the standard later.

It would have been better to use a prototype (for those of you
in groups other than comp.lang.c, that's a function declaration that
specifies the types of any parameters):

int (*barf)(int, int) = maximum;

IMHO it's better to use prototypes consistently than to figure out the
rules for interactions between prototyped vs. non-prototyped function
declarations.

[...]

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Paul Rubin
RG  writes:
> Yes, I know I could have used lint.  But that misses the point.  For any 
> static analyzer, because of the halting problem, I can construct a 
> program that either contains an error that the analyzer will not catch, 
> or for which the analyzer will produce a false positive.

Can you describe any plausible real-world programs where the effort of
complicated static is justified, and for which the halting problem gets
in the way of analysis?  By "real world", I meanI wouldn't consider
searching for counterexamples to the Collatz conjecture to qualify as
sufficiently real-world and sufficiently complex for fancy static
analysis.  And even if it did, the static analyzer could deliver a
partial result, like "this function either returns a counterexample to
the Collatz conjecture or else it doesn't return".  

D. Turner wrote a famous paper arguing something like the above, saying
basically that Turing completeness of programming languages is
overrated:

  http://www.jucs.org/jucs_10_7/total_functional_programming

The main example of a sensible program that can't be written in a
non-complete language is an interpreter for a Turing-complete language.
But presumably a high-assurance application should never contain such a
thing, since the interpreted programs themselves then wouldn't have
static assurance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal J. Bourguignon
RG  writes:

> One might hypothesize that the best of both worlds would be a dynamic 
> language with a static analyzer layered on top.  Such a thing does not 
> exist.  It makes an instructive exercise to try to figure out why.  (For 
> the record, I don't know the answer, but I've learned a lot through the 
> process of pondering this conundrum.)

There are static analysis tools for Common Lisp:
http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/lang/lisp/code/tools/lint/0.html

or lisp in general.  For example PHENARETE is in the category of static
analysis tools.

One could regret that they're not more developed, but I guess this only
proves the success of using dynamic programming languages: if there were
a real need for these tools, along with a good ROI, they would be more
developed.  In the meantime, several test frameworks are developed.


-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal J. Bourguignon
RG  writes:

> In article ,
>  Seebs  wrote:
>
>> On 2010-09-30, RG  wrote:
>> > You can't have it both ways.  Either I am calling it incorrectly, in 
>> > which case I should get a compiler error,
>> 
>> You get a warning if you ask for it.  If you choose to run without all
>> the type checking on, that's your problem.
>
> My example compiles with no warnings under gcc -Wall.

IIRC, -Wall is not reall ALL.

Try with:  gcc -Wall  -Wextra -Werror 

I would still argue that should be the default, and if really there was
a need, there could be options to disable some warning, or to have some
errors be warnings...

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Keith Thompson
RG  writes:
> In article ,
>  Keith Thompson  wrote:
>> RG  writes:
>> [...]
>> > You can't have it both ways.  Either I am calling it incorrectly, in 
>> > which case I should get a compiler error, or I am calling it correctly, 
>> > and I should get the right answer.  That I got neither does in fact 
>> > falsify the claim.  The only way out of this is to say that 
>> > maximum(8589934592, 1) returning 1 is in fact "correct", in which case 
>> > we'll just have to agree to disagree.
>> 
>> You are calling maximum() incorrectly, but you are doing so in a way
>> that the compiler is not required to diagnose.
>
> Yes.  I know.  That was my whole point.  There are ways to call a 
> function incorrectly (more broadly, there are errors in code) that a C 
> compiler is not required to diagnose.

Of course.

>> If you want to say that the fact that the compiler is not required
>> to diagnose the error is a flaw in the C language, I won't
>> argue with you.
>
> I'm not even saying it's a flaw in the language.  All I'm saying is that 
> the original claim -- that any error in a C program will be caught by 
> the compiler -- is false, and more specifically, that it can be 
> demonstrated to be false without appeal to unknown run-time input.

Did someone *really* claim that "any error in a C program will
be caught by the compiler"?  If so, I must have missed that.
It's certainly not true; code that compiles cleanly can be riddled
with errors.  That's true in any language, but more so in C than
in some others.

> As an aside, this particular error *could* be caught (and in fact would 
> be caught by other tools like lint), but there are errors that can not 
> be caught by any static analysis, and that therefore one should not be 
> lulled into a false sense of security by the fact that your code is 
> written in a statically typed language and compiled without errors or 
> warnings.  That's all.

I don't believe anyone has said otherwise.

>> If I write:
>> 
>> const double pi = 22.0/7.0;
>> printf("pi = %f\n", pi);
>> 
>> then I suppose I'm calling printf() incorrectly, but I wouldn't
>> expect my compiler to warn me about it.
>> 
>> If you're arguing that
>> 
>> int maximum(int a, int b) { return a > b ? a : b; }
>> 
>> is flawed because it's too easy to call it incorrectly, you're
>> effectively arguing that it's not possible to write correct
>> code in C at all.
>
> I would say that it is very, very hard to write correct code in C for 
> any non-vacuous definition of "correct".  That is the reason that core 
> dumps and buffer overflows are so ubiquitous.  I prefer Lisp or Python, 
> where core dumps and buffer overflows are virtually nonexistent.  One 
> does get the occasional run-time error that might have been caught at 
> compile time, but I much prefer that to a core dump or a security hole.

I would say that it can certainly be difficult to write correct
code in C, but I don't believe it's nearly as hard as you think
it is.  It requires more discipline than some other languages,
and it can require some detailed  knowledge of the language itself,
particularly what it defines and what it doesn't.  And it's not
always worth the effort if another language can do the job as well
or better.

> One might hypothesize that the best of both worlds would be a dynamic 
> language with a static analyzer layered on top.  Such a thing does not 
> exist.  It makes an instructive exercise to try to figure out why.  (For 
> the record, I don't know the answer, but I've learned a lot through the 
> process of pondering this conundrum.)

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Re: Problems with wsgi Python3

2010-09-30 Thread hidura

Sorry, for the last mail, here it's what you asked:

{'CONTENT_LENGTH': '61',
[Thu Sep 30 13:35:07 2010] [error] 'CONTENT_TYPE':
[Thu Sep 30 13:35:07 2010] [error] 'multipart/form-data;  
boundary=---8905735096173894531259794847',

[Thu Sep 30 13:35:07 2010] [error] 'DOCUMENT_ROOT':
[Thu Sep 30 13:35:07 2010] [error] '/home/hidura/webapps/karinapp/Suite',
[Thu Sep 30 13:35:07 2010] [error] 'GATEWAY_INTERFACE':
[Thu Sep 30 13:35:07 2010] [error] 'CGI/1.1',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_ACCEPT':
[Thu Sep 30 13:35:07 2010]  
[error] 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

[Thu Sep 30 13:35:07 2010] [error] 'HTTP_ACCEPT_CHARSET':
[Thu Sep 30 13:35:07 2010] [error] 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_ACCEPT_ENCODING':
[Thu Sep 30 13:35:07 2010] [error] 'gzip,deflate',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_ACCEPT_LANGUAGE':
[Thu Sep 30 13:35:07 2010] [error] 'es-do,en-us;q=0.7,en;q=0.3',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_CONNECTION':
[Thu Sep 30 13:35:07 2010] [error] 'close',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_HOST':
[Thu Sep 30 13:35:07 2010] [error] 'hidura.webfactional.com',
[Thu Sep 30 13:35:07 2010] [error] 'HTTP_REFERER':
[Thu Sep 30 13:35:07 2010]  
[error] 'http://hidura.webfactional.com/?md=btdump',

[Thu Sep 30 13:35:07 2010] [error] 'HTTP_USER_AGENT':
[Thu Sep 30 13:35:07 2010] [error] 'Mozilla/5.0 (X11; U; Linux x86_64;  
en-US; rv:1.9.2.10) Gecko/20100915 Ubuntu/10.04 (lucid) Firefox/3.6.10',

[Thu Sep 30 13:35:07 2010] [error] 'HTTP_X_FORWARDED_FOR':
[Thu Sep 30 13:35:07 2010] [error] '190.94.122.180',
[Thu Sep 30 13:35:07 2010] [error] 'PATH_INFO':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'QUERY_STRING':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'REMOTE_ADDR':
[Thu Sep 30 13:35:07 2010] [error] '127.0.0.1',
[Thu Sep 30 13:35:07 2010] [error] 'REMOTE_PORT':
[Thu Sep 30 13:35:07 2010] [error] '58742',
[Thu Sep 30 13:35:07 2010] [error] 'REQUEST_METHOD':
[Thu Sep 30 13:35:07 2010] [error] 'POST',
[Thu Sep 30 13:35:07 2010] [error] 'REQUEST_URI':
[Thu Sep 30 13:35:07 2010] [error] '/Gate.py',
[Thu Sep 30 13:35:07 2010] [error] 'SCRIPT_FILENAME':
[Thu Sep 30 13:35:07 2010]  
[error] '/home/hidura/webapps/karinapp/Suite/Gate.py',

[Thu Sep 30 13:35:07 2010] [error] 'SCRIPT_NAME':
[Thu Sep 30 13:35:07 2010] [error] '/Gate.py',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_ADDR':
[Thu Sep 30 13:35:07 2010] [error] '127.0.0.1',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_ADMIN':
[Thu Sep 30 13:35:07 2010] [error] '[no address given]',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_NAME':
[Thu Sep 30 13:35:07 2010] [error] 'hidura.webfactional.com',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_PORT':
[Thu Sep 30 13:35:07 2010] [error] '80',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_PROTOCOL':
[Thu Sep 30 13:35:07 2010] [error] 'HTTP/1.0',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_SIGNATURE':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'SERVER_SOFTWARE':
[Thu Sep 30 13:35:07 2010] [error] 'Apache/2.2.15 (Unix) mod_wsgi/3.3  
Python/3.1',

[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.application_group':
[Thu Sep 30 13:35:07 2010] [error] 'web152.webfaction.com|/gate.py',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.callable_object':
[Thu Sep 30 13:35:07 2010] [error] 'application',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.handler_script':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.input_chunked':
[Thu Sep 30 13:35:07 2010] [error] '0',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.listener_host':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.listener_port':
[Thu Sep 30 13:35:07 2010] [error] '51543',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.process_group':
[Thu Sep 30 13:35:07 2010] [error] '',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.request_handler':
[Thu Sep 30 13:35:07 2010] [error] 'wsgi-script',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.script_reloading':
[Thu Sep 30 13:35:07 2010] [error] '1',
[Thu Sep 30 13:35:07 2010] [error] 'mod_wsgi.version':
[Thu Sep 30 13:35:07 2010] [error] (3, 3),
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.errors':
[Thu Sep 30 13:35:07 2010] [error] <_io.TextIOWrapper encoding='utf-8'>,
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.file_wrapper':
[Thu Sep 30 13:35:07 2010] [error] mod_wsgi.Adapter object at 0xb7b97218>,

[Thu Sep 30 13:35:07 2010] [error] 'wsgi.input':
[Thu Sep 30 13:35:07 2010] [error] ,
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.multiprocess':
[Thu Sep 30 13:35:07 2010] [error] False,
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.multithread':
[Thu Sep 30 13:35:07 2010] [error] True,
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.run_once':
[Thu Sep 30 13:35:07 2010] [error] False,
[Thu Sep 30 13:35:07 2010] [error] 'wsgi.url_scheme':
[Thu Sep 30 13:35:07 2010] [error] 'http',
[Thu S

Re: "Strong typing vs. strong testing"

2010-09-30 Thread Pascal J. Bourguignon
TheFlyingDutchman  writes:

>>
>> > "in C I can have a function maximum(int a, int b) that will always
>> > work. Never blow up, and never give an invalid answer. "
>>
>> > Dynamic typed languages like Python fail in this case on "Never blows
>> > up".
>>
>> How do you define "Never blows up"?
>
> Never has execution halt.
>
> I think a key reason in the big rise in the popularity of interpreted
> languages 

This is a false conception.

Whether the execution of a program is done by a processor of the
programming language, or a processor of another programming language
(and therefore requiring a translation phase), is a notion is NOT a
characteristic of programming language, but only of execution
environments.


1- There are C interpreters
CINT - http://root.cern.ch/root/Cint.html
EiC - http://eic.sourceforge.net/
Ch - http://www.softintegration.com

2- All the current Common Lisp implementations have compilers,

3- Most current Common Lisp implementations actually compile to native
   code (ie they chose to translate to programming languages that are
   implemented by Intel, AMD or Motorola. (Notice that these programming
   languages are NOT implemented in hardware, but in software, called
   micro-code, stored on the real hardware inside the
   micro-processors); some choose to translate to C and call an external
   C compiler to eventually translate to "native" code).

4- Actually, there is NO current Common Lisp implementation having only
   an interpreter.  On the contrary, most of the don't have any
   interpreter (but all of them have a REPL, this is an orthogonal
   concept).

5- Even the first LISP implementation made in 1959 had a compiler.

6- I know less the situation for the other dynamic programming language,
   but for example, if CPython weren't a compiler, you should know that
   CLPython is a compiler (it's an implementation of Python written in
   Common Lisp, which translates Python into Common Lisp and compiles it).


> is that when execution halts, they normally give a call
> stack and usually a good reason for why things couldn't continue. As
> opposed to compiled languages which present you with a blank screen
> and force you to - fire up a debugger, or much much worse, look at a
> core dump - to try and discern all the information the interpreter
> presents to you immediately.

Theorically, a compiler for a static programming language has even more
information about the program, so it should be able to produce even
better backtrace in case of problem...

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace hacking question

2010-09-30 Thread Arnaud Delobelle
MRAB  writes:

> On 30/09/2010 18:07, kj wrote:
>>
>>
>>
>> This is a recurrent situation: I want to initialize a whole bunch
>> of local variables in a uniform way, but after initialization, I
>> need to do different things with the various variables.
>>
>> What I end up doing is using a dict:
>>
>> d = dict()
>> for v in ('spam', 'ham', 'eggs'):
>>  d[v] = init(v)
>>
>> foo(d['spam'])
>> bar(d['ham'])
>> baz(d['eggs'])
>>
>>
>>
>> This is fine, but I'd like to get rid of the tedium of typing all
>> those extra d['...']s.
>>
>> I.e., what I would *like* to do is something closer to this:
>>
>> d = locals()
>> for v in ('spam', 'ham', 'eggs'):
>>  d[v] = init(v)
>>
>> foo(spam)
>> bar(ham)
>> baz(eggs)
>>
>> ...but this results in errors like "NameError: global name 'spam' is
>> not defined".
>>
>> But the problem is deeper than the fact that the error above would
>> suggest, because even this fails:
>>
>> spam = ham = eggs = None
>> d = locals()
>> for v in ('spam', 'ham', 'eggs'):
>>  d[v] = init(v)
>>
>> foo(spam) # calls foo(None)
>> bar(ham)  # calls bar(None)
>> baz(eggs) # calls baz(None)
>>
>>
>> In other words, setting the value of locals()['x'] does not set
>> the value of the local variable x.
>>
>> I also tried a hack using eval:
>>
>> for v in ('spam', 'ham', 'eggs'):
>>  eval "%s = init('%s')" % (v, v)
>>
>> but the "=" sign in the eval string resulted in a "SyntaxError:
>> invalid syntax".
>>
>> Is there any way to use a loop to set a whole bunch of local
>> variables (and later refer to these variables by their individual
>> names)?
>>
> The handling of local variables in CPython is optimised, so changing
> locals() won't have any effect, as you discovered.
>
> An alternative is to create a namespace in an instance of a class and
> then add attributes to it:
>
> class Namespace(object):
> pass
>
> n = Namespace()
> for v in ('spam', 'ham', 'eggs'):
> setattr(n, v, init(v))
>
> foo(n.spam)
> bar(n.ham)
> baz(n.eggs)

Note that "exec" can be used:

>>> def init(name):
... return "init " + name
... 
>>> def foo():
... for name in "bar", "baz":
... exec "%s = init(name)" % name
... print bar
... print baz
... 
>>> foo()
init bar
init baz

Not that I can think of a reason to do this :)

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


C API: Getting PyObject by name

2010-09-30 Thread pbienst
Hi,

I'm embedding Python in a C app.

Say I do the following:

  PyRun_SimpleString("a = 1")

Is there then a way to get access to the PyObject corresponding to a,
only making use in C of the fact that it's called "a"?

I've searched through the API docs, but I couldn't really find what I
was looking for.

Any help most appreciated!

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


Re: "Strong typing vs. strong testing"

2010-09-30 Thread Seebs
On 2010-09-30, RG  wrote:
> In article ,
>  Seebs  wrote:
>> And that's the magic of static typing:  It is not a false positive to
>> warn you that "2L" is not of type int.

> We'll have to agree to disagree about that.

No, we won't.  It's the *definition* of static typing.  Static typing
is there to give you some guarantees at the expense of not being able
to express some things without special extra effort.  That's why it's
static.

> The numerical value 2 can 
> safely be represented as an int, so I would consider this a false 
> positive.

That's nice for you, I guess.

The point of static typing is that it makes it possible to ensure that
the values that reach a function are in fact of the correct type -- at
the cost of not being able to rely on free runtime conversions.

If you want to write safe conversions, you can do that.  If you don't
bother to do that, you end up with errors -- by definition.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >