THRINAXODON BLOWS THE SMOKE HARD!

2014-01-25 Thread Thrinass

==
>BREAKING NEWS
==
>
The New York Times, Thrinaxodon, PhD
===
>
According to U.S. dictator Obama, the U.S. has recently legalized weed 
to brainwash it's citizens. Millions of Americans hate the new move, 
they don't want OUR KIDS GROWING UP IN A WORLD RULLED BY WEED! 
Thrinaxodon was mad at the move, staying in New Zealand to get away from 
the shit, Thrinaxodon said, "My homeland America has legalized a drug! 
WTF? Obama has already done enough crimes against humanity, but 
brainwashing our Star Trek: Next Generation is now the new goal of the 
Obama regime? WTF?"

>

>
Obama said, "I`m doing this for my people, fellow Americans by 
brainwashing our Star Trek: Next Generation for my BRAND NEW FEMA CAMPS!"

>
Thrinaxodon said, "Bullshit! Communist regimes are better than the Obama 
regime!"


>
Who knows what will happen to our sons and grandsons.
>
==
EVIDENCE THAT HUMANS LIVED IN THE DEVONIAN:

https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/6f501c469c7af24f#

https://groups.google.com/group/sci.bio.paleontology/browse_thread/thread/3aad75c16afb0b82#



http://thrinaxodon.wordpress.com/

===

THRINAXODON ONLY HAD THIS TO SAY:

"I..I...I...Can't believe it. This completely disproved Darwinian
orthodoxy."

===

THE BASTARDS AT THE SMITHSONIAN, AND THE LEAKEY FOUNDATION ARE ERODING
WITH FEAR.

===
THESE ASSHOLES ARE GOING TO DIE:
THOMAS AQUINAS;
ALDOUS HUXLEY;
BOB CASANVOVA;
SkyEyes;
DAVID IAIN GRIEG;
MARK ISAAK;
JOHN HARSHAM;
RICHARD NORMAN;
DR. DOOLITTLE;
CHARLES DARWIN;
MARK HORTON;
ERIK SIMPSON;
HYPATIAB7;
PAUL J. GANS;
JILLERY;
WIKI TRIK;
THRINAXODON;
PETER NYIKOS;
RON OKIMOTO;
JOHN S. WILKINS
===

THRINAXODON WAS SCOURING ANOTHER DEVONIAN FOSSIL BED, AND FOUND A
HUMAN SKULL, AND A HUMAN FEMUR. HE ANALYSED THE FINDS, AND SAW THAT
THEY WERE NOT NORMAL ROCKS. THESE WERE FOSSILIZED BONES. THEY EVEN HAD
TOOTH MARKS ON THEM. SO, THRINAXODON BROUGHT THEM TO THE LEAKEY
FOUNDATION, THEY UTTERLY DISMISSED IT, AND SAID, "We want to keep
people thinking that humans evolved 2 Ma." THRINAXODON BROUGHT HIS
SWORD, AND SAID, "SCIENCE CORRECTS ITSELF." RICHARD LEAKEY SAID, "That
is a myth, for people to believe in science." THRINAXODON PLANS TO
BRING DOOM TO SCIENCE, ITSELF.



THRINAXODON IS NOW ON TWITTER.

--
Thrinaxodon, The Ultimate Defender of USENET
--
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand this moji-bake

2014-01-25 Thread Peter Otten
Steven D'Aprano wrote:

> I have an unexpected display error when dealing with Unicode strings, and
> I cannot understand where the error is occurring. I suspect it's not
> actually a Python issue, but I thought I'd ask here to start.

I suppose it is a Python issue -- where Python fails to guess an encoding it 
usually falls back to ascii.

> But using Python 2.7, I get a really bad case of moji-bake:
> 
> [steve@ando ~]$ python2.7 -c "print u'ñøλπйж'"
> ñøλÏйж
> 
> 
> However, interactively it works fine:
> 
> [steve@ando ~]$ python2.7 -E
> Python 2.7.2 (default, May 18 2012, 18:25:10)
> [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 print u'ñøλπйж'
> ñøλπйж

You can provoke it with exec:

>>> exec "print u'ñøλπйж'"
ñøλÏйж
>>> exec u"print u'ñøλπйж'"
ñøλπйж
>>> exec "# -*- coding: utf-8 -*-\nprint u'ñøλπйж'"
ñøλπйж

> This occurs on at least two different machines, one using Centos and the
> other Debian.
> 
> Anyone have any idea what's going on? I can replicate the display error
> using Python 3 like this:
> 
> py> s = 'ñøλπйж'
> py> print(s.encode('utf-8').decode('latin-1'))
> ñøλÏйж
> 
> but I'm not sure why it's happening at the command line. Anyone have any
> ideas?

It is probably burried in the C code -- after a few indirections I lost 
track :(

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


Re: Trying to understand this moji-bake

2014-01-25 Thread wxjmfauth
Le samedi 25 janvier 2014 05:37:34 UTC+1, Steven D'Aprano a écrit :
> I have an unexpected display error when dealing with Unicode strings, and 
> 
> I cannot understand where the error is occurring. I suspect it's not 
> 
> actually a Python issue, but I thought I'd ask here to start.
> 
> 
> 
> Using Python 3.3, if I print a unicode string from the command line, it 
> 
> displays correctly. I'm using the KDE 3.5 Konsole application, with the 
> 
> encoding set to the default (which ought to be UTF-8, I believe, although 
> 
> I'm not completely sure). This displays correctly:
> 
> 
> 
> [steve@ando ~]$ python3.3 -c "print(u'ñøλπйж')"
> 
> ñøλπйж
> 
> 
> 
> 
> 
> Likewise for Python 3.2:
> 
> 
> 
> [steve@ando ~]$ python3.2 -c "print('ñøλπйж')"
> 
> ñøλπйж
> 
> 
> 
> 
> 
> But using Python 2.7, I get a really bad case of moji-bake:
> 
> 
> 
> [steve@ando ~]$ python2.7 -c "print u'ñøλπйж'"
> 
> ñøλÏйж
> 
> 
> 
> 
> 
> However, interactively it works fine:
> 
> 
> 
> [steve@ando ~]$ python2.7 -E
> 
> Python 2.7.2 (default, May 18 2012, 18:25:10)
> 
> [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
> 
> Type "help", "copyright", "credits" or "license" for more information.
> 
> >>> print u'ñøλπйж'
> 
> ñøλπйж
> 
> 
> 
> 
> 
> This occurs on at least two different machines, one using Centos and the 
> 
> other Debian.
> 
> 
> 
> Anyone have any idea what's going on? I can replicate the display error 
> 
> using Python 3 like this:
> 
> 
> 
> py> s = 'ñøλπйж'
> 
> py> print(s.encode('utf-8').decode('latin-1'))
> 
> ñøλÏйж
> 
> 
> 
> but I'm not sure why it's happening at the command line. Anyone have any 
> 
> ideas?
> 
> 
> 

The basic problem is neither Python, nor the system (OS), nor
the terminal, nor the GUI console. The basic problem is that
all these elements [*] are not "speaking" the same language.

The second problem lies in Python itsself. Python attempts
to solve this problem by doing its own "cooking" based on the
elements, I pointed above [*], with the side effect the
situation may just become more confused and/or just not properly
working (sys.std***.encoding, print, GUI/terminal, souce
coding, ...)

The third problem is more *x specific. In many cases,
the Python "distribution" is tweaked in such a way to
make it working on a specific *x-version/distribution
(sys.getdefaultencoding(), site.py, sitecustomize.py)
and finally resulting in a non properly working Python.

Fourth problem. GUI applications supposed to mimick the
"real" terminal by doing and adding their own "recipes".

Fifth problem. The user who has to understand all this
stuff.

n-th problem, ...
jmf

PS I already understood all this stuff ten years ago!

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


Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread justinpmullins
My son is learning Python and I know nothing about computers. 
He's written a simple calculator program that doesn't work. For the life of me, 
I can't see why.
Any help gratefully received. Here's his code: 
def a():
import sys
print("welcome to the calculation")
print("please type a number")
one = int(sys.stdin.readline())
print("type d for division,")
print("type m for multiplication,") 
print("type s for subtraction,")
print("and type p for plus")
op = (sys.stdin.readline())
print("%s selected" % op)
print("please enter another number")
two = int(sys.stdin.readline())
if op == str(d):
out == one / two
print("the answer is %s" % out)
elif op == "m":
out == one * two
print("the answer is %s" % out)
elif op == "s":
out == one - two
print("the answer is %s" % out)
elif op == "p":
out == one + two
print("the answer is %s" % out)
else:
print("huh")

Where is he going wrong?
Many thanks in advance

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


Re: Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread Ervin Hegedüs
Hello,

On Sat, Jan 25, 2014 at 02:02:15AM -0800, [email protected] wrote:
> My son is learning Python and I know nothing about computers. 

:)

> He's written a simple calculator program that doesn't work. For the life of 
> me, I can't see why.
> Any help gratefully received. Here's his code: 
> def a():
>   import sys
>   print("welcome to the calculation")
>   print("please type a number")
>   one = int(sys.stdin.readline())
>   print("type d for division,")
>   print("type m for multiplication,") 
>   print("type s for subtraction,")
>   print("and type p for plus")
>   op = (sys.stdin.readline())
>   print("%s selected" % op)
>   print("please enter another number")
>   two = int(sys.stdin.readline())
>   if op == str(d):
>   out == one / two
>   print("the answer is %s" % out)
>   elif op == "m":
>   out == one * two
>   print("the answer is %s" % out)
>   elif op == "s":
>   out == one - two
>   print("the answer is %s" % out)
>   elif op == "p":
>   out == one + two
>   print("the answer is %s" % out)
>   else:
>   print("huh")
> 
> Where is he going wrong?

what's your error message?

First, you have to put an interpreter in first line - if you're
on Linux/Unix:

#!/usr/bin/python

or some kind of that. I don't know what's the expected on Windows
:(.

Second, you defined a funcfion, called "a", and if you want to
see how does it work, you must call that (after you define it):

def a():
  ...
  ...

a()


Third, at the first statement (if op == str(d)) you're
referencing for an undefined variable (d), I think you would
put `if op == "d":', instad of that.


Good luck,

Ervin


-- 
I � UTF-8
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread justinpmullins
PS: At the first statement, we've also tried 
 
op == "d":

But that doesn't work either.



On Saturday, January 25, 2014 10:02:15 AM UTC, [email protected] wrote:
> My son is learning Python and I know nothing about computers. 
> 
> He's written a simple calculator program that doesn't work. For the life of 
> me, I can't see why.
> 
> Any help gratefully received. Here's his code: 
> 
> def a():
> 
>   import sys
> 
>   print("welcome to the calculation")
> 
>   print("please type a number")
> 
>   one = int(sys.stdin.readline())
> 
>   print("type d for division,")
> 
>   print("type m for multiplication,") 
> 
>   print("type s for subtraction,")
> 
>   print("and type p for plus")
> 
>   op = (sys.stdin.readline())
> 
>   print("%s selected" % op)
> 
>   print("please enter another number")
> 
>   two = int(sys.stdin.readline())
> 
>   if op == str(d):
> 
>   out == one / two
> 
>   print("the answer is %s" % out)
> 
>   elif op == "m":
> 
>   out == one * two
> 
>   print("the answer is %s" % out)
> 
>   elif op == "s":
> 
>   out == one - two
> 
>   print("the answer is %s" % out)
> 
>   elif op == "p":
> 
>   out == one + two
> 
>   print("the answer is %s" % out)
> 
>   else:
> 
>   print("huh")
> 
> 
> 
> Where is he going wrong?
> 
> Many thanks in advance
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread Peter Otten
[email protected] wrote:

> My son is learning Python and I know nothing about computers.
> He's written a simple calculator program that doesn't work. 

Normally you are supposed to explain what you or your son expect and what 
you get instead. If Python ends with an error you should paste that into 
your message, e. g.:

Traceback (most recent call last):
  File "calculator.py", line 29, in 
a()
  File "calculator.py", line 14, in a
if op == str(d):
NameError: global name 'd' is not defined

Also, we need to know if you are using Python 2 or Python 3. Sometimes even 
the exact version is important. You can find it out with

$ python3 -V
Python 3.2.2

> For the life
> of me, I can't see why. Any help gratefully received. Here's his code:

> def a():
> import sys
> print("welcome to the calculation")
> print("please type a number")
> one = int(sys.stdin.readline())
> print("type d for division,")
> print("type m for multiplication,") 
> print("type s for subtraction,")
> print("and type p for plus")
> op = (sys.stdin.readline())
> print("%s selected" % op)
> print("please enter another number")
> two = int(sys.stdin.readline())
> if op == str(d):

The name d is defined nowhere in your script. That line should be

  if op == "d":

similar to the `elif`s that follow.

> out == one / two

You want to assign to out but you are actually comparing out to one / two. 
Change the line (and similar lines below) to a single =, e. g.
  out = one / two

> print("the answer is %s" % out)
> elif op == "m":
> out == one * two
> print("the answer is %s" % out)
> elif op == "s":
> out == one - two
> print("the answer is %s" % out)
> elif op == "p":
> out == one + two
> print("the answer is %s" % out)
> else:
> print("huh")

Change the above line to

  print("Unknown op=%r" % op) 

and add a function invocation

a()

> Where is he going wrong?
> Many thanks in advance

When you run the script with my modifications

$ python3 calculator.py 
welcome to the calculation
please type a number
10
type d for division,
type m for multiplication,
type s for subtraction,
and type p for plus
m
m
 selected
please enter another number
20
Unknown op='m\n'

you see that what you supposed to be an "m" is actually an "m" followed by a 
newline. The readline() method reads a line including the final newline.
You can remove that by changing the line

op = (sys.stdin.readline())

to

op = sys.stdin.readline().strip()

but a more straightforward approach would be to replace all occurences of

sys.stdin.readline()

with 

input() # if you are using Python 3

or

raw_input() # if yo are using Python 2.


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


Re: Python declarative

2014-01-25 Thread Matěj Cepl
[This message has also been posted to gmane.comp.python.general.]
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 2014-01-25, 07:18 GMT, Frank Millman wrote:
> I have stated that my objective is to express as little as 
> possible in Python code.

Yes, and I believe that it is very wrong. But anyway, if you are 
so passionate about GUI-via-XML, what’s wrong with Glade 
(http://www.pygtk.org/pygtk2reference/class-gladexml.html)? You 
have editors for that XML etc.

Matěj

-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)

iD8DBQFS457O4J/vJdlkhKwRAlA7AJ9nTl4v+FoiNZb3NLaSsIZMd2HO5wCeNYwe
EVLDNqlw3YaQtloF1RGWP8Y=
=AloI
-END PGP SIGNATURE-
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread Denis McMahon
On Sat, 25 Jan 2014 02:02:15 -0800, justinpmullins wrote:

> def a():
>   import sys print("welcome to the calculation") print("please type 
a
>   number")
>   one = int(sys.stdin.readline()) print("type d for division,")
>   print("type m for multiplication,") print("type s for 
subtraction,")
>   print("and type p for plus")
>   op = (sys.stdin.readline()) print("%s selected" % op) print
("please
>   enter another number")
>   two = int(sys.stdin.readline())
>   if op == str(d):
>   out == one / two print("the answer is %s" % out)
>   elif op == "m":
>   out == one * two print("the answer is %s" % out)
>   elif op == "s":
>   out == one - two print("the answer is %s" % out)
>   elif op == "p":
>   out == one + two print("the answer is %s" % out)
>   else:
>   print("huh")

a() is a function, but I can see nothing in the code that invokes the 
function a()

Ignore the comment about needing to define the type of file on the first 
line on linux, it's a red herring. You only need to do that (and possibly 
chmod the file) on a *nix system if you want to execute it directly as a 
command, rather than by calling the interpreter on it.

I suspect that if you remove the line:

"def a():"

and un-indent the rest of the text, the program will run just fine.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need Help with Programming Science Project

2014-01-25 Thread Denis McMahon
On Fri, 24 Jan 2014 20:58:50 -0800, theguy wrote:

> I know. I'm kind of ashamed of the code, but it does the job I need it
> to up to a certain point

OK, well first of all take a step back and look at the problem.

You have n exemplars, each from a known author.

You analyse each exemplar, and determine some statistics for it.

You then take your unknown sample, determine the same statistics for the 
unknown sample.

Finally, you compare each exemplar's stats with the sample's stats to try 
and find a best match.

So, perhaps you want a dictionary of { author: statistics }, and a 
function to analyse a piece of text, which might call other functions to 
get eg avg words / sentence, avg letters / sentence, avg word length, and 
the sd in each, and the short word ratio (words <= 3 chars vs words >= 4 
chars) and some other statistics.

Given the statistics for each exemplar, you might store these in your 
dictionary as a tuple.

this isn't python, it's a description of an algorithm, it just looks a 
bit pythonic:

# tuple of weightings applied to different stats
stat_weightings = ( 1.0, 1.3, 0.85, .. )

def get_some_stat( t ):
# calculate some numerical statistic on a block of text
# return it

def analyse( f ):
text = read_file( f )
return ( get_some_stat( text ), .. )

exemplars = {}

for exemplar_file in exemplar_files:
exemplar_data[author] = analyse( exemplar_file )

sample_data = analyse( sample_file )

scores = {}

tmp = 0
x = 0

# score for a piece of work is sum of ( diff of stat * weighting )
# for all the stats, lower score = closer match
for author in keys( exemplar_data ):
for i in len( exemplar_data[ author ] ):
tmp = tmp + sqrt( exemplar_data[ author ][ i ] - 
sample_data[ i ] ) * stat_weightings( i )
scores[ author ] = tmp
if tmp > x:
x = tmp

names = []

for author in keys( scores ):
if scores[ author ] < x:
x = scores[ author ]
names = [ author ]
elif scores[ author ] == x:
names.append( [ author ] )

print "the best matching author(s) is/are: ", names

Then all you have to do is find enough ways to calculate stats, and the 
magic coefficients to use in the stat_weightings

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: should I transfer 'iterators' between functions?

2014-01-25 Thread Ned Batchelder

On 1/25/14 1:37 AM, [email protected] wrote:

take the following as an example, which could work well.
But my concern is, will list 'l' be deconstructed after function return? and 
then iterator point to nowhere?

def test():
 l = [1, 2, 3, 4, 5, 6, 7, 8]
 return iter(l)
def main():
 for i in test():
 print(i)




The two things to understand here are names, and values.  When you leave 
the function test, the name l goes away, because it is a locally scoped 
name.  It referred to a value, your list.  But values have reference 
counts, and are not reclaimed until their reference count drops to zero.


Your function is returning a value, a listiterator, and that 
listiterator refers to the list, so the list won't be reclaimed.


Names have scopes but no types.  Values have types, but no scope.  They 
live as long as they are referred to by something.


This is covered in more detail here: 
http://nedbatchelder.com/text/names.html



--
Ned Batchelder, http://nedbatchelder.com

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


Re: should I transfer 'iterators' between functions?

2014-01-25 Thread Ned Batchelder

On 1/25/14 1:37 AM, [email protected] wrote:

take the following as an example, which could work well.
But my concern is, will list 'l' be deconstructed after function return? and 
then iterator point to nowhere?

def test():
 l = [1, 2, 3, 4, 5, 6, 7, 8]
 return iter(l)
def main():
 for i in test():
 print(i)




One more thing: there's no need to call iter() explicitly here.  Much 
more common than returning an iterator from a function is to return an 
iterable.  Your code will work exactly the same if you just remove the 
iter() call:


def test():
l = [1, 2, 3, 4, 5, 6, 7, 8]
return l
def main():
for i in test():
print(i)


--
Ned Batchelder, http://nedbatchelder.com

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


Re: should I transfer 'iterators' between functions?

2014-01-25 Thread Peter Otten
Ned Batchelder wrote:

> On 1/25/14 1:37 AM, [email protected] wrote:
>> take the following as an example, which could work well.
>> But my concern is, will list 'l' be deconstructed after function return?
>> and then iterator point to nowhere?
>>
>> def test():
>>  l = [1, 2, 3, 4, 5, 6, 7, 8]
>>  return iter(l)
>> def main():
>>  for i in test():
>>  print(i)
>>
>>
> 
> One more thing: there's no need to call iter() explicitly here.  Much
> more common than returning an iterator from a function is to return an
> iterable.  Your code will work exactly the same if you just remove the
> iter() call:
> 
>  def test():
>  l = [1, 2, 3, 4, 5, 6, 7, 8]
>  return l
>  def main():
>  for i in test():
>  print(i)
 
For that specific client code, yes. In the general case the difference 
matters. Iteration over an iterable starts at the beginning while iteration 
over an iterator starts at the current item:

>>> def main():
... items = test()
... print(list(zip(items, items)))
... 
>>> def test(): return range(6) # an iterable
... 
>>> main()
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
>>> def test(): return iter(range(6)) # an iterator
... 
>>> main()
[(0, 1), (2, 3), (4, 5)]
 


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


Re: Help with my 8-year old son's first program. I'm stuck!

2014-01-25 Thread justinpmullins
Thanks Peter, that did the trick.
You've got here a very happy 8-year old and a mighty relieved 46-year old!!


On Saturday, January 25, 2014 10:41:20 AM UTC, Peter Otten wrote:
> [email protected] wrote:
> 
> 
> 
> > My son is learning Python and I know nothing about computers.
> 
> > He's written a simple calculator program that doesn't work. 
> 
> 
> 
> Normally you are supposed to explain what you or your son expect and what 
> 
> you get instead. If Python ends with an error you should paste that into 
> 
> your message, e. g.:
> 
> 
> 
> Traceback (most recent call last):
> 
>   File "calculator.py", line 29, in 
> 
> a()
> 
>   File "calculator.py", line 14, in a
> 
> if op == str(d):
> 
> NameError: global name 'd' is not defined
> 
> 
> 
> Also, we need to know if you are using Python 2 or Python 3. Sometimes even 
> 
> the exact version is important. You can find it out with
> 
> 
> 
> $ python3 -V
> 
> Python 3.2.2
> 
> 
> 
> > For the life
> 
> > of me, I can't see why. Any help gratefully received. Here's his code:
> 
> 
> 
> > def a():
> 
> > import sys
> 
> > print("welcome to the calculation")
> 
> > print("please type a number")
> 
> > one = int(sys.stdin.readline())
> 
> > print("type d for division,")
> 
> > print("type m for multiplication,") 
> 
> > print("type s for subtraction,")
> 
> > print("and type p for plus")
> 
> > op = (sys.stdin.readline())
> 
> > print("%s selected" % op)
> 
> > print("please enter another number")
> 
> > two = int(sys.stdin.readline())
> 
> > if op == str(d):
> 
> 
> 
> The name d is defined nowhere in your script. That line should be
> 
> 
> 
>   if op == "d":
> 
> 
> 
> similar to the `elif`s that follow.
> 
> 
> 
> > out == one / two
> 
> 
> 
> You want to assign to out but you are actually comparing out to one / two. 
> 
> Change the line (and similar lines below) to a single =, e. g.
> 
>   out = one / two
> 
> 
> 
> > print("the answer is %s" % out)
> 
> > elif op == "m":
> 
> > out == one * two
> 
> > print("the answer is %s" % out)
> 
> > elif op == "s":
> 
> > out == one - two
> 
> > print("the answer is %s" % out)
> 
> > elif op == "p":
> 
> > out == one + two
> 
> > print("the answer is %s" % out)
> 
> > else:
> 
> > print("huh")
> 
> 
> 
> Change the above line to
> 
> 
> 
>   print("Unknown op=%r" % op) 
> 
> 
> 
> and add a function invocation
> 
> 
> 
> a()
> 
> 
> 
> > Where is he going wrong?
> 
> > Many thanks in advance
> 
> 
> 
> When you run the script with my modifications
> 
> 
> 
> $ python3 calculator.py 
> 
> welcome to the calculation
> 
> please type a number
> 
> 10
> 
> type d for division,
> 
> type m for multiplication,
> 
> type s for subtraction,
> 
> and type p for plus
> 
> m
> 
> m
> 
>  selected
> 
> please enter another number
> 
> 20
> 
> Unknown op='m\n'
> 
> 
> 
> you see that what you supposed to be an "m" is actually an "m" followed by a 
> 
> newline. The readline() method reads a line including the final newline.
> 
> You can remove that by changing the line
> 
> 
> 
> op = (sys.stdin.readline())
> 
> 
> 
> to
> 
> 
> 
> op = sys.stdin.readline().strip()
> 
> 
> 
> but a more straightforward approach would be to replace all occurences of
> 
> 
> 
> sys.stdin.readline()
> 
> 
> 
> with 
> 
> 
> 
> input() # if you are using Python 3
> 
> 
> 
> or
> 
> 
> 
> raw_input() # if yo are using Python 2.

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


Re: Need Help with Programming Science Project

2014-01-25 Thread Rustom Mody
On Saturday, January 25, 2014 8:12:20 PM UTC+5:30, Dennis Lee Bieber wrote:
> 
>   Heck, at the very least turn all those _99 variables into single
> lists The posted code looks like something from 1968 K&K BASIC.

Yes thats correct.

My suggestion of data-files is a second step.

A first step is just converting to using internal (python) data structures.
[And not 1968 BASIC scalars!]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand this moji-bake

2014-01-25 Thread Peter Pearson
On Sat, 25 Jan 2014 17:08:56 +1100, Chris Angelico  wrote:
> On Sat, Jan 25, 2014 at 3:37 PM, Steven D'Aprano
> wrote:
>> But using Python 2.7, I get a really bad case of moji-bake:
>>
>> [steve@ando ~]$ python2.7 -c "print u'ñøλπйж'"
>> ñøλÏйж
>
> What's 2.7's default source code encoding? I thought it was ascii, but
> maybe it's assuming (in the absence of a magic cookie) that it's
> Latin-1.
>
> ChrisA

I seem to be getting the same behavior as Steven:

$ python2.7 -c "print u'ñøλπйж'"
ñøλπйж
$ python2.7 -c "import sys; print(sys.stdout.encoding)"
UTF-8
$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE=C
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
$ python2.7 -c "import sys; print(sys.stdin.encoding)"
UTF-8

Also, my GNOME Terminal 3.4.1.1 character encoding is "Unicode (UTF-8)".

HTH

-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
https://mail.python.org/mailman/listinfo/python-list


Pls help me...I want to save data to my database but I am unable to

2014-01-25 Thread Max Cuban
This is my first programming pet project. I have the following script that
extracts links from specific sites and display them on the web(via django).
The script work fine but I'm unable to save any stuff in my database.

Hence if I run the code, I get the output I want but then it always
extracts only new content. I will rather want to have the content scrapped
earlier saved to the database so that on subsequent run, it only scrap and
append ONLY new links to the list.
[ ]
Any help will be appreciated.
[]
# Create your views here.
from django.template.loader import get_template
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render_to_response
from django.template import Context
from bs4 import BeautifulSoup
import urllib2, sys
import urlparse
import re
from datetime import date, datetime
from listing.models import jobLinks


def businessghana():
site = "http://www.businessghana.com/portal/jobs";
hdr = {'User-Agent' : 'Mozilla/5.0'}
req = urllib2.Request(site, headers=hdr)
jobpass = urllib2.urlopen(req)
soup = BeautifulSoup(jobpass)
for tag in soup.find_all('a', href = True):
tag['href'] = urlparse.urljoin('
http://www.businessghana.com/portal/', tag['href'])
return map(str, soup.find_all('a', href =
re.compile('.getJobInfo')))

def tonaton():
site = "http://tonaton.com/en/job-vacancies-in-ghana";
hdr = {'User-Agent' : 'Mozilla/5.0'}
req = urllib2.Request(site, headers=hdr)
jobpass = urllib2.urlopen(req)
soup = BeautifulSoup(jobpass)
result = []
# next two lines make all the links in the soup absolute
for tag in soup.find_all('a', href=True):
tag['href'] = urlparse.urljoin('http://www.tonaton.com',
tag['href'])
# assign all 'h2' tags to 'jobs'. The 'h2'tag contains the required
links
jobs = soup.find_all('h2')
# Loop through the 'h2' tags and extract all the links
for h2 in soup.find_all('h2'):
n = h2.next_element
if n.name == 'a':  result.append(str(n))
return result

def jobscomgh():
site = "http://jobs.com.gh";
hdr = {'User-Agent' : 'Mozilla/5.0'}
req = urllib2.Request(site, headers=hdr)
jobpass = urllib2.urlopen(req)
soup = BeautifulSoup(jobpass)
return map(str, soup.find_all('a', href =
re.compile('.display-job')))

businessghana_links = businessghana()
tonaton_links = tonaton()
jobscomgh_links = jobscomgh()

def all_links():
return (businessghana_links + tonaton_links + jobscomgh_links)

def save_new_links(all_links):
current_links = jobLinks.objects.all()
for i in all_links:
if i not in current_links:
jobLinks.objects.create(url=i)

def this_week_links(all_links):
return jobLinks.objects.filter(date__gte =
datetime.timedelta(days=-7))

save_new_links(all_links)
this_week_links(all_links)

def display_links(request):
name = all_links()
paginator = Paginator(name, 25)
page = request.GET.get('page')
try:
name = paginator.page(page)
except PageNotAnInteger:
name = paginator.page(1)
except EmptyPage:
name = paginator.page(paginator.num_pages)


return render_to_response('jobs.html', {'name' : name})
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand this moji-bake

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 4:56 AM, Peter Pearson  wrote:
> $ python2.7 -c "import sys; print(sys.stdin.encoding)"
> UTF-8

This isn't from stdin, though, it's about the interpretation of the
bytes of source code without a magic cookie.

According to PEP 263 [1], the default encoding should have become
"ascii" as of Python 2.5. That's what puzzles me.

ChrisA

[1] http://www.python.org/dev/peps/pep-0263/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pls help me...I want to save data to my database but I am unable to

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 6:00 AM, Max Cuban  wrote:
> This is my first programming pet project. I have the following script that
> extracts links from specific sites and display them on the web(via django).
> The script work fine but I'm unable to save any stuff in my database.
>
> Hence if I run the code, I get the output I want but then it always extracts
> only new content. I will rather want to have the content scrapped earlier
> saved to the database so that on subsequent run, it only scrap and append
> ONLY new links to the list.

At what point are you saving anything to the database? I'm not seeing
it. This may be a consequence of there being simply too much code for
the post - when you have a problem, try to post the smallest amount of
code necessary to demonstrate that problem. If your problem is saving
stuff to the database, create a project that simulates generating
links (maybe just hard-codes a dozen of them), and tries to save them.
Often, the exercise of making the small version actually shows you
where the problem is, right there; and if it doesn't, it's much easier
for us to see and help you. In this case, after reading your opening
paragraph, the very first thing I did was to scan your code for a
"commit" operation - but I couldn't find one, and I can't find any
database work.

BTW, the word you want here is "scrape" (other tenses "scraping" and
"scraped"). Scrapping ("scrap", "scrapped" - pronounced with a short
'a' sound like "flapping") is destruction and disposal - "the wreckers
are scrapping hundreds of smashed cars". Scraping (pronounced with a
long 'a' sound like "trading" [1]) is running a tool over something to
clean something else off - "every winter, car owners spend innumerable
hours scraping ice off their windscreens" - and this is the word
that's been picked up for "screen scraping" and related terms.

Hope that helps!

ChrisA

[1] I could go into detail about single and double consonants if
anyone's curious, but I don't think it'd help)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand this moji-bake

2014-01-25 Thread Oscar Benjamin
On 25 January 2014 04:37, Steven D'Aprano
 wrote:
>
> But using Python 2.7, I get a really bad case of moji-bake:
>
> [steve@ando ~]$ python2.7 -c "print u'ñøλπйж'"
> ñøλÏйж
>
> However, interactively it works fine:
>
> [steve@ando ~]$ python2.7 -E
> Python 2.7.2 (default, May 18 2012, 18:25:10)
> [GCC 4.1.2 20080704 (Red Hat 4.1.2-52)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 print u'ñøλπйж'
> ñøλπйж
>
> This occurs on at least two different machines, one using Centos and the
> other Debian.

Same for me. It's to do with using a u literal:

$ python2.7 -c "print('ñøλπйж')"
ñøλπйж
$ python2.7 -c "print(u'ñøλπйж')"
ñøλπйж
$ python2.7 -c "print(repr('ñøλπйж'))"
'\xc3\xb1\xc3\xb8\xce\xbb\xcf\x80\xd0\xb9\xd0\xb6'
$ python2.7 -c "print(repr(u'ñøλπйж'))"
u'\xc3\xb1\xc3\xb8\xce\xbb\xcf\x80\xd0\xb9\xd0\xb6'

$ python2.7
Python 2.7.5+ (default, Sep 19 2013, 13:49:51)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> b='\xc3\xb1\xc3\xb8\xce\xbb\xcf\x80\xd0\xb9\xd0\xb6'
>>> print(b)
ñøλπйж
>>> s=u'\xc3\xb1\xc3\xb8\xce\xbb\xcf\x80\xd0\xb9\xd0\xb6'
>>> print(s)
ñøλπйж
>>> print(s.encode('latin-1'))
ñøλπйж
>>> import sys
>>> sys.getdefaultencoding()
'ascii'

It works in the interactive prompt:

>>> s = 'ñøλπйж'
>>> print(s)
ñøλπйж
>>> s = u'ñøλπйж'
>>> print(s)
ñøλπйж

But the interactive prompt has an associated encoding:

>>> import sys
>>> sys.stdout.encoding
'UTF-8'

If I put it into a utf-8 file with no encoding declared I get a SyntaxError:
$ cat tmp.py
s = u'ñøλπйж'
print(s)
oscar@tonis-laptop:~$ python2.7 tmp.py
  File "tmp.py", line 1
SyntaxError: Non-ASCII character '\xc3' in file tmp.py on line 1, but
no encoding declared; see http://www.python.org/peps/pep-0263.html for
details

If I add the encoding declaration it works:

oscar@tonis-laptop:~$ vim tmp.py
oscar@tonis-laptop:~$ cat tmp.py
# -*- coding: utf-8 -*-
s = u'ñøλπйж'
print(s)
oscar@tonis-laptop:~$ python2.7 tmp.py
ñøλπйж
oscar@tonis-laptop:~$

So I'd say that your original example should be a SyntaxError with
Python 2.7 but instead it implicitly uses latin-1.


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


Pls help me...I want to save scraped data automatically to my database(cleaner version)

2014-01-25 Thread Max Cuban
I have asked this question earlier but this should make more sense than the
earlier version and I don't want anyone who could potentially helped to be
put off by the initial mess even if I updated it with my cleaner version as
a reply

I want to save the links scraped to be save in my database so that on
subsequent run, it only scrapes and append only new links to the list.

This is my code below but  at the end of the day my database is empty. What
changes can I make to overcome this? Thanks in advance


from django.template.loader import get_template
from django.shortcuts import render_to_response
from bs4 import BeautifulSoup
import urllib2, sys
import urlparse
import re
from listing.models import jobLinks
 #this function extract the links
def businessghana():
site = "http://www.businessghana.com/portal/jobs";
hdr = {'User-Agent' : 'Mozilla/5.0'}
req = urllib2.Request(site, headers=hdr)
jobpass = urllib2.urlopen(req)
soup = BeautifulSoup(jobpass)
for tag in soup.find_all('a', href = True):
tag['href'] = urlparse.urljoin('
http://www.businessghana.com/portal/', tag['href'])
return map(str, soup.find_all('a', href =
re.compile('.getJobInfo')))
 # result from businssghana() saved to a variable to make them iterable as
a list
all_links  = businessghana()

#this function should be saving the links to the database unless the link
already exist
def save_new_links(all_links):
current_links = jobLinks.objects.all()
for i in all_links:
if i not in current_links:
jobLinks.objects.create(url=i)

# I called the above function here hoping that it will save to database
save_new_links(all_links)

# return my httpResponse with this function
def display_links(request):
name = all_links()
return render_to_response('jobs.html', {'name' : name})
 My django models.py looks like this:
 from django.db import models class jobLinks(models.Model): links =
models.URLField() pub_date = models.DateTimeField('date retrieved') def
__unicode__(self): return self.links
-- 
https://mail.python.org/mailman/listinfo/python-list


Can't get sqlite3.Row working: keyword lookup doesn't work

2014-01-25 Thread lgabiot

Hello,

using Python 2.7.6

I try to access a sqlite database using keyword lookup instead of 
position (much more easy to maintain code), but it always fail, with the 
error:

Index must be int or string

I have created the database, populated it, and here is the code that 
tries to retrieve the information:


with sqlite3.connect(mydbPath) as db: # open the database
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute("SELECT * FROM files")

for row in cursor.fetchall():
print(row.keys())
print(row["filename"])


result is:

['filename', 'filepath', 'filetag', 'PROJECT', 'SCENE', 'TAKE', 'TAPE', 
'CIRCLED', 'FILE_UID', 'UBITS', 'TOTAL_FILES', 'FAMILY_UID', 'track_1', 
'track_2', 'track_3', 'track_4', 'track_5', 'track_6', 'track_7', 
'track_8', 'track_9', 'track_10', 'track_11', 'track_12', 'NOTE', 
'duration', 'BWF_ORIGINATION_DATE', 'TIMECODE_FLAG', 'TIMECODE_RATE', 
'FILE_SAMPLE_RATE', 'AUDIO_BIT_DEPTH', 'DIGITIZER_SAMPLE_RATE', 
'TIMESTAMP_SAMPLE_RATE', 'TIMESTAMP_SINCE_MIDNIGHT', 'is_Short', 
'is_MS', 'is_renamed_MS', 'WF_created', 'max_level', 'is_silent', 
'is_silent_moved', 'silent_path', 'is_WS', 'is_WS_copied', 'CSV_made', 
'is_cantar', 'is_sound_devices', 'exist']


error =>  Index must be int or string

What is wrong?

thanks a lot.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand this moji-bake

2014-01-25 Thread Steven D'Aprano
On Sat, 25 Jan 2014 17:08:56 +1100, Chris Angelico wrote:

> On Sat, Jan 25, 2014 at 3:37 PM, Steven D'Aprano
>  wrote:
>> But using Python 2.7, I get a really bad case of moji-bake:
>>
>> [steve@ando ~]$ python2.7 -c "print u'ñøλπйж'" ñøλÏйж
> 
> What's 2.7's default source code encoding? I thought it was ascii, but
> maybe it's assuming (in the absence of a magic cookie) that it's
> Latin-1.

I think that's it! Python 2.7 ought to raise a SyntaxError, since there's 
no source encoding declared, while Python 3.3 defaults to UTF-8 which is 
the same as my terminal. If there's a bug, it is that Python 2.7 doesn't 
raise SyntaxError when called with -c and there are non-ASCII literals in 
the source. Instead, it seems to be defaulting to Latin-1, hence the moji-
bake.

Thanks to everyone who responded!


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


Re: Trying to understand this moji-bake

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 1:04 PM, Steven D'Aprano
 wrote:
> If there's a bug, it is that Python 2.7 doesn't
> raise SyntaxError when called with -c and there are non-ASCII literals in
> the source. Instead, it seems to be defaulting to Latin-1, hence the moji-
> bake.

That might well be a bug! I was reading the PEP, which was pretty
clear about it needing to be ASCII by default. It's not so clear about
-c but I would expect it to do the same.

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


Re: Python declarative

2014-01-25 Thread Steven D'Aprano
On Sat, 25 Jan 2014 09:18:44 +0200, Frank Millman wrote:

> I have realised that we unlikely to come to an agreement on this in the
> near future, as our philosophies are completely different.
> 
> You [Chris Angelo] have stated that your objective is to express as
> much as possible in Python code.
> 
> I have stated that my objective is to express as little as possible in
> Python code.

Interesting perspective.


> We would have to resolve that difference of opinion first, before
> discussing our respective approaches in detail, and that is way beyond
> the scope of this thread.
> 
> As a brief example of my approach, here is how I would write your simple
> 'About' box.
> 
> Here is your version -
> 
> mainwindow = GTK2.Window(0)->add(GTK2.Vbox(0,0)
> ->add(GTK2.Label("About Gypsum: big long multi-line string"))
> ->add(GTK2.HbuttonBox()
> ->add(GTK2.Button("Close"))
> ->add(GTK2.Button("Foobar"))
> )
> );

That's not Python code, but it's reasonably concise and readable. (By the 
way, what language is it?) The meaning is fairly obvious, and it's all 
pretty simple. I'd like to see a more human readable GUI designer 
language:

# hypothetical code in a DSL for creating GUI elements
create new window mainwindow
with mainwindow
add vbox at 0,0
add label "About Gypsum: big long multi-line string"
add hbuttonbox
add button "Close"
add button "Foobar"

but what you've got there is okay. Seven lines of readable code.


> Here is my version -
> 
> 
>   
>   
>   
>   
>   
> 
> 
> 
>   
>   
>
>   
>
>   
>   
> 
>   
>  btn_enabled="true" btn_validate="false" btn_default="true">
> 
>   
>  btn_enabled="true" btn_validate="false" btn_default="false">
> 
>   
> 
> 
> 
> 
>   
> 
> 
>   
> 
>   
> 

Thirty. Seven. Lines. Of. XML.

You've got to be kidding me. How can you *possibly* prefer that? 

First rule of XML: it is not human-writable. It's barely human-readable. 
It's a *document* interchange language which happens to use mostly human-
readable elements, which is not the same thing at all. It's designed to 
be machine written. Using XML for *data* is abusive to both the XML 
design goals and to the poor schmuck who has to read your config file. 
Using XML *as a programming language* is not just abuse, it's getting 
into grievous bodily harm territory.

Here's a simple programming expression, familiar to most people, common 
to hundreds of programming languages:

3+4*5

Here it is written as XML:

345


Source:
http://www.ibm.com/developerworks/xml/library/x-sbxml/index.html

More here:

http://www.codinghorror.com/blog/2008/05/xml-the-angle-bracket-tax.html
http://myarch.com/why-xml-is-bad-for-humans/


If you expect a human being to routinely *read*, let alone *write*, XML 
in preference to some real programming language, that is a horrible, 
horrible thing. Using XML as an internal, machine-generated, format not 
intended for humans is not too bad. Anything else is abusive.



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


Re: Python declarative

2014-01-25 Thread Mark Lawrence

On 26/01/2014 02:33, Steven D'Aprano wrote:

Here's a simple programming expression, familiar to most people, common
to hundreds of programming languages:

3+4*5

Here it is written as XML:

345

Source:
http://www.ibm.com/developerworks/xml/library/x-sbxml/index.html

More here:

http://www.codinghorror.com/blog/2008/05/xml-the-angle-bracket-tax.html
http://myarch.com/why-xml-is-bad-for-humans/

If you expect a human being to routinely *read*, let alone *write*, XML
in preference to some real programming language, that is a horrible,
horrible thing. Using XML as an internal, machine-generated, format not
intended for humans is not too bad. Anything else is abusive.



If I worked as a consultant I'd much prefer the XML version as I'd be 
able to charge much more on the grounds that I'd done much more, hoping 
that the people paying didn't bother with design reviews or the like :)


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: Trying to understand this moji-bake

2014-01-25 Thread Terry Reedy

On 1/25/2014 2:13 PM, Chris Angelico wrote:

On Sun, Jan 26, 2014 at 4:56 AM, Peter Pearson  wrote:

$ python2.7 -c "import sys; print(sys.stdin.encoding)"
UTF-8


This isn't from stdin, though, it's about the interpretation of the
bytes of source code without a magic cookie.

According to PEP 263 [1], the default encoding should have become
"ascii" as of Python 2.5. That's what puzzles me.


I believe it is actually (but unofficially) latin-1 so that latin-1 
accented chars can be used in identifiers even though only ascii is 
officially supported.


--
Terry Jan Reedy

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


Re: Python declarative

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 1:33 PM, Steven D'Aprano
 wrote:
>> Here is your version -
>>
>> mainwindow = GTK2.Window(0)->add(GTK2.Vbox(0,0)
>> ->add(GTK2.Label("About Gypsum: big long multi-line string"))
>> ->add(GTK2.HbuttonBox()
>> ->add(GTK2.Button("Close"))
>> ->add(GTK2.Button("Foobar"))
>> )
>> );
>
> That's not Python code, but it's reasonably concise and readable. (By the
> way, what language is it?) The meaning is fairly obvious, and it's all
> pretty simple.

It's Pike, and the above example is pure Pike without any of my own
helpers. If you fire up Pike's interactive mode and type two commands
"GTK2.setup_gtk();" and "start backend" first, you can paste that in
and it'll create you a window. (It won't DO anything, but it'll sit
there looking like a window.) It tends to get a little verbose after a
while (hence the need for helper functions to combat the complexity),
but the advantage of this system is that it took me absolutely zero
code. I didn't have to write any framework.

> I'd like to see a more human readable GUI designer
> language:
>
> # hypothetical code in a DSL for creating GUI elements
> create new window mainwindow
> with mainwindow
> add vbox at 0,0
> add label "About Gypsum: big long multi-line string"
> add hbuttonbox
> add button "Close"
> add button "Foobar"
>
> but what you've got there is okay. Seven lines of readable code.

Sure. That would make reasonable sense, as a DSL. And, in fact, if I
were making a Python GUI, I would want to add something that would let
me do it that way - at least compared to PyGTK, which insists on every
box getting a temporary name, since the add() methods don't chain. But
that's a cost, that has to be written. I'm happy with the no-code
version to start with. Now, with something as complicated as the
character sheet, well, that's different. I think if I did all the
charsheet code as pure no-helpers Pike, it would be a dozen pages of
code and indented about fifty tabs. At that point, it's worth putting
some effort into taming the beast :) Here's an actual example from the
charsheet:

GTK2.Hbox(0,10)->add(GTK2Table(({
({"Name",ef("name",12),0,0,"Char level",num("level",8)}),
({"Race",ef("race",8),"HD",ef("race_hd"),"Experience",num("xp",8)}),
({"Class",ef("class1",12),"Level",num("level1"),"To next
lvl",calc("`+(@enumerate(level,1000,1000))-xp")}),

({"Class",ef("class2",12),"Level",num("level2"),"Size",select("size",sizes)}),
({"Class",ef("class3",12),"Level",num("level3"),
"Grapple",calc(grapple_formula,"grapple","string")
}),
({"Class",ef("class4",12),"Level",num("level4")}),
}))->set_col_spacings(4))
->add(GTK2.Frame("Wealth")->add(GTK2Table(({
({"Platinum",num("wealth_plat",7)}),
({"Gold",num("wealth_gold",7)}),
({"Silver",num("wealth_silver",7)}),
({"Copper",num("wealth_copper",7)}),
({"Total 
gp",calc("(wealth_plat*1000+wealth_gold*100+wealth_silver*10+wealth_copper)/100")}),
}


It's a mix of basic Pike and GTK functions (GTK2.Frame is one of the
standard widgets) and helpers (num, ef, and calc) that return widgets,
maybe with child widgets. GTK2Table takes an array and plops
everything into it at appropriate locations. I use that function
*everywhere* in the charsheet - mainly because I was porting from a
spreadsheet, but D&D character sheets are inherently tabular.

(Note that I've reformatted this a bit from the original, and it might
be disrupted a bit by the email/newsgroup format. In the original,
this is all a few tabs in, but as long as your editor isn't wrapping
the lines, it's pretty readable.)

At what point is it a DSL rather than just "Pike code with helper
functions"? This is particularly true with Python code; it wouldn't be
hard to make a DSL that's derived from Python.

(By the way, your translation "add a vbox at 0,0" isn't accurate; the
0,0 are parameters to the Vbox itself, being the homogenous flag (if
it's nonzero, it forces its children to the same height and/or width,
but 0 means each child gets what it asks for) and the padding (0 puts
children hard up against one another, nonzero puts that much room
between them). A window has only a single child, which occupies its
entire space; that's why it's conventional to add a layout manager as
the one child, and then add multiple children to that. Means the
window needn't care about the minutiae of child positioning. But if
you call that "add a vbox 0,0", that'd work fine; and if you're making
a DSL, I'd make 0,0 the defaults and say "add a vbox padding 10" if I
want to override.)

The only problem with your DSL as I see it is that it doesn't mark the
beginning and end of child widget layouts. This needs to be a tree.
But Python already has a notation for that: indent! So if the two
buttons are indented, they'll be inside the hbuttonbox (which is a
type of horizontal box), which is within the vertical box (again,
indent everything that's inside it), which is within the

Re: Python declarative

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 1:45 PM, Mark Lawrence  wrote:
> If I worked as a consultant I'd much prefer the XML version as I'd be able
> to charge much more on the grounds that I'd done much more, hoping that the
> people paying didn't bother with design reviews or the like :)

And that's very true. If someone wants something infinitely
customizeable, the best solution might be an empty file with a shebang
at the top - but that's hardly something you can charge oodles for.
This is where soft-coding comes from.

http://thedailywtf.com/Articles/Soft_Coding.aspx

The business logic examples given there are best served by hard code.
Suppose you need to calculate this-value plus that-value times
other-value; is there any difference between writing that in Python
(ugh, that's hard code!) and putting the formula in a config file,
where it'll get parsed and evaluated (oh, that's a config file, that's
fine)? As you'll see in my other post, there's a formula evaluator
routine there; it takes a string of code and compiles it:

(wealth_plat*1000+wealth_gold*100+wealth_silver*10+wealth_copper)/100

It's straight code, and it's embedded. If ever the rules change, I can
edit the code. For instance, here's the D&D Fourth Edition version of
that:

(wealth_plat*1+wealth_gold*100+wealth_silver*10+wealth_copper)/100

Should the value of a platinum coin be moved out into a config file?
Maybe. MAYBE. Should the value of a silver piece be? Definitely not!
There's no use-case for silver pieces being worth anything other than
ten copper. If and when there is one, the code can simply be edited.
There is no value in soft-coding this formula.

Code isn't something to be afraid of. It's just text files like any
other. After all, Python code is a config file for /usr/bin/python, so
if you want to change what Python does, just edit its config file!

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


Re: Python declarative

2014-01-25 Thread Rustom Mody
On Sunday, January 26, 2014 9:36:15 AM UTC+5:30, Chris Angelico wrote:
> Code isn't something to be afraid of. It's just text files like any
> other. After all, Python code is a config file for /usr/bin/python, so
> if you want to change what Python does, just edit its config file!

Windows stores configuration in the registry -- by fiat
Linux (posix) stores configuration in /etc + ~/.files -- by convention

Which do you think is preferable?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python declarative

2014-01-25 Thread Chris Angelico
On Sun, Jan 26, 2014 at 3:47 PM, Rustom Mody  wrote:
> On Sunday, January 26, 2014 9:36:15 AM UTC+5:30, Chris Angelico wrote:
>> Code isn't something to be afraid of. It's just text files like any
>> other. After all, Python code is a config file for /usr/bin/python, so
>> if you want to change what Python does, just edit its config file!
>
> Windows stores configuration in the registry -- by fiat
> Linux (posix) stores configuration in /etc + ~/.files -- by convention
>
> Which do you think is preferable?

Not exclusively, in either case. Many many things are config files of
various sorts. The terms of the GPL specifically state that a GPL'd
language does not enforce that code written in it is GPL'd, because
it's just (to the GPL code) data files.

Plenty of Windows programs store config files outside the registry.

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


Re: Python declarative

2014-01-25 Thread Frank Millman

"Steven D'Aprano"  wrote in message 
news:[email protected]...
> On Sat, 25 Jan 2014 09:18:44 +0200, Frank Millman wrote:
>
>> I have realised that we unlikely to come to an agreement on this in the
>> near future, as our philosophies are completely different.
>>
>> You [Chris Angelo] have stated that your objective is to express as
>> much as possible in Python code.
>>
>> I have stated that my objective is to express as little as possible in
>> Python code.
>
> Interesting perspective.
>

[...]

I did not really want to continue this, but I have to respond to that.

There is a sub-context within which I made my statement.

Here is a quote from one of my earlier posts -

> Each form definition is stored as gzip'd XML in a database, and linked to 
> the
> menu system. There is just one python program that responds to the 
> selection
> of a menu option, retrieves the form from the database, unpacks it and 
> runs it.

I do not expect anyone to read or edit the XML - it is just a storage 
format. I am sure it could be done in JSON or YAML as well.

One objective is to make it easy for non-programmers to modify forms and 
create new ones. I showed a screenshot earlier that illustrated a 'button' 
definition.

Frank



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