[Tutor] superscript with easydialogs

2007-08-06 Thread Ben
Hi,

I have been working with easydialogs module lately especially the progress
bar (for Windows). I would like to put superscript text like (TM) to (™)
when calling the label function. I have been looking around the net for some
info, and can not find anything about it . It makes me wonder if python
itself allow to  the superscript.  Any suggestions? Thanks in advance.

-Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hi

2007-03-16 Thread Ben

Hi all,

I am a newbie to Python. I just learned python for two weeks, and I have to
say I feel very comfortable with the language. The stumbling blocks for me
is the development of the GUI. I am currently learning pywin (PythonWin) to
develop a gui. But I found it is very difficult. I have been searching all
over internet on pywin tutorials, manuals or documentations, and I find
nothing good or concise for either tutorials or documentations about pywin.
Is anyone can point me where I can find a good tutorial about pywin for
someone like me? I will really appreciate it. Thank you

-Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] threading and gui programming

2007-03-20 Thread Ben

Hi all,

I am curious about one thing. I have been doing research on gui programming.
One thing that I don't understand is why there are some examples uses
threading in the gui examples. Is there any benefits or advantages for using
the threading in the gui programming? Thanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] threading and gui programming

2007-03-20 Thread Ben

That makes sense. I am a newbie to python programming. What really confuses
me is that there are so many gui programming options for python (i.e.
pywin32, wxPython, etc). Is this means that all of these available gui
options be able to integrate with threading? Thanks.

On 3/20/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


Ben wrote:
> Hi all,
>
> I am curious about one thing. I have been doing research on gui
> programming. One thing that I don't understand is why there are some
> examples uses threading in the gui examples. Is there any benefits or
> advantages for using the threading in the gui programming? Thanks.

This is commonly done when a user action starts some kind of processing
that will take some time. In order for the GUI to remain responsive, the
long process must be in a different thread. In general, the GUI will not
respond to new input until the event handler for the user action returns.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pywin DoModal vs CreateWindow

2007-03-21 Thread Ben

Recently my friend ask me for help on pywin32 gui programming. There is one
thing that throw us off (Note. Both of us don't have any mfc background and
we are newbie in python). When the "DoModal" is called, the gui will stay in
loop. It is different when the "CreateWindow" is called. If we run the
program from command prompt, the gui won't stay in loop (or basically just
blink for a moment and disappear). It is different if we run the program
from "PythonWin" program. Can someone explain this for us? It cause a lot of
confusion. And what should we do to make the gui stay in loop if we used
"CreateWindow" and called it from command prompt. We really appreciate for
any help. Thanks in advance.

Below is the snippet code that we used for testing:
Note: Codes credits to Mark Hammond.

import win32ui
import win32con
from pywin.mfc.dialog import Dialog

d = Dialog (win32ui.IDD_SIMPLE_INPUT)

print d
print d._obj_

d.CreateWindow ()
#d.ShowWindow (win32con.SW_SHOWNORMAL)
button = d.GetDlgItem (win32ui.IDC_PROMPT1)
print "button: ", button
button.SetWindowText ("Hello from Python")
d.SetWindowText ("Python is awesome")
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] threading and gui programming

2007-03-23 Thread Ben

Hi Tony,

Thank you very much for your pointer. I think I understand what are you
explaining to me. Do you mind give me some code examples? I am still trying
to grasp the gui programming overall. And it is really over my head. I
really appreciate your help. Thank you

-Ben

On 3/23/07, Tony Cappellini <[EMAIL PROTECTED]> wrote:


Hi Ben,

I've just started gui programming in Python, and my first app needed a
little threading.
It's over my head, so a friend gave me an example, and I integrated it.

The reason for threading in my example- is the same as what Kent
mentioned.

My app is a gui front end to another python program which processes files.
The file processor outputs text, and my gui displays it in a text box.
If it were not for threading, my app would freeze until the app that
I'm calling finished.

Another way to think of it- is using yourself for an example/.
If you were eating dinner, and someone in the room called your name-
you would probably turn your head or walk over to them while you were
chewing a mouthfull :-)

If you didn't respond to them until you were finished eating, they
could not finish what they were doing either.

Does that make sense?

You may not always need threading in a gui app. It just depends on
what you ar edoing, and how long it takes.



Message: 1
Date: Tue, 20 Mar 2007 14:49:50 -0400
From: Ben <[EMAIL PROTECTED]>
Subject: [Tutor] threading and gui programming
To: tutor@python.org
Message-ID:
   <[EMAIL PROTECTED]>
Content-Type: text/plain; charset="iso-8859-1"

Hi all,

I am curious about one thing. I have been doing research on gui
programming.
One thing that I don't understand is why there are some examples uses
threading in the gui examples. Is there any benefits or advantages for
using
the threading in the gui programming? Thanks.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using Python in Windows

2008-06-25 Thread Ben
Hi,

I'm trying to learn Python in Windows XP. I've been going through the
Python version of Allen Downey's open source textbook. I frequently
find that the instructions he gives don't work for me when I try to
run them in IDLE. For example, in Ch. 4 he says you should load up
GASP (http://openbookproject.net//thinkCSpy/ch04.xhtml#auto10) and
play around with it. Here's what happens when I try what he says to
do:

IDLE 1.2.2
>>> from gasp import *

Traceback (most recent call last):
 File "", line 1, in 
   from gasp import *
ImportError: No module named gasp
>>>

When I try to put all the information in a module, save it, and run
it, I get "there's an error in your program: invalid syntax", and it
highlights instance. Below is what my module looks like.

from gasp import *
begin_graphics()
Circle((200, 200), 60)
Circle instance at (200, 200) with radius 60
Line((100, 400), (580, 200))
Line instance from (100, 400) to (590, 250)
Box((400, 350), 120, 100)
Box instance at (400, 350) with width 120 and height 100
end_graphics()

Similarly, I can't get the truth table to work in the Exercises
section at the bottom of ch. 4. I'm wondering if this is because I'm
using Windows. I've tried using Ubuntu, and it doesn't display
correctly.

Thanks,
Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Using Python in Windows

2008-06-28 Thread Ben
Hmm. The instruction on adding something
gaspthe
library seems to be catered towards Linux. I've done a Google search
and
glanced at the Tutorial, the Windows FAQ (
http://www.python.org/doc/faq/windows/), ect. I don't see it in the global
module index . Installing Python
modules  goes a little over my
head...

On Sat, Jun 28, 2008 at 1:21 PM, wesley chun <[EMAIL PROTECTED]> wrote:
>>  IDLE 1.2.2
>>  >>> from gasp import *
>>
>>  Traceback (most recent call last):
>>   File "", line 1, in 
>>from gasp import *
>>  ImportError: No module named gasp
>
>
> as brian mentioned, gasp doesn't come with Python.  in fact, this very
> thread came up just last month, and here was one of my replies, but
> you can also check out the entire thread if you wish:
>
> http://mail.python.org/pipermail/tutor/2008-May/061975.html
>
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.popen doesn't give up

2004-12-02 Thread Ben Vinger
 --- Ben Vinger <[EMAIL PROTECTED]> wrote: 
>  --- Bob Gailer <[EMAIL PROTECTED]> wrote: 
> > Solutions:
> > 2 - l = os.popen(r'snmpget -Os -c ' +
> SNMPcommunity
> > + ' -v2c -r 3 ' + IP + 
> > ' ' + counter, 'r').read() Puts snmpget's output
> in
> > l.

Sorry, now I have doubts again.  Originally, I had:
I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v
2c -r 3 ' + IP + ' ' + counter, 'r')
bytes = string.split(I.read(), None)[3]

With Bob's suggestion, I have:
I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v
2c -r 3 ' + IP + ' ' + counter, 'r').read()
bytes = string.split(I, None)[3]

But is this really different?
I can add I.close() as you suggested, maybe that will
do the trick. 

Thanks
Ben




___ 
Moving house? Beach bar in Thailand? New Wardrobe? Win £10k with Yahoo! Mail to 
make your dream a reality. 
Get Yahoo! Mail www.yahoo.co.uk/10k
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Character creator program

2010-05-12 Thread Ben Millane
Ok first off here is a link to my code

http://pastie.org/956909

My problem is, that although I have the program working how I want it to work 
in general. I still have an issue with the user input section. If my user 
inputs any of the options from the menu, the program works as it should. But 
say if the user accidentally pressed enter with no option entered the program 
ends with an error message, or if they put in the incorrect number or a letter, 
it returns an error.

What I would like to happen is for a "Choice invalid, please choose another 
option" message to come up if this happens, but I am unsure how to put this in.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Character creator program

2010-05-13 Thread Ben Millane
>
> Ok, thank you everyone for the helpful replies. I am currently very new to
> both Python and programming (started looking into the whole business about 2
> weeks ago) and I know how awful my coding skills are at the moment. But,
> thanks to lists like these, I hope I can improve my skills. I will look at
> the branching tutorial for sure and add my else statement in too. Thanks
> again.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] New to programming question

2005-04-12 Thread Ben Markwell
This is an exercise from "How to think like a Computer Scientist."


The following example shows how to use concatenation and a for loop to generate an abecedarian series.  "Abecedarian" refers
to a series or list in which the elements appear in alphabetical
order.  For example, in Robert McCloskey's book Make Way for
Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack,
Nack, Ouack, Pack, and Quack.  This loop outputs these names in order:


prefixes = "JKLMNOPQ"
suffix = "ack"

for letter in prefixes:
  print letter + suffix



The output of this program is:


Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack



Of course, that's not quite right because "Ouack" and
"Quack" are misspelled.

As an exercise, modify the program to fix this error.

==

In trying to solve the problem I have come up with the following:

prefixes = 'JKLMNOPQ'
suffix = 'ack'
xsuffix = 'uack'


for letter in prefixes:
    n = 0
    if prefixes[n] == 'O' or 'Q':
    print prefixes[n] + xsuffix
    else:
    print letter + suffix

--- I know it doesn't work, but want to know if I am on the right track.  And what is the solution?

Thanks

Ben



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


how to run a programm after you have typed in the commands (was Re: [Tutor] help (fwd))

2005-04-13 Thread Ben Vinger
It sounds like you've been using the Python
interactive prompt such as IDLE.   You can type the
same Python statements you've used there into a text
editor or Python IDE and save it.
Let's say you have created a Python program/script
called hello.py in a text editor and saved it. You can
now open a command prompt (Windows) or console (linux)
in the directory where your program is saved.
 Then type:
python hello.py 

If you are using Windows and this does not work, it
will be because Python is not in your system path.
Good luck
Ben



--- Danny Yoo <[EMAIL PROTECTED]> wrote:
> 
> 
> -- Forwarded message --
> Date: Wed, 13 Apr 2005 17:12:55 +0200
> From: Feziwe Mpondo <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: help
> 
> how to run a programm after you have typed in the
> commands
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

Send instant messages to your online friends http://uk.messenger.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)

2005-04-13 Thread Ben Markwell
Thanks for everybodys input. Am learning slowly but surely.

Ben
On 4/13/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]
> wrote:Quoting Joseph Quigley <[EMAIL PROTECTED]
>:> prefixes = 'JKLMNOPQ'> suffix = 'ack'>> for letter in prefixes:>  if letter == ('O') or ('Q'):>   print letter + 'u' + suffix>  else:>   print letter + suffix
Hi Joseph,This still won't work.  The reason is that your if statement is interpreted likethis:if letter == 'O':print letter + 'u' + suffixelif 'Q':print letter + 'u' + suffic
else:print letter + suffixDo you see?  The == "binds more tightly" than the or.  And, in python, 'Q' isconsidered True for the purposes of tests.So this is what happens:>>> prefixes = 'JKLMNOPQ'
>>> suffix = 'ack'>>>>>> for letter in prefixes:...   if letter == ('O') or ('Q'):... print letter + 'u' + suffix...   else:... print letter + suffix...
JuackKuackLuackMuackNuackOuackPuackQuack>>>What you can do instead is this:for letter in prefixes:if letter in ['O', 'Q']:print letter + 'u' + suffix
else:print letter + suffixHTH.--John.___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question regarding the len function of a list while using a loop

2005-04-14 Thread Ben Markwell
Could somebody explain to me why the code I used to complete this exercise doesn't work. 
And how do you send an integer to len?

Thanks

Ben

==


As an exercise, write a loop that traverses a
list and prints the length of each element.  What happens if
you send an integer to len?

>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]
>>> i = 0
>>> while i < len(foo):
     print len(foo[i])
     i = i+1

    
5

Traceback (most recent call last):
  File "", line 2, in -toplevel-
    print len(foo[i])
TypeError: len() of unsized object___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding the len function of a list while using a loop

2005-04-14 Thread Ben Markwell
Yes this does make sense.  Thank youOn 4/14/05, Brian van den Broek <[EMAIL PROTECTED]> wrote:
Ben Markwell said unto the world upon 2005-04-14 08:14:> Could somebody explain to me why the code I used to complete this exercise
> doesn't work.> And how do you send an integer to len?>> Thanks>> Ben>> ==>>> *As an exercise, write a loop that traverses a list and prints the length of
> each element. What happens if you send an integer to len?>> *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]>>>>>i = 0>>>>while i < len(foo):
>> print len(foo[i])> i = i+1>>> 5>> Traceback (most recent call last):> File "", line 2, in -toplevel-> print len(foo[i])
> TypeError: len() of unsized objectHi Ben,Max and Alberto have already explained why you got the error message.Depending on the context in which you are doing this, the having theerror crash the program might be what is desired. (I get that the
context is simply an exercise, but let's pretend it is an actualprogram, written in anger :-).) Or, you might want your program tohandle the problem more elegantly.Using the general framework Alberto suggested, here's a way to do that
(I've also thrown some string formatting in to make the output morefriendly): >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> for item in foo:... try:... print "Item: %s has length %s" %(item, len(item))
... except TypeError:... print "Item: %s has no length" %item...Item: spam! has length 5Item: 1 has no lengthItem: ['brie', 'cheddar', 'swiss'] has length 3Item: [1, 2, 3] has length 3
 >>>This works by attempting to do the thing in the try part, and catchingany case than raises a TypeError (as your original code did), doingthe routine of the except block instead.Does that make sense?
If not, post back and I can try to explain in more detail.Best,Brian vdB___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2005-05-26 Thread Ben Vinger
Or like this:

for x in range (0,256):
print ord(chr(x)), ': ', chr(x)

(you could just print x, instead of ord(chr(x)), but
then you would not be using ord)

Ben

--- Pujo Aji <[EMAIL PROTECTED]> wrote:
> Actually you can do the same way:
> 
> # Convert intAscii to charAscii
> S = [chr(x) for x in range(0,256)]
> for x in S: print x
> 
> #Convert charAscii to intAscii
> AsciiInt = [ord(x) for x in S]
> for x in AsciiInt: print x
> 
> Best Regards,
> pujo
> 
> On 5/26/05, John Carmona <[EMAIL PROTECTED]>
> wrote:
> > With the help of Pujo Aji I have written this
> little script that print every
> > single ASCII code>>
> > 
> > S = [chr(x) for x in range (0,256)]
> > for x in S:
> > print x,
> > 
> > The next step is to use the built-in functin ord()
> in order to convert each
> > character to an ASCII integer. I have had a look
> at the ord() function but
> > it says that it only take one argument i.e.
> ord('a'). How could I execute to
> > convert each character into an ASCII integer?
> > 
> > Thanks in advance
> > JC
> > 
> > 
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



___ 
Can't remember an address in your address book? Enter the first few letters and 
Address AutoComplete will automatically finish it. 
Get Yahoo! Mail http://uk.mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject). Ord and Chr query

2005-05-27 Thread Ben Vinger

--- John Carmona <[EMAIL PROTECTED]> wrote:
> Ben I could not get your script working

indentation? 




___ 
Can't remember an address in your address book? Enter the first few letters and 
Address AutoComplete will automatically finish it. 
Get Yahoo! Mail http://uk.mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] replaying

2005-07-18 Thread Ben Vinger
Mailman can be set up to reply to the forum, but
people on this list prefer to live with pain!

--- geon <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> Seems to me as very unuseful thing in this phorum,
> when I choose Replay 
> to any message, the field "to whom or Receiver" is
> all the time not 
> tutor@python.org but the original sender! Why? I can
> not understand that?
> 
> It sould be prefferably posted back to mailing list
> IMHO.
> 
> 
> -- 
> geon
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




___ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hy, I'm a n00b to Python, have some questions

2005-07-18 Thread Ben Vinger

--- Alex Nedelcu <[EMAIL PROTECTED]> wrote:
> 4. What's the hottest web framework right now that
> does not require an 
> application server (meaning that it runs on fastcgi)

Take a look at Myghty  - it seems pretty good - it is
a Python rewrite of Perl::Mason (which Amazon.com is
based on).   You can run it through mod_python which I
believe performs better than fastcgi.





___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] raw_input into range() function

2007-04-18 Thread Ben Sherman
On 4/18/07, Guba <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am trying to do the exercises in Michael Dawson's "Absolute Beginner"
> book. In chapter four ("for Loops, Strings, and Tuples") one of the
> challenges is: "Write a program that counts for the user. Let the user
> enter the starting number, the ending number, and the amount by which to
> count."
>
> The code I have come up with so far is further below; basically my
> problem is that I don't know how to feed the range() function with the
> user-input numbers it expects.
>
> Your help is highly appreciated!
>
> Guba
>
>
> # Counting Program
> # 2007-04-18
>
> # Welcoming the player
> print "Hello, let me do some counting for you!"
>
> # Telling the player what to do & assigning that info to variables.
> start_num = int(raw_input("Please give me a starting number. "))
> end_num = int(raw_input("Please give me an ending number. "))
> interval = int(raw_input("By which amount am I to count? "))
>
> start_num == 0
> end_num == 1
> interval == 2
>
> print "Counting:"
> for i in range(0, 1, 2):
>  print i
>
>
> raw_input("\n\nHit Enter to exit.")


Your attempt to read input is never used, and your variable
assignments are not correct.

You are using the test operator '==' instead of the assignment
operator '='.  The lines:
"""
start_num == 0
end_num == 1
interval == 2
"""
do something you aren't trying to do here.  Those lines are testing to
see if start_num equals zero, and then ignoring what the test result
is.  They don't actually *do* anything.

Your code should look like this:

print "Hello, let me do some counting for you!"

start_num = int(raw_input("Please give me a starting number. "))
end_num = int(raw_input("Please give me an ending number. "))
interval = int(raw_input("By which amount am I to count? "))

print "Counting:"
for i in range(start_num, end_num, interval):
print i
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] scope/namespaces

2007-04-24 Thread Ben Sherman
Am I wrong in my memory?  When I was a wee lad prior to 99 for sure),
I thought I would initialize my loops with:

for (int x=0; x <10; x++) {
}

I am rapidly veering off topic.


On 4/24/07, Alan Gauld <[EMAIL PROTECTED]> wrote:
> Correcting my own post!
>
> "Alan Gauld" <[EMAIL PROTECTED]> wrote
>
> > That's a very recent change to C/C++ (1999 apparently),
>
> Actually only a recent change in C. Its always been true of C++.
> But in C up until recently(*) you couldn't define a loop
> variable in the loop it had to be outside:
>
> int x;
> for (x=0;)
>
> (*)I'm not sure whether the C++ style loop definition was
> introduced in the original ANSI standard or the later
> revision (none of my books malke it clear), but I think it was
> the revision.
>
> But C++ always had loop variables as part of block scope.
>
> Sory for any confusion,
>
> Alan G.
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fixing garbled email addresses

2007-05-01 Thread Ben Sherman

On 5/1/07, Dotan Cohen <[EMAIL PROTECTED]> wrote:

I have had the misfortune of having a university Windows machine
garble all the email addresses in my addressbook (a txt file so that I
can use it both on my home Fedora machine and on the university
Windows machines). I figure this is as good a time as any to start
learning python and fix the file. How can I iteriate through a text
file that looks like this:

 "=?UTF-8?B?157XqNeZ15Qg15nXoNeY16bXnw==?=" <[EMAIL PROTECTED]>,
 "=?UTF-8?B?157XqNenINen15nXmNek15XXkQ==?=" <[EMAIL PROTECTED]>,
 "=?UTF-8?B?157XqdeUINem15LXkNeZ?=" <[EMAIL PROTECTED]>,

and have it return:
[EMAIL PROTECTED],
[EMAIL PROTECTED],
[EMAIL PROTECTED],

Thanks in advance.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Hi Dotan!  Welcome to python!

Here is some code that will do what you need.  It uses the re module,
which are regular expressions.

# You need to import the module:
import re

# Then you need to read in the file that contains your list.
email_list = open("brokenemails.txt","r")

# We need to generate your regular expression.  The grabs anything in
# the file that is between < and >, but it includes the <>
re_mail=re.compile(r"\<(.*)\>")

# Then filter each line of the file through the regex, discarding the
# <> from above, and puts each address into a list.
addresses = [re_mail.search(line).group(1) for line in
email_list.readlines()]

# Now we print them out, comma and newline separated
print ",\n".join(addresses)

Let me know if you need more detail!

Your pal,
Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fixing garbled email addresses

2007-05-01 Thread Ben Sherman

On 5/1/07, Dotan Cohen <[EMAIL PROTECTED]> wrote:


[snip]
>
> List comprehensions are the best thing ever!
>
> Happy to help,
> Ben
>


With Gmail one must be careful and check that the To and Subject
fields contain what you'd expect.

Does 'list comprehension' mean a detailed explanation of the code? If
so, then I'll be reading a lot of them in the near future. I really do
appreciate the dedication and attention to detail. Thanks.




List comprehension are a python/programming term.  They allow one to make a
list without generating a blank one and appending to it. A very basic
example:

newlist = [item for item in spam(eggs)]

is the same as

newlist = []
for item in spam(eggs):
   newlist.append(item)

If you walk through the code from earlier, you can see where a list
comprehension saved some lines and made the flow easier to read.

Official documentation is here: http://docs.python.org/tut/node7.html(section
5.1.4)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Aaagh! Stack arrays!?! calc average

2007-05-01 Thread Ben Sherman

On 5/1/07, John Washakie <[EMAIL PROTECTED]> wrote:


Oops, I meant it crashes at line 7..

>
> 1) tinit = data[0][0]
> 2)for d in data:
> 3)if d[0] <= tinit+60:
> 4)sum = sum+d
> 5)else:
> 6)avg = sum/len(sum)
> 7)newData = append([newData],[avg],axis=0)
> 8)tinit = d[0]
>



You didn't include your append() function here, so it's hard to tell whats
going on.  Perhaps you mean to use newData.append(avg) assuming that newData
is a list?

Also, your average looks funky.  If sum is something you can get a len() on,
you can't divide it.  It should be bombing here.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Aaagh! Stack arrays!?! calc average

2007-05-01 Thread Ben Sherman

On 5/1/07, John Washakie <[EMAIL PROTECTED]> wrote:


Ug,

It still doesn't make sense due to the sum/cnt where cnt is just an
int, and sum is a 1-dimensional array!

I'm missing something here about working with numpy arrays...



You need to add all of  the numbers in your list - you can't just divide a
list by an int.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Aaagh! Stack arrays!?! calc average

2007-05-01 Thread Ben Sherman

On 5/1/07, John Washakie <[EMAIL PROTECTED]> wrote:


It aint pretty! And if I had just walked away, it probably would've
taken half the time in the morning, but here's what I've come up with
(any suggestions for improvements, or course are welcome):

for d in data:
w = len(d)
if d[0] <= tinit+60:
d = column_stack(d)
cnt,sum = cnt+1,sum+d

else:
avg = sum/(ones(w)*cnt)
tinit,cnt,sum = d[0],0,zeros(n)
if init==0:
newData,init = avg,1
else:
newData = append(newData,avg,axis=0)

return newData





Sorry my last reply was so terse - I needed to catch a train. :)

So you need to check out a couple of functions - namely sum.


numbers=[1,2,3,4,5]
numbers.append(6)
numbers

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

sum(numbers)

21

len(numbers)

6

sum(numbers)/len(numbers)

3

WAIT WAIT hold the phone!?  21/5 is NOT 3!  It's 3.5!  The short story here
is that you have to make on of the numbers a floating point to get the
result to return a float, so do this:


sum(numbers)*1.0/len(numbers)

3.5

So there is our average.  If floor division doesn't make sense to you, you
aren't alone.  This changes in Python 3000.  You can read about floor
division here:
http://www.python.org/doc/2.2.3/whatsnew/node7.html

I don't quite know what your stack is for - it can probably be accomplished
using some slices or other fun stuff.

Good luck, and welcome to python!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Learning to Debug?

2007-05-16 Thread Ben Sherman

On 5/16/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


I'm moving forward with my learning of Python, but I've decided it's
finally time to address a problem that has haunted me in every language I've
every tried to learn: debugging.   I'm just not very good at it. Does anyone
have recommendations for Python-centric books/online tutorials that teach
you techniques for good debugging?





Hi David, welcome to Python!

You should look at the pdb module.  A good tutorial is at
http://www.ferg.org/papers/debugging_in_python.html

Good luck!
Ben
(accidentally replied directly to David the first time)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] encryption for files/passwords

2007-05-18 Thread Ben Sherman

On 5/18/07, Rohan Deshpande <[EMAIL PROTECTED]> wrote:


Hey all,

I am writing a small python script to maintain some passwords and
identity info.  All the data is in an external file.  what is the best
way to encrypt/decrypt this file's data using a key? I am new to
encryption methods let alone how to do it in python.  I had a look at
python-crypto, ezPyCrypto and yawPyCrypto but they seemed overkill?



If you only need to encrypt passwords, look at the crypt module - it does
one way password hashing.

Good luck!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how long?

2007-07-03 Thread Ben Waldin
How long will it take until I successfully create my own working program that 
is useful? I have crated the address book ones in the tutors and just want to 
know how long it takes before I start to create my own thought up programs that 
will be useful. Thanks Ben   
_
Discover the new Windows Vista
http://search.msn.com/results.aspx?q=windows+vista&mkt=en-US&form=QBRE___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String module; Count

2007-10-17 Thread Ben Sherman
You can only count one at a time.

count = conversion(n).count("0") + conversion(n).count("1")

count is a string method, so it operates directly on the string - you
don't have to call it like you did.

import string
string.count(mystr, "cheese")

is the same as

mystr.count("cheese")

At least it is in newer versions of python.

Let me know if that helped.

Cheers,
Ben

On 10/17/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I am having trouble getting the string.count function to work. I want it to
> count the amount of digits (0 or 1) in the string, but I keep getting an
> error stating the string.count was expecting a character buffer object.
> CODE:
> count = string.count(conversion(n),["0","1"])
>
> ERROR:
> Traceback (most recent call last):
>   File "/Users//Desktop/Project 1.py", line 59, in -toplevel-
> signed_mag()
>   File "/Users//Desktop/Project 1.py", line 29, in signed_mag
> count = string.count(conversion(n),["0","1"])
>   File
> "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/string.py"
> , line 348, in count
> return s.count(*args)
> TypeError: expected a character buffer object
>
> I'm trying to make a decimal to binary converter that has the option to
> select the amount of bits for Signed Binary. I've thought of a way (not
> tested yet) on how to implement the bits, but I first need to count the
> amount of digits in the original conversion. Thanks in advance.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beat me over the head with it

2007-12-10 Thread Ben Bartrum
import motivation

(sorry)

> -Original Message-
> From: [EMAIL PROTECTED]
> Sent: Sat, 8 Dec 2007 22:04:04 -0600
> To: [EMAIL PROTECTED]
> Subject: Re: [Tutor] Beat me over the head with it
> 
> Need help with a motivational disorder? ;)
> 
> When you say you want to learn Python, what's the nature of the "want
> to" part? Looking to write a game, land a job, parse a log file?
> 
> Perhaps if you focus on what it is you want to do, that will lead the
> way.
> 
> On Dec 8, 2007 9:08 PM, Theyain <[EMAIL PROTECTED]> wrote:
>> I'm not sure if this is really the place to do this, but I will ask
>> anyways.
>> 
>> Hello everyone, names Theyain.  I want to learn Python.  But I am one of
>> those people who needs some one to "Beat me over the head" to actually
>> learn something.  I can't get myself to actually sit down and read a
>> tutorial on Python because no one is making me.  So can someone help me
>> with this?  I really want to learn python, but I can't do it with out
>> help.
>> 
>> 
>> So help?
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] thread not running

2007-12-10 Thread Ben Bartrum
Hello

I have the following, which I use within a CherryPy app.  The subprocess bit is 
just to see if it runs or not.   It works on my home PC (Python 2.5.1 on 
Ubuntu), but not on the live host which has Python 2.4.4 on Debian Etch.  


def daemon():
  while 1:
 myperiodicfunction()
 p = subprocess.Popen('cal > /tmp/stilhere.txt', shell=True)
 time.sleep(30) 

thread.start_new_thread(daemon,())

Is there a way to get it to work without upgrading Python (which I am not keen 
to do, as I prefer the packaged version & security updates)

Thanks


GET FREE 5GB EMAIL - Check out spam free email with many cool features!
Visit http://www.inbox.com/email to find out more!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] thread not running

2007-12-10 Thread Ben Bartrum

> What's going wrong when running it with 2.4? AfaIcs, all modules are
> in 2.4, so it my not have to do anything with the Python version, but
> with the underlying system. Any traceback? Perhaps replace the
> subprocess part with just a print statement to see what's happening?

There are no tracebacks, and I have done some more investigation:
1. the thread code works fine standalone on both systems
2. the thread code works within CherryPy on my home PC but does not work within 
CherryPy on the live host
3. Both run the same version of CherryPy - I could not imagine it is a CherryPy 
issue, but unless you have any suggestion I'll try the CherryPy list

The live code runs under supervisor.  Could that make a difference?

Thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Program Specification Request

2008-01-16 Thread Ben Bartrum
>Question(s):
>Q01:  Is this a 'reasonable' first project?

Yes.  But I'd say do it in 2 phases.  First do a command-line version, then do 
the GUI.

>Q02:  We can use either MAC or WinXP but which? Or both?

It realy doesn't matter

>Q03:  Is this the appropriate forum?

Yes


GET FREE SMILEYS FOR YOUR IM & EMAIL - Learn more at 
http://www.inbox.com/smileys
Works with AIM®, MSN® Messenger, Yahoo!® Messenger, ICQ®, Google Talk™ and most 
webmails
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What web framework?

2008-01-29 Thread Ben Bartrum
Yes, CherryPy is an excellent, and uniquely straightforward tool for writing a 
database-driven web application.  I'd start looking into things like Django for 
larger sites where you also want templating, and client-side interactivity 
through JavaScript etc.
In my simple CherryPy apps, I use Python's own (%) string substitution instead 
of a templating language, so a simple CherryPy app can consist of pure Python 
code, SQL queries and nothing else needed.  



> -Original Message-
> From: [EMAIL PROTECTED]
> Sent: Tue, 29 Jan 2008 01:00:22 -
> To: tutor@python.org
> Subject: Re: [Tutor] What web framework?
> 
> "Terry Carroll" <[EMAIL PROTECTED]> wrote
> 
>> But querying's different.  I'd initially planed on making this a
>> wxPython
>> application, but I think it might be simpler to have it as a web
>> app, even
>> though I'll be the only user, and the db will be resident on the
>> same
>> program I'm querying from.
>> 
>> This calls for using a web framework,
> 
> Not really, a simple CGI app would be suffficient.
> A framework is really only needed where you have lots of pages
> all with the same look n feel and lots of interaction between them.
> If all you need is a query screen and a results screen then basic
> CGI should be more than adequate.
> 
> If you really want more then look at basic CherryPy rather than
> TurboGears/Django. It takes the CGI pains away while keeping
> the code simple and direct.
> 
> TurboGears and Django are both excellent but the learning curve
> for a simple app is more than the gain IMHO. OTOH If you want
> to build knowledge for the future then pick one and go with it.
> It doesn't much matter which they all use the same principles
> its only syntax differences really.
> 
> IMHO at least,
> 
> Alan G.
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON????

2005-09-01 Thread Ben Vinger
The Python interpreter already contain the code for
multiplication, so you don't need to write it.  You
can just use it:

x = raw_input('give the first number')
y = raw_input('give the second number')
print x,  ' times ', y, ' is', int(x) * int( y)

Or in the interactive interpreter you can just:

>>> 2 * 4
8

Good Luck!


--- [EMAIL PROTECTED] wrote:

> Dear Python,
>  How does a calculator multiply? I want to create a
> computer software that can multiply. How do I
> program the computer to multiply? 
> > ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hey i need some help here

2005-09-11 Thread Ben Vinger
It is almost certain that you are using MS Windows,
and that Python is not in you "system path".
If so, here's what to do:

Add the top-level Python directory to your Windows
"PATH".  On Windows NT this is done with Control
Panel/System/Environment.  On Windows 2000 and Windows
XP it is done with Control
Panel/System/Advanced/Environment Variables.  Edit the
PATH environment variable in the System settings to
add C:\Python22 or C:\Program Files\Python22 (or
wherever you put Python)

(taken from
http://cars9.uchicago.edu/software/python/)

Ben

--- Matt Warren <[EMAIL PROTECTED]> wrote:

> I just started attempting to program and thought i
> would try python as my 
> first tool. However following the beginners guide on
> their page it says to 
> insert python as a command and that it should come
> up with the program 
> information. When i insert python it says it is not
> recognizable as an 
> internal or external command. can somebody help me?
> 



___ 
How much free photo storage do you get? Store your holiday 
snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Website monitoring program.

2005-11-21 Thread Ben Vinger
Below is a program I found at
http://starship.python.net/crew/neale/ (though it does
not seem to be there anymore.)  It uses a seperate
file for the URLs

--- Adisegna <[EMAIL PROTECTED]> wrote:

> My question is how to use a loop to go through a
> tuple of URLs. Please feel
> free to suggest an easier way to do the same thing.


#!/usr/bin/env python

"""watch.py -- Web site change notification tool
Author: Neale Pickett <[EMAIL PROTECTED]>
Time-stamp: <2003-01-24 13:52:13 neale>

This is something you can run from a cron job to
notify you of changes
to a web site.  You just set up a ~/.watchrc file, and
run watcher.py
from cron.  It mails you when a page has changed.

I use this to check for new software releases on sites
that just change
web pages; my wife uses it to check pages for classes
she's in.

You'll want a ~/.watchrc that looks something like
this:

to: [EMAIL PROTECTED]
http://www.example.com/path/to/some/page.html

The 'to:' line tells watch.py where to send change
notification email.
You can also specify 'from:' for an address the
message should come from
(defaults to whatever to: is), and 'host:' for what
SMTP server to send
the message through (defaults to localhost).

When watch.py checks a URL for the first time, it will
send you a
message (so you know it's working) and write some
funny characters after
the URL in the .watchrc file.  This is
normal--watch.py uses these
characters to remember what the page looked like the
last time it
checked.

"""

import os.path
import urllib2 as urllib
import sha
import smtplib

rc = '~/.watchrc'
host = 'localhost'
fromaddr = None
toaddr = None

def hash(data):
return sha.new(data).hexdigest()

def notify(url):
msg = """From: URL Watcher <%(from)s>
To: %(to)s
Subject: %(url)s changed

%(url)s has changed!
""" % {'from': fromaddr,
   'to':   toaddr,
   'url':  url}
s = smtplib.SMTP(host)
s.sendmail(fromaddr, toaddr, msg)
s.quit()

fn = os.path.expanduser(rc)

f = open(fn)
outlines = []
for line in f.xreadlines():
if line[0] == '#':
continue

line = line.strip()
if not line:
continue

splits = line.split(' ', 1)
url = splits[0]
if url == 'from:':
fromaddr = splits[1]
elif url == 'to:':
toaddr = splits[1]
if not fromaddr:
fromaddr = toaddr
elif url == 'host:':
host = splits[1]
else:
if (not fromaddr) or (not toaddr):
raise ValueError("must set to: before any
urls")
page = urllib.urlopen(url).read()
ph = hash(page)

try:
h = splits[1]
except IndexError:
h = None
if h != ph:
notify(url)
line = '%s %s' % (url, ph)
outlines.append(line)

f.close()

f = open(fn, 'w')
f.write('\n'.join(outlines) + '\n')
f.close()




___ 
Yahoo! Model Search 2005 - Find the next catwalk superstars - 
http://uk.news.yahoo.com/hot/model-search/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] extra characters in XML

2006-01-11 Thread Ben Vinger
Hello all

I want to do the following in an XML file:

XFile = open(XmlFile,'r')
for line in XFile.readlines():
if line.find('') > 0:
  print line

However, it does not work due to extra characters that
appear in the XML file.  For example if I use the
previous code without the if condition, on a console
it looks like:
< e n d _ t i m e >
And if you output that to a text file and open that in
a text editor, the text editor shows a square instead
of a space in between every character.  What is going
on?

Thanks
Ben





___ 
Yahoo! Photos – NEW, now offering a quality print service from just 8p a photo 
http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] extra characters in XML

2006-01-11 Thread Ben Vinger
Found the following (which solved the problem, though
not on the console) at
http://www.jorendorff.com/articles/unicode/python.html

  import codecs
  # Open a UTF-8 file in read mode
  infile = codecs.open("infile.txt", "r", "utf-8")
  # Read its contents as one large Unicode string.
  text = infile.read()
  # Close the file.
  infile.close()

The same function is used to open a file for writing;
just use "w" (write) or "a" (append) as the second
argument.


--- Ben Vinger <[EMAIL PROTECTED]> wrote:

> Hello all
> 
> I want to do the following in an XML file:
> 
> XFile = open(XmlFile,'r')
> for line in XFile.readlines():
> if line.find('') > 0:
>   print line
> 
> However, it does not work due to extra characters
> that
> appear in the XML file.  For example if I use the
> previous code without the if condition, on a console
> it looks like:
> < e n d _ t i m e >
> And if you output that to a text file and open that
> in
> a text editor, the text editor shows a square
> instead
> of a space in between every character.  What is
> going
> on?
> 
> Thanks
> Ben
> 
> 
> 
> 
>   
>
___
> 
> Yahoo! Photos – NEW, now offering a quality print
> service from just 8p a photo
> http://uk.photos.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] extra characters in XML

2006-01-12 Thread Ben Vinger
Thanks - it was exactly as you said 

--- Kent Johnson <[EMAIL PROTECTED]> wrote:

> Most likely your XML file is 16-bit unicode, not
> utf-8. When ascii text 
> is represented as unicode, every other byte will be
> a null byte. That is 
> the extra character that shows up as a space or box
> depending on who is 
> interpreting it. The utf-8 codec must be swallowing
> the null bytes.
> 
> In your code above, instead of utf-8 try utf_16_be
> and utf_16_le, one of 
> them should work.






___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] a class knowing its self

2006-01-18 Thread Ben Vinger
Hello

I've been reading about how a class has access to its
own 'self', so I tried the following, but it is not
working as I would expect:

class Skill:
   def __init__(self):
  self.history = []  

   def setName(self, skill):
  self.name = skill

   def getName(self):
  return self.name

# Assigning data to my class:  

SkillNames = [r'python', r'apache', r'mysql']

#a.)
python = Skill()
python.setName('python')
print python.getName()

#b.)
for s in SkillNames:
  s = Skill()
  s.setName(s)
  print s.getName()

Why does a work and b not?   

b returns:
<__main__.Skill instance at 0x401e260c>
<__main__.Skill instance at 0x401e230c>
<__main__.Skill instance at 0x401e23ec>

why does b not return the names of the 3 instances of
Skill?

Thanks
Ben



___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a class knowing its self

2006-01-21 Thread Ben Vinger
Yes, you are right, - Shuying Wang's suggestion fixed
the immediate problem, but there is still someting
wrong with my code - maybe I'll ask about it again
later.


--- Ewald Ertl <[EMAIL PROTECTED]> wrote:


> > 
> Have a more precisely look at your code.
> s.getName() does just return, what you have put into
> the class with setName(). ( Reassignment of a
> variable to
> something different what you intended ).




___ 
NEW Yahoo! Cars - sell your car and browse thousands of new and used cars 
online! http://uk.cars.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] passwords in scripts

2006-01-21 Thread Ben Vinger
Hello

I've written a couple of scripts that check log files
on our WIndows and Unix servers.  These scripts have
plain text passwords in them, so anyone who can access
the filesystem of the Windows server that runs the
scripts can discover the passwords of the servers.
Is there a way to hide/encrypt these passwords?  Or
can the scripts be converted to compiled code in order
for the passwords to be hidden?


Thanks
Ben 



___ 
Win a BlackBerry device from O2 with Yahoo!. Enter now. 
http://www.yahoo.co.uk/blackberry
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passwords in scripts

2006-01-23 Thread Ben Vinger
Hi Ivan

I'm not sure I understand what you are saying here. 
Surely if the file is compiled it can just run (and
will only need to be RE-compiled when I have to change
the code (such as when one of the servers has their
password changed).
I would never need to de-compile, because I'll just
keep a copy of the file  on a memory stick, edit it
there, compile it and replace the current compiled
file with the newly compiled file.
Not that I know anything about compiling Python
programs, I just want to know if this is a possibility

Thanks
Ben


--- Ivan Furone <[EMAIL PROTECTED]> wrote:

> 2006/1/21, Ben Vinger <[EMAIL PROTECTED]>:
> > Hello
> >
> > I've written a couple of scripts that check log
> files
> > on our WIndows and Unix servers.  These scripts
> have
> > plain text passwords in them, so anyone who can
> access
> > the filesystem of the Windows server that runs the
> > scripts can discover the passwords of the servers.
> > Is there a way to hide/encrypt these passwords? 
> Or
> > can the scripts be converted to compiled code in
> order
> > for the passwords to be hidden?
> >
> >
> > Thanks
> > Ben
> >
> >
> 
> Hello,
> Compiling a file in python is a big time
> loss,because there's not a
> built-in function for decompiling,but you can just
> use the 'dis'module
> for disassembling it and the result is always
> different from the
> original,because it uses Abstract Source Tree syntax
> in spite of
> Python language for translating the bytecode;on the
> other hand it
> wouldn't secure the file itself from being accessed
> but makes it
> useless IMHO.Thus,with a slight impact on
> complexity,a module with the
> crypted passwords would be imported, which would
> proceed for checking
> the passwords and exporting them in a StringIO
> object at runtime.For
> enhancing security,once used it could be removed and
> used again when
> needed,without removing the scripts themselves.You
> can check the
> 'crypt' module for this task.
> Cheers,
> Ivan
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




___ 
Win a BlackBerry device from O2 with Yahoo!. Enter now. 
http://www.yahoo.co.uk/blackberry
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passwords in scripts

2006-01-23 Thread Ben Vinger
Hi Danny

The Unix servers are ancient HP-UX ones.  I doubt if
an SSH implementation for them exists, but it is not
worth my while trying to find out, because I will not
be allowed to install anything on them (or even
suggest it).  So I access them using telnetlib:

host = 'hpserver'
user = 'backupuser\r'
password = 'backuppassword\r'
telnetConnection = telnetlib.Telnet(host)
telnetConnection.read_until('login: ')
telnetConnection.read_until('Password: ')
telnetConnection.write(password)
menu = telnetConnection.read_until('Please Enter
choice :')

etc - doing the things programatically what I would
have done if I opened a regular telnet session

On the  Windows servers the scheduled task I use runs
with my domain logon credentials.   This is fine for
the majority of the servers, but some are in other
domains where my  credentials don't do the job. For
them, I just open a connection to the ipc$ share in
advance, like so:

os.system(r'net use \\farserver\ipc$ 
/u:fardomain\administrator farpassword')

The information about all the backup results is
finally served as a single web page, so anyone can see
at a glance whether the backups worked. This can also
easily be emailed out, or warnings can be sent.

But surely my problem is a very common one.  Every
web-app must supply a username and password to make a
connection to its backend database, for example.

Thanks
Ben



--- Danny Yoo <[EMAIL PROTECTED]> wrote:

> I guess one question might be: why are the passwords
> there in the first
> place?  *grin*
> 
> 
> It's usually a good idea to try avoiding hardcoding
> things in a program,
> and that goes for passwords too.  If you're using
> passwords to connect to
> the Unix servers, you might want to consider looking
> at Keychain:
> 
> http://www.gentoo.org/proj/en/keychain/
> 
> to avoid having to do manual password entry. 
> Alternatively, 'ssh' can
> be used to run remote commands on a Unix server. 
> There's a good example
> of this here:
> 
> http://www.jdmz.net/ssh/
> 
> 
> If you could tell us more details on why those
> passwords are there, we
> might have some better suggestions.
> 
> 
> Good luck!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passwords in scripts

2006-01-24 Thread Ben Vinger
--- Alan Gauld <[EMAIL PROTECTED]> wrote:

> command line arguments?
> 
> $ startapp -d mydb -l user/password &
> 
> That way they are 
> 1) kept secret(especially if you turn shell history
> off ;-) and 
> 2) can be changed every time you restart the server
> app and
> 3) you can have production and test databases
> running simultaneously...

These are good points, but what if the server is
bounced when I'm on holiday (or everyone who might
enter the password is asleep).  
My own little app isn't critical, but I can't see this
do the trick for high profile web sites and similar.








___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passwords in scripts

2006-01-24 Thread Ben Vinger
Compiling is certainly helpful in my case, and I did
not realise how simple it was until you explained it. 
I estimate that most of our MCSEs will not know about
the strings command or attempt to look inside
something like test.pyc for a password.
As for users, I'll be amazed if they tried it.   And
real crackers - I think our network/firewall people
know what they are doing, so I assume crackers are
kept out.
So, yes, I will use this until I've done something
with crypt and/or expect.  
Finally, regarding changing the policy about telnet -
it looks to me like the network where I am (I'm very
new), is secure on the networking side however lax it
might be on the server side.  It is 100% switched,
which means that only by controlling a switch can
cleartext stuff be seen, and the switches are
well-protected (also physically).  So while I might
agree with everyone who mentioned it, I will leave the
Unix security to whoever in our large organisation's
concern it is.  I just want to avoid endangering it
myself.

Thanks
Ben

--- Danny Yoo <[EMAIL PROTECTED]> wrote:

> 
> 
> On Tue, 24 Jan 2006, Ivan Furone wrote:
> 
> > I'm not sure I understand what you are saying
> here. Surely if the file
> > is compiled it can just run (and will only need to
> be RE-compiled when I
> > have to change the code (such as when one of the
> servers has their
> > password changed).
> 
> Hi Ivan,
> 
> But the issue is that hardcoding passwords in a
> program doesn't really
> protect that password from exposure.  For example:
> 
> ##
> bash-3.00$ cat test.py
> message = "hello, this is a test"
> bash-3.00$ python
> Python 2.3.3 (#1, Nov  7 2005, 22:36:37) [C] on
> sunos5
> Type "help", "copyright", "credits" or "license" for
> more information.
> >>> import test
> >>> ^D
> ###
> 
> 
> Doing the import will cause test.py to be compiled
> to 'test.pyc':
> 
> ##
> bash-3.00$ ls -l test.pyc
> -rw-r--r--   1 dyoo other143 Jan 24
> 10:55 test.pyc
> ##
> 
> 
> But watch what happens here:
> 
> ##
> bash-3.00$ strings test.pyc
> hello, this is a testN(
> message(
> message(
> test.pys
> ##
> 
> Our secret string shows right up!
> 
> 
> 
> This works even if we're talking about C code:
> 
> /**/
> bash-3.00$ cat test.c
> #include 
> int main(int argc, char** argv) {
>   char *msg = "hello";
> }
> bash-3.00$ gcc test.c
> bash-3.00$ strings a.out
> hello
> /**/
> 
> 
> So the fact that we're "compiling" code doesn't do
> anything significant to
> add security: those string literals are ripe for the
> taking for anyone
> competent enough to use the 'strings' command.  So
> that's what we're
> trying to warn you about.  Compiling code is not a
> magic wand to obscure
> secrets.
> 
> 
> Hope this helps!
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mod_python and other web frameworks

2006-01-25 Thread Ben Vinger

--- Intercodes <[EMAIL PROTECTED]> wrote:

> List: I am still open to suggestions.

Being also keen to write better web apps in Python,
I've spent a considerable amount of time reading about
this (and it is indeed confusing), I've opted to try
out something like Pylons or Turbogears.
One thing I will say though, is that most of the
frameworks you've read about can be run on top of
mod_python.  So mod_python is not one of the lot - it
is essential on Apache unless you opt to use CGI or
FCGI. But as I understand it, you would always opt for
mod_python over CGI or FCGI on a high-traffic website,
though CGI or FCGI is of course fine for smaller
things.
But mod_python is not so easy to work with and it will
only work on Apache.  So it seems best to choose
something else and run that through mod_python when
you're on Apache.






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trying to enter text from a file to a Dictionary

2006-01-26 Thread Ben Markwell
Being new to programming, I made a text file that  contains terms with their definitions that I have come across in my  studying. As an exercise, I thought  I would make a glossary using  a dictionary so I can look up words, add new words, view all entries,  etc.   I want to enter the words and definitions from the  text file into the dict. The way the text file is set up is that one  line is the word and the next line is the definition. For example:  Word      Definition of the word.  Second Word      Definition of the second word.  EtcI thought this would be rather simple (maybe it really is), but I'm  stuck.  I can't figure out how to tell Python to read the line  with the word, add the word to the Key of the dict, then read the next  line and add that line to the Value of the dict, then do it all again  'til the end of the file.I tried using a!
  for loop
 like thisf = open('glossary.txt','r')  gloss = {}for line in f:      gloss[line] = lineWhen I tried to print this, a huge list of key/values printed out. With  many copies of the same key/value pair.   And the key and the  value were the same. (not word followed by definition) , which  afterword made sense, because, I told it that   gloss[line] = lineI tried :for line in f:      gloss[line] = f.readline()That got me nowhere. Sorry for being so dense. I understand what needs to happen, but am having trouble implementing it. Thanks for your help and understanding.  
		Bring words and photos together (easily) with 
PhotoMail  - it's free and works with Yahoo! Mail.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
Hello Danny

Thanks for replying to my post.
>   I tried :>>   for line in f:Thanks for your reply to my post. 


>   gloss[line] = f.readline()>
This should have worked, but there's one problem.  Whenever we're doingsomething like:for line in f:...there can be some interference between the iteration and any readline()
in the body of the loop.  For efficiency reasons, the iterator's allowedto march through the file ahead several lines at with an internal buffer.This means our position in the file might be further along than we might
realize, and that means that readline() will give nonsensical results.So we're getting caught by a low-level detail.  We should try to avoidusing both the for loop and readline() on the same file. Here's one way we
can avoid the problem:
while True:word = f.readline()defn = f.readline()if not word or not defn:   break...Does this make sense?
 It does mostly...I don't see why you need the:

 if not word or not defn:





   break











If this is so that when python iterates to the end of the file, it
knows to stop, and if that is so, then why doesn't python know it has
gotten to the end of the file without it being told?
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
Hi Ben,Yes, that's the point: Python doesn't know when to stop.  *grin*
The way we've rewritten the loop:while True:...is an "infinite" loop that doesn't stop unless something in the loop'sbody does something extraordinary, like "breaking" out of the loop.
Python is much dumber than we might expect.In more detail: Python's readline() method doesn't fail when we reach theend of a file:  we actually start hitting the empty string.  For example:##
>>> import StringIO>>> sampleTextFile = StringIO.StringIO("""This is... a sample... text file... """)>>> sampleTextFile.readline()'This is\n'
>>> sampleTextFile.readline()'a sample\n'>>> sampleTextFile.readline()'text file\n'>>> sampleTextFile.readline()''>>> sampleTextFile.readline()''##
Notice that when we hit the end of the file, readline() still continues torun and give us empty string values.  That's why the loop above needs tomake sure it breaks out in this particular situation.
Does this make sense?  Please feel free to ask questions about this.
Yes The  -- while true loop
--  needs something to be false or it needs to be told when to
stop. If that is correct, then it makes sense. 

Thanks 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
On 1/27/06, Bob Gailer <[EMAIL PROTECTED]> wrote:
Bob Gailer wrote:> Alan Gauld wrote:>>> Hi Ben,>>>>>>>>> I want to enter the words and definitions from the  text file into the>>> dict.>>> The way the text file is set up is that one  line is the word and the
>>> next line is the definition.>>>>>>>>>>>>>  I tried using a for loop like this>>>>>>  f = open('glossary.txt','r')>>>  gloss = {}
>>>>>>  for line in f:>>>  gloss[line] = line>>>>>>>> The problem that you have is that you really need to read two lines at a>> time.
>> (Assuming that the definitions are all on one line which may not be true!)>> A while loop may be easier in this case.>>>> A for loop will read each line individually. You then need to set a
>> definition>> flag to tell the loop body whether you are reading a definition or a key.>>>> Either type of loop is possible. Since you started with a for loop lets>> stick with it...
>>>> definition = False>> currentKey = None>>>> for line in f:>> if isDefinition:>>gloss[currentKey] = line>>currentKey = None
>>isDefinition = False>> else:>>currentKey = line>>isDefinition = True>>>>> Or you can use next():>> for line in f:
> gloss[line] = f.next()>Or even:[gloss.setdefault(l,f.next()) for l in f]
Hello Bob

I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f] is beyond me at this point.
Thanks for your input.

Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to enter text from a file to a Dictionary

2006-01-27 Thread Ben Markwell
> I understand f.next(), but [gloss.setdefault(l,f.next()) for l in f]> is beyond me at this point.
[expr for l in f] is a "list comprehension". expr is an _expression_ thatmay involve l.result = [expr for l in f] # is equivalent to:result = []for l in f:result.append(expr)
"list comprehension" (once understood) is often easier to read and moreefficient than the for loop.result = xxx.setdefault(key, newvalue) is a dictionary method that triesto get an item from the dictionary xxx using key. If the key is not in
the dictionary it adds the item assigning it newvalue. Equivalent to:if key not in xxx:xxx[key] = newvalueresult = xxx[key]Note that list comprehension and setdefault both return something. In my
code the returned values are ignored. The outcome (populating adictionary via a loop) is a "side effect".
Thank you Bob.  This is much to think about.  I very much appreciate your concise explanation.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trapping a Dr Watson error

2006-02-02 Thread Ben Vinger
Hello

I have a script based on:
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/Windows_NT_Eventlog.html
It collects eventlogs data from many Windows servers.
I know how to handle normal Python Tracebacks, but my
script bombs out with a Dr Watson error when
connecting to one particular server.
(It even runs fine against the Application log of this
server, but bombs out on the System log).  Anyways, I
want to know if it is possible to trap, handle and
survive a Dr Watson error programatically

Thanks
Ben




___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python help

2006-02-08 Thread Ben Vinger
Why are these homework programming challenges so
recognisable?  It boils down to:
Write a function that that uses X and Y techniques.
The function may be hard and challenging to write but
doesn't ever do anything interesting or anything that
is useful and complete on its own.

I realise teachers have to test mastery of certain
techniques, but they seem to lack the imagination. 
Especially with modern languagues like Python, where
you can write a whole program that actually does
something usefull using only a few lines of code it
should not be necessary to ask these kinds of dull
questions.

Just stick at it Natasha, it is far more interesting
when you the programming challenge has to accomplish a
real result.

Ben
--- Natasha Menon <[EMAIL PROTECTED]> wrote:

> Hi,
>
>   I have a few doubts in python programming. C if
> any of u can help me out. 
>
>   1. 
>   In a file called string_stuff.py i have to write a
> function called frequencies that takes a string as a
> parameter and returns a dictionary where the keys
> are the characters from the string and each value is
> an integer indicating the number of times the key
> appeared in the string. 
>
>   2.
>   Similary in the same file string_stuff.py, have to
> write a function called locations that takes a
> string as a parameter and returns a dictionary where
> the keys are the characters from the string and each
> value is a list indicating the indices in the string
> at which the key appears, sorted in increasing
> order.
>
>   3.
>   In the same file string_stuff.py, write a function
> called concordance that takes an open file as a
> parameter and returns a dictionary where the keys
> are the strings from the file and each value is a
> list of line numbers of the lines in which the key
> appeared, sorted in increasing order. Start counting
> at 0. Each line number should appear at most once in
> a list, even if a word appears twice on a line. You
> may assume that the input consists only of
> alphabetic letters (a-z, A-Z) and whitespace. 
>
>
>   Id really appreciate if you could help me on these
> small question. I am tryin to learn to program in
> python.
>
>   Thanks,
>   Natasha
> 
>   
> -
> Brings words and photos together (easily) with
>  PhotoMail  - it's free and works with Yahoo! Mail.>
___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How can a function know where it was called from

2006-03-02 Thread Ben Vinger
Hello
 
I want myfunction in the pseudocode below return something different if it was called from indexfunction.
 
def indexfunction():    blah
 
def myfunction():   x = 'whatever'   if :  return x   else:  return  + x +  
 
 
Thanks
Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can a function know where it was called from

2006-03-02 Thread Ben Vinger
Thanks to all who responded.  I ended up using  a sender parameter as suggested by Andre and Alan, as this was very simple to do.
 
Ben
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to monitor streaming data from the internet via modem?

2006-03-09 Thread Ben Vinger
On 3/8/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
Ethereal is one well knownand powerful one, but there are others which may be simpler touse. 

 
Yes, with Ethereal comes a command-line version called tethereal, which I've used within Python on both Windows and Linux.  It worked nicely for trafic analysis, but if you're interested only in the clear text passing through the line, I'd think of using netcat.  

 
 (Sorry Alan, my previous attempt went straight to you instead of the list) 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Build your own web server in three lines of code

2006-03-23 Thread Ben Vinger
The nice-looking, revamped Python web site states that
you can do this, but does not go on to say how.  
Does anyone know?

On an OT note, I've recently seen how it can be done
in a shell script:
http://www.debian-administration.org/articles/371

Ben



___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] TypeError: dict objects are unhashable

2006-03-24 Thread Ben Vinger
Hello

I want to create a dictionary (from SQL usernames) of
the format:
  accounts = {
  ('psmit', '123456'): 'psmit',
  ('rmatt', 'mypass'): 'rmatt',
  }

So I have:
  accounts = {}
  UserCursor.execute(sqlstr)
  rows = UserCursor.fetchall()
  UserConn.commit()
  for row in rows:
U = row['User']
P = row['Password']
InnerDict = {}
InnerDict[U] = P
accounts[InnerDict] = U

But I get:
TypeError: dict objects are unhashable
Unfortunately, I just can't see what I'm doing wrong

Thanks



___ 
NEW Yahoo! Cars - sell your car and browse thousands of new and used cars 
online! http://uk.cars.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List slicing and joining

2007-04-11 Thread Ben Sherman
I've got a list that contain a bunch of information, including the
FQDN of a host.

host_data=['foo.example.com', 'other unimportant data']

I need to seperate the hostname from the domain name.

This is how I'm doing it, and it work, but it seems *really* hacky.
Is there a better (or more pythony) way?

hostname=host_data[0].split(".")[0]
domain=".".join(host_data[0].split(".")[1:])

Thanks,
Ben
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me!

2007-04-12 Thread Ben Sherman
You

On 4/12/07, suryo agung <[EMAIL PROTECTED]> wrote:
> pleate tell me how to make
>
> input number=4
> result
>
> 1
> 22
> 333
> 
>
> in python
> please give me your answer.

input_number = 4

for i in range(1,input_number + 1):
  print str(i) * i

If this is homework, please tell your teacher I helped - I need the
extra credit.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Scanning a file for specific text and copying it to a new file

2010-12-02 Thread Ben Ganzfried
I'm trying to build a program that reads in a file and copies specific
sections to a new file.  More specifically, every time the words
"summary on" are in the original file, I want to copy the following
text to the new file until I get to the words "summary off".

My questions are the following:
1) Once I have read in the old file, how do I copy just the parts that
I want to the new file?  What command do I give the computer to know
that "summary on" (whether capitalized or not) means start writing to
the new file-- and "summary off" means stop?  Also, I assume I'll put
all of this in a while loop based on the condition that we should read
until we are done reading the whole document?  (although, this is
somewhat inefficient because the last "summary on/off" could be way
before the end, but this is preferable to missing one that is at the
end...)

Thank you very much for any help you can provide.  Much appreciated!

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Meaning of -1 in Python

2010-12-10 Thread Ben Ganzfried
I'm currently working through the Google Python tutorial exercises and
had questions about the following function:

def not_bad(s):
  # +++your code here+++
  # LAB(begin solution)
  n = s.find('not')
  b = s.find('bad')
  if n != -1 and b != -1 and b > n:
s = s[:n] + 'good' + s[b+3:]
  return s

It's clear that n!=-1 and b!=-1 means something like : "if in the
string 's' we find the word "not" and in string 's' we find the word
"bad."

I'm wondering the following:
On a deeper computational level, what is going on here?  What exactly
does Python take -1 to mean?  Is it saying that since the string 's'
is indexed starting from 0 to len(s), and since -1 is not part of
that, that therefore something having the value of -1 will never be in
the string?  If so, then how exactly does using negative numbers to
count a string work?  I have read something about this earlier...

Also, does the part: b>n mean, in this case: "bad comes after not in
the string 's'"?

Thank you very much.

Sincerely,

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tab delimited question

2010-12-13 Thread Ben Ganzfried
I'm searching line by line for certain tags and then printing the tag
followed by the word immediately following the tag.

So for example, suppose I had the following line of text in a file:
"this   is  a   key test123 noisenoise  noise   noise   noise"

In this example, I would want to print "key test123" to a new file.
The rest of the words I would not want.

Here is my code so far:

def test(infile, outfile):
  for line in infile:
tagIndex = line.find("key")
start = tagIndex + 4
stop = line[start:].find("\t") -1
if tagIndex != -1:
print("start is: ", start)
print("stop is: ", stop)
print("spliced word is ", line[start: stop])

My question is the following: What is wrong w/ the variable 'stop'?
The index it gives me when I print out 'stop' is not even close to the
right number.  Furthermore, when I try to print out just the word
following the tag w/ the form: line[start: stop], it prints nothing
(it seems b/c my stop variable is incorrect).

I would greatly appreciate any help you have.  This is a much
simplified example from the script I'm actually writing, but I need to
figure out a way to eliminate the noise after the key and the word
immediately following it are found.

Thank you very much for any help you can provide.

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] AttributeError: 'list' object has no attribute 'find'

2010-12-21 Thread Ben Ganzfried
Hey,

I keep getting the error above and unfortunately browsing through
google and finding similar responses has not been fruitful for me.  My
code is below and I have marked off the location of the problem in my
code.  I'm wondering the following:

1) Doesn't the read() file object method return the specified
characters from the file as a string?
2) If #1 is correct, then why is my variable "source" being viewed as
a list as opposed to a string?
3) How can I change my variable "source" so that it can use the 'find'
method?  Or alternatively, is there another method besides the 'find'
method that would do the same thing that 'find' does that would work
on my variable 'source' as it currently is?

Thanks so much,

Ben

#recursively find each instance of the tag throughout the whole document
def findOneTag (tag, source, output):
print("tag is ", tag)
#print("source is now ", source)
print("output is ", output)
#base case
if source == "":
return
#recursive case
tagIndex = source.find(tag) #(*THIS IS THE LOCATION OF THE
PROBLEM**)
print("tagIndex is ", tagIndex)
start = source[tagIndex:].find("\t") + 1
print("start is ", start)
stop = source[tagIndex + start:].find("\t")
print("stop is ", stop)
if tagIndex !=-1:
output.write(tag + "\t" + line[start: stop])
print("spliced text is: ", line[start:stop])
#recursively call findOneTag(tag, String source[stop:], output)
findOneTag(tag, source[stop + 1:], output)

def main():
tag = "species"
inname = "skeletontext.txt"
outname = "skeletontext1234567.txt"
inname1 = open(inname, "r")
output = open(outname, "w")
source = inname1.readlines()
print("source is: ", source)
findOneTag(tag, source, output)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Java Virtual Machine Launcher Question

2010-12-26 Thread Ben Ganzfried
Happy holidays everyone!

My current question relates to a broader python programming question I
have and so I thought it was worth posting here.  I'm trying to read a
single MAGE-TAB file (http://www.mged.org/mage-tab/) and acquire
metadata.

I just downloaded WinRAR to open zip files, but when trying to open
the .jar file for my converter, I get the following message:

"Java Virtual Machine Launcher:

Failed to load Main-Class manifest attribute from
C:\Users\Ben\AppData\Local\Temp\Rar$DI01.718\isatools_deps.jar"

If anyone could help me better understand how to fix this, what is
happening and/or point me in the right direction, I would be very much
obliged.

Thank you very much!

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Odd result from function call

2011-01-07 Thread Ben Ganzfried
When I call one of my functions from the shell (ie compare(10, 5)) it
produces the correct output.  However, when I run the program after calling
the method later in the script, the result is bizarre.  I'm curious why the
wrong result is printed.  Here is an example:

def compare(x,y):
if x < y:
print (x, " is less than ", y)
print("x is ", x, "y is ", y)
elif x > y:
print(x, " is greater than ", y)
else:
print(x, " and ", y, " are equal.")


x = input("First x is: ")
y = input("First y is: ")
print("x is ", x)
print("y is ", y)
compare(x,y)
a = input("Second x is: ")
b = input("Second y is: ")
print("x is ", a)
print("y is ", b)
compare(a,b)
c = input("Third x is: ")
d = input("Third y is: ")
print("x is ", c)
print("y is ", d)
compare(c,d)

Sample (and incorrect) output w/ 10, 5:

First x is: 10
First y is: 5
x is  10
y is  5
10  is less than  5
x is  10 y is  5
Second x is:

When I do simply compare(10, 5) from the shell, I get the correct output (ie
10 is greater than 5).  I had thought I had narrowed the problem down to the
fact that when I run the script only the first digit is counted-- however,
it seems as if only the first digit is counted (ie anything starting w/ a 9
will be greater than anything starting with a 1 (even if the numbers are 9
and 1324234)), and THEN, the second digit is counted (such that 89 is
correctly identified at 81).

Anyway I'm wondering:
1) Why does the script run correctly when I simply call the function from
the shell but not when I try to call the function from within the script?
2) What is actually going on such that only the first digit is being
evaluated?  That is, the interpreter knows that x is 10 and y is 5-- and
yet, for some reason the 5 is being tested against the 1 and since 5 is
bigger than 1, it concludes that 5 is greater than 10.

thanks!

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Object/Class Beginner Questions

2011-01-14 Thread Ben Ganzfried
Hey guys,

I'm using a tutorial geared for a 2.x version of Python and I am currently
using Python 3.1-- so it is possible that my confusion has to do with
different notations between them.  But in any case, here is what I have:

>>> type(Time)

>>> t1 = Time()
>>> type(t1)


where:

class Time:
def __init__(self, hours = 0, minutes = 0, seconds = 0):
   self.hours = hours
   self.minutes = minutes
   self.seconds = seconds

def print_time(t1):
print(t.hours, ":", t.minutes, ":", t.seconds)

Now the book I am working with has the following example:

>>> type(Point)

>>> p = Point()
>>> type(p)


My questions are the following:
1) Why is the type for my class Time : >>> type(Time)
  
when the type for their class Point is: 
Also, what is the difference between "class" and "classobj" in this case?
2) Why does my t1 object give the following as its type: 
And in their p object example the type is: ?
3) What is happening such that when I try to call my print_time(t1) function
I get the following error:
>>> t1 = Time()
>>> t1.hours = 3
>>> t1.minutes = 30
>>> t1.seconds = 45
>>> print_time(t1)
Traceback (most recent call last):
  File "", line 1, in 
print_time(t1)
NameError: name 'print_time' is not defined


Thank you very much.

Sincerely,

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Object/Class Beginner Questions

2011-01-14 Thread Ben Ganzfried
I actually just figured it out (since the tutorial talks about the
difference in indentation between a method and a function in a later
chapter).  Basically, a method is within a class and therefore cannot be
called from the command prompt whereas a function that stands by itself in a
script can be called from the command prompt.

Although if this isn't quite right or there's more to it, I would still
definitely appreciate any advice you have.

Thanks again,

Ben

On Fri, Jan 14, 2011 at 1:53 PM, Ben Ganzfried wrote:

> Hey guys,
>
> I'm using a tutorial geared for a 2.x version of Python and I am currently
> using Python 3.1-- so it is possible that my confusion has to do with
> different notations between them.  But in any case, here is what I have:
>
> >>> type(Time)
> 
> >>> t1 = Time()
> >>> type(t1)
> 
>
> where:
>
> class Time:
> def __init__(self, hours = 0, minutes = 0, seconds = 0):
>self.hours = hours
>self.minutes = minutes
>self.seconds = seconds
>
> def print_time(t1):
> print(t.hours, ":", t.minutes, ":", t.seconds)
>
> Now the book I am working with has the following example:
>
> >>> type(Point)
> 
> >>> p = Point()
> >>> type(p)
> 
>
> My questions are the following:
> 1) Why is the type for my class Time : >>> type(Time)
>'type'>
> when the type for their class Point is: 
> Also, what is the difference between "class" and "classobj" in this case?
> 2) Why does my t1 object give the following as its type:  '__main__.Time'>
> And in their p object example the type is: ?
> 3) What is happening such that when I try to call my print_time(t1)
> function I get the following error:
> >>> t1 = Time()
> >>> t1.hours = 3
> >>> t1.minutes = 30
> >>> t1.seconds = 45
> >>> print_time(t1)
> Traceback (most recent call last):
>   File "", line 1, in 
> print_time(t1)
> NameError: name 'print_time' is not defined
>
>
> Thank you very much.
>
> Sincerely,
>
> Ben
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Object/Class Beginner Questions

2011-01-14 Thread Ben Ganzfried
* I meant that*: A method actually can be called from the command prompt,
but the syntax is quite different than that used to call a function from the
command prompt.

On Fri, Jan 14, 2011 at 2:37 PM, Ben Ganzfried wrote:

> I actually just figured it out (since the tutorial talks about the
> difference in indentation between a method and a function in a later
> chapter).  Basically, a method is within a class and therefore cannot be
> called from the command prompt whereas a function that stands by itself in a
> script can be called from the command prompt.
>
> Although if this isn't quite right or there's more to it, I would still
> definitely appreciate any advice you have.
>
> Thanks again,
>
> Ben
>
>
> On Fri, Jan 14, 2011 at 1:53 PM, Ben Ganzfried wrote:
>
>> Hey guys,
>>
>> I'm using a tutorial geared for a 2.x version of Python and I am currently
>> using Python 3.1-- so it is possible that my confusion has to do with
>> different notations between them.  But in any case, here is what I have:
>>
>> >>> type(Time)
>> 
>> >>> t1 = Time()
>> >>> type(t1)
>> 
>>
>> where:
>>
>> class Time:
>> def __init__(self, hours = 0, minutes = 0, seconds = 0):
>>self.hours = hours
>>self.minutes = minutes
>>self.seconds = seconds
>>
>> def print_time(t1):
>> print(t.hours, ":", t.minutes, ":", t.seconds)
>>
>> Now the book I am working with has the following example:
>>
>> >>> type(Point)
>> 
>> >>> p = Point()
>>
>> >>> type(p)
>> 
>>
>> My questions are the following:
>> 1) Why is the type for my class Time : >>> type(Time)
>>   > 'type'>
>> when the type for their class Point is: 
>> Also, what is the difference between "class" and "classobj" in this case?
>> 2) Why does my t1 object give the following as its type: > '__main__.Time'>
>> And in their p object example the type is: ?
>> 3) What is happening such that when I try to call my print_time(t1)
>> function I get the following error:
>> >>> t1 = Time()
>> >>> t1.hours = 3
>> >>> t1.minutes = 30
>> >>> t1.seconds = 45
>> >>> print_time(t1)
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> print_time(t1)
>> NameError: name 'print_time' is not defined
>>
>>
>> Thank you very much.
>>
>> Sincerely,
>>
>> Ben
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OOP question

2011-01-18 Thread Ben Ganzfried
Hey guys,

I'm trying to get a version of Roulette working and I had a quick question.
Here is my code:

class Outcome:

def __init__(self, name, odds):
self.name = name
self.odds = odds

def winAmount(self, amount):
return odds*amount

def __eq__(self, other):
if (self == other):
return True
else:
return False

def __ne__(self, other):
if (self != other):
return True
else:
return False

def __str__(self):
return "%s (%d:1)" % ( self.name, self.odds )

Now whenever I try to call the winAmount method, I get the following error:
NameError: global name 'odds' is not defined

I'm wondering the following: I had thought that by initializing "odds" in
the first initialization method that "odds" should then be accessible to all
the other methods in the class.  This does not seem to be the case.  So what
is the ideal fix?  On the one hand I still need to initialize "odds",
right?  But if "odds" is within the initialization method, how else can it
be accessed by the other methods?

Thanks so much!

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Project Idea

2011-01-28 Thread Ben Ganzfried
Hey guys,

Would it be feasible for a beginner to write a script that could connect
with:
https://chrome.google.com/extensions/detail/laankejkbhbdhmipfmgcngdelahlfoji
?  More specifically, I am interested in writing a script such that the user
would have to enter a short password (say 6 random letters) and only then
could they access the Internet.  (Also, it looks like stayfocusd only works
for google chrome...i'd love for my script to apply to all other internet
browsers that may be installed on a computer as well).

If so, I would love to hear any tips or advice for getting started that you
could suggest.

Thanks a bunch,

Ben
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Roulette Unit Test Questions

2011-02-05 Thread Ben Ganzfried
Hey,

I'm having a lot of confusion getting the unit test working for one of my
classes for the Roulette bot I'm working on and would greatly appreciate any
advice or help.

Here is the description of what I am trying to do:
http://homepage.mac.com/s_lott/books/oodesign/build-python/html/roulette/bin.html
.  Basically, I have my Bin class working and I am trying to get my BinTest
class to do the following: Perform a unit test of the
Binclass.
The unit test should create several instances of
Outcome,
two instances of
Binand
establish that
Bins
can be constructed from the
Outcome
s.

While I would greatly appreciate any pointers in fixing my mistakes, I would
also greatly appreciate any pointers telling me what exactly it is that I do
not yet understand.

Thanks a bunch, my code is below.

Here is my Bin class:

from Outcome import *
class Bin:

def __init__(self, *outcomes):
self.outcomes = outcomes

def add(self, outcome):
self.outcomes += outcome
return self.outcomes
def __str__(self):
return (', '.join( map(str,self.outcomes)))



Here is the code for my BinTest class:

import Outcome
import Bin

class BinTest:
def __init__(self):
pass

def create_Outcome(outcome):
o1 = Outcome(outcome)

#creates two instances of Bin
def create_Bin():
b1 = Bin(("Red", 5), ("Black", 17),("Red", 5))
b2 = Bin(("00-0-1-2-3"), ("00"))
#establishes that Bin can be constructed from Outcome
def construct_Bin_from_Outcome():
b3 = Bin(o2)
b4 = Bin(o4)
b5 = Bin(o1)

def main():
bin_test1 = BinTest()
bin_test1.create_Outcome()
#create_Outcome("Red", 5)
#create_Outcome("Black", 17)
#create_Outcome("Red", 5)
#create_Outcome("00-0-1-2-3")
#create_Outcome("00")

print("o2 is ", o2)
print("o3 is ", o3)
print("o4 is ", o4)
print("o5 is ", o5)
print("b1 is ", b1)
print("b2 is ", b2)
print("b3 is ", b3)
print("b4 is ", b4)
print("b5 is ", b5)

if __name__ == "__main__":
main()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Tic-Tac-Toe

2011-02-19 Thread Ben Ganzfried
Hey,

I *think* that everything is working except my function gameWon.  I keep
getting the following error: " line 67, in gameWon
if (cell % 3 == 0) and (self.__mycells[cell] ==  self.__mycells[cell +
1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]):
TypeError: unsupported operand type(s) for %: 'instance' and 'int'
>>> "

My thinking was the following: I wanted to check the verticals, horizontals,
and diagonals to see if they were the same.  If so, then the game is won.
I'm not sure why I'm not actually comparing the value inside the appropriate
cells, but clearly the error means that what I'm trying to do is not what is
actually happening.  My full code is below and I would greatly appreciate
any help you can provide.

Thanks,

Ben

_-

#Ben Ganzfried
#2/18/11
#Tic-Tac-Toe

class Player:


def __init__(self, name, type):
self.__name = name
self.__type = type

def move(self):
cell_index = input("%s's (%s) move: " & (self.__name, self.__type))
cell_index = int(cell_index)
while cell_index > 8 and cell_index < 0:
print("Please retry...")
cell_index = input("%s's (%s) move: " & (self.__name,
self.__type))
return cell_index

def getName(self):
return self.__name

def getType(self):
return self.__type

class Board:

def __init__(self):
self.__mycells = []
for i in range(0, 9):
current_cell = Cell()
self.__mycells.append(current_cell)

def print1(self):
counter = 0
for cell in self.__mycells:
cell.print1()
counter +=1
if counter % 3 == 0:
print("\n")

def setCellToX(self, cell_number):
cell = self.__mycells[cell_number]
if not cell.isOccupied():
cell.setToX()
return True
else:
return False

def setCelltoO(self, cell_number):
cell = self.__mycells[cell_number]
if not cell.isOccupied():
cell.setToO()
return True
else:
return False

def isTied(self):
for cell in self.__mycells:
if not cell.isOccupied():
return False
return True

def gameWon(self):
for cell in self.__mycells:
#horizontals
if (cell % 3 == 0) and (self.__mycells[cell] ==
self.__mycells[cell + 1]) and (self.__mycells[cell + 1]==
self.__mycells[cell + 2]):
return True
#verticals
elif (cell < 3) and (self._mycells[cell] == self._mycells[cell +
3]) and (self._mycells[cell] == self.__mycells[cell + 6]):
return True
#diagonals
elif (cell == 0) and (self.__mycells[cell] ==
self.__mycells[cell + 4]) and (self.__mycells[cell] == self.__mycells[cell +
8]):
return True
elif (cell == 2) and (self.__mycells[cell] ==
self.__mycells[cell + 2]) and (self.__mycells[cell] == self.mycells[cell +
4]):
return True
return False


class Cell:

def __init__(self):
self.__value = " "

def setToX(self):
self.__value = "X"

def setToO(self):
self.__value = "O"

def print1(self):
print(self.__value,)
#add a predicate (start in terms of question, not action)
def isOccupied(self):
return not self.__value == " "

def main():
#initialize game
#draw board
#create two players
#enter a loop-- prompt each player for a loop...stops when a player wins
or a tie
board = Board()
board.print1()
pX = Player("Ben", "X")
pO = Player("Sam", "O")
while not board.gameWon() and not board.isTied():
c1 = pX.move()
success = board.setCellToX(c1)
while not success:
c1 = pX.move()
success = board.setCellToX(c1)
board.print1()
c1 = pO.move()
success = board.setCellToO(c1)
while not success:
c1 = pO.move()
success = board.setCellToO(c1)
board.print1()
print("Game Over")



if __name__ == "__main__":
main()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem recognizing '{' character?

2011-03-28 Thread Ben Hunter
Hi,

I'm completing the Python lessons on YouTube that Google posted. At the end
of section 2 of day 2, there is a task to identify files then put them in a
zip file in any directory. The code is from the 'solution' folder, so it's
not something I wrote. I suspect I have a problem with PATHS or environment
variables. I'm new to programming in something as advanced as Python, but I
do okay with VBA - so I just feel like there's a setting up issue somewhere.
I'm on Windows 7, tried running this in Idle and from the command line.

These two work perfectly.

def get_special_paths(dirname):
  result = []
  paths = os.listdir(dirname)  # list of paths in that dir
  for fname in paths:
match = re.search(r'__(\w+)__', fname)
if match:
  result.append(os.path.abspath(os.path.join(dirname, fname)))
  return result


def copy_to(paths, to_dir):
  if not os.path.exists(to_dir):
os.mkdir(to_dir)
  for path in paths:
fname = os.path.basename(path)
shutil.copy(path, os.path.join(to_dir, fname))

This third one does not.

def zip_to(paths, zipfile):
  """Zip up all of the given files into a new zip file with the given
name."""
  cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths)
  print "Command I'm going to do:" + cmd
  (status, output) = commands.getstatusoutput(cmd)
  # If command had a problem (status is non-zero),
  # print its output to stderr and exit.
  if status:
sys.stderr.write(output)
sys.exit(1)

My command is this: >>> copyspecial.zip_to(paths, 'zippy')

But something goes wrong and it spits this out:
'{' is not recognized as an internal or external command,
operable program or batch file.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem recognizing '{' character?

2011-03-29 Thread Ben Hunter
Thanks a ton. For the record I did read the 'command' module help page, but
must have skipped over the 'Platforms: Unix' and 'Deprecated' parts. I
successfully got it to work with the subprocess module, but I really
appreciate you filling out the rest with the sys.stderr.write(stderrdata). I
certainly would have stumbled over that.

-BJH


On Mon, Mar 28, 2011 at 8:12 PM, Ben Hunter  wrote:

> Hi,
>
> I'm completing the Python lessons on YouTube that Google posted. At the end
> of section 2 of day 2, there is a task to identify files then put them in a
> zip file in any directory. The code is from the 'solution' folder, so it's
> not something I wrote. I suspect I have a problem with PATHS or environment
> variables. I'm new to programming in something as advanced as Python, but I
> do okay with VBA - so I just feel like there's a setting up issue somewhere.
> I'm on Windows 7, tried running this in Idle and from the command line.
>
> These two work perfectly.
>
> def get_special_paths(dirname):
>   result = []
>   paths = os.listdir(dirname)  # list of paths in that dir
>   for fname in paths:
> match = re.search(r'__(\w+)__', fname)
> if match:
>   result.append(os.path.abspath(os.path.join(dirname, fname)))
>   return result
>
>
> def copy_to(paths, to_dir):
>   if not os.path.exists(to_dir):
> os.mkdir(to_dir)
>   for path in paths:
> fname = os.path.basename(path)
> shutil.copy(path, os.path.join(to_dir, fname))
>
> This third one does not.
>
> def zip_to(paths, zipfile):
>   """Zip up all of the given files into a new zip file with the given
> name."""
>   cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths)
>   print "Command I'm going to do:" + cmd
>   (status, output) = commands.getstatusoutput(cmd)
>   # If command had a problem (status is non-zero),
>   # print its output to stderr and exit.
>   if status:
> sys.stderr.write(output)
> sys.exit(1)
>
> My command is this: >>> copyspecial.zip_to(paths, 'zippy')
>
> But something goes wrong and it spits this out:
> '{' is not recognized as an internal or external command,
> operable program or batch file.
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Data frame packages

2011-03-31 Thread Ben Hunter
Is anybody out there familiar with data frame modules for python that will
allow me to read a CSV in a similar way that R does? pydataframe and
DataFrame have both befuddled me. One requires a special stripe of R that I
don't think is available on windows and the other is either very buggy or
I've put it in the wrong directory / installed incorrectly. Sorry for the
vague question - just taking the pulse. I haven't seen any chatter about
this on this mailing list.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Data frame packages

2011-03-31 Thread Ben Hunter
I appreciate all the responses and apologize for not being more detailed. An
R data frame is a tightly grouped array of vectors of the same length. Each
vector is all the same datatype, I believe, but you can read all types of
data into the same variable. The benefit is being able to quickly subset,
stack and such (or 'melt' and 'cast' in R vernacular) according to any of
your qualitative variables (or 'factors'). As someone pretty familiar with R
and quite a newbie to python, I'm wary of insulting anybody's intelligence
by describing what to me is effectively the default data format my most
familiar language. The following is some brief R code if you're curious
about how it works.

d <- read.csv(filename, header = TRUE, sep = ',') #this reads the table.
'<-' is the assignment operator
d[ , 'column.name'] # this references a column name. This same syntax can be
used to reference all rows (index is put left of the comma) and columns in
any order.

The data frame then allows you to quickly declare new fields as functions of
other fields.
newVar <- d[ ,'column.name'] + d[ ,'another.column']
d$newVar <- newVar # attaches newVar to the rightmost column of 'd'

At any rate, I finally got pydataframe to work, but had to go from Python
2.6 to 2.5. pydataframe has a bug for Windows that the author points out.
Line 127 in 'parsers.py' should be changed from:
columns = list(itertools.izip_longest(*split_lines ,fillvalue = na_text))

to:
columns = list(itertools.izip_longest(list(*split_lines),fillvalue =
na_text))

I don't know exactly what I did, but the module would not load until I did
that. I know itertools.izip_longest requires 2 arguments before fillvalue,
so I guess that did it.

It's a handy way to handle alpha-numeric data. My problem with the csv
module was that it interpreted all numbers as strings.

Thanks again.

On Thu, Mar 31, 2011 at 8:17 AM, James Reynolds  wrote:

>
>
> On Thu, Mar 31, 2011 at 11:10 AM, Blockheads Oi Oi <
> breamore...@yahoo.co.uk> wrote:
>
>> On 31/03/2011 09:38, Ben Hunter wrote:
>>
>>> Is anybody out there familiar with data frame modules for python that
>>> will allow me to read a CSV in a similar way that R does? pydataframe
>>> and DataFrame have both befuddled me. One requires a special stripe of R
>>> that I don't think is available on windows and the other is either very
>>> buggy or I've put it in the wrong directory / installed incorrectly.
>>> Sorry for the vague question - just taking the pulse. I haven't seen any
>>> chatter about this on this mailing list.
>>>
>>>
>>>
>> What are you trying to achieve?  Can you simply read the data with the
>> standard library csv module and manipulate it to your needs?What makes
>> you say that the code is buggy, have you examples of what you tried and
>> where it was wrong?  Did you install with easy_install or run setup.py?
>>
>>
>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>> Regards.
>>
>> Mark L.
>>
>>
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> I'm not familiar with it, but what about http://rpy.sourceforge.net/
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] installing where does my money go

2011-04-07 Thread Ben Teeuwen
Hi everyone, 

I'm a total newbie giving his best shot at visualising local educational 
institution's faculty budget (over 60 million) to stir up some healthy 
democratic debate, by trying to adapt the code from 
http://wheredoesmymoneygo.org/getting-started/. Its open source, so I'm trying 
out how far I'll wind up :).

I'm installing the setup below (see 
http://wheredoesmymoneygo.org/getting-started/).
I've got a mac os 10.6.7, python 2.7.1, pip, and the most recent postgres 
installation. 

I get stuck at;
"Run setup.py to install all required local packages. (Needs more details...)"

bteeuwen@Ben-3 ~/Sites/wdmmg]$./setup.py
from: can't read /var/mail/setuptools
from: can't read /var/mail/wdmmg
./setup.py: line 4: syntax error near unexpected token `newline'
./setup.py: line 4: `setup('

Then I added this to setup.py:
#!/usr/bin/python

This is where I end:
bteeuwen@Ben-3 ~/Sites/wdmmg]$./setup.py
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/dist.py:266:
 UserWarning: Unknown distribution option: 'paster_plugins'
  warnings.warn(msg)
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

Anyone any advice where to look for answers? Thx!!

Ben

__

sInstallation and Setup
==

Steps to set up WDMMG from scratch. May not be comprehensive, please edit.

--

Install Postgres (or any other sqlalchemy compatible DB) on your machine.
Create a new database called 'production', add a superuser: note down the
username and password.

  $ sudo -u postgres createuser -P nameofuser
  $ sudo -u postgres createdb --owner nameofuser nameofdb

--

Check out wdmmg from the Mercurial repository. 

$ hg clone http://knowledgeforge.net/okfn/wdmmg

[OUTDATED: For info: This will create a "wdmmg" directory with everything in 
it. Inside,
you will find:

 - "doc": self-explanatory.
 - "econdata": source code for some fo our data packages.
 - "wdmmg": source code for the data store.
 - "wdmmgrdf": version of the data store with an RDF backend (dormant).
 - "flash": source code for the dashboard.

Inside "wdmmg/wdmmg" you will find a pretty standard Pylons application. Thex
main part is a Python package called (you guessed it) "wdmmg". So the actual
code is inside "wdmmg/wdmmg".]

--

Run setup.py to install all required local packages. (Needs more details...)

--

Install 'wdmmg' using pip. NB {your-pyenv] here means
'the location of your virtualenv if you have one'::

$ pip -E {your-pyenv} install -r pip-requirements.txt

--

Create a config file called development.ini (this has the config options needed
to run the site locally): 

$ paster make-config wdmmg development.ini

--

Edit development.ini with Solr and SQLAlchemy details for your local machine: 

solr.url = url of remote Solr script (can be found in .ini files 
on servers), or just 'stub' if you prefer

sqlalchemy.url = postgres://username:password@localhost/production

--

Sync the database tables and set up the application:

$ paster setup-app development.ini

--

For data store theme:

Get main wdmmg theme files from the mercurial repository at::

  http://bitbucket.org/okfn/wdmmg-wp-theme

And put them at::

  wdmmg/public/themes/wdmmg

--

Install some data (not sure if this really belongs here?)

$ chmod a+x install_data.sh
$ ./install_data.sh

--

Run tests, edit anything that is broken::

$ nosetests 

--

Load fixtures so you have some sample data::

$ paster fixtures setup 

[
Alternatively, if you want the full datasets, run the install_data script 
(slow)::

  $ chmod a+x install_data.sh
  $ ./install_data.sh

]

--

Finally, run the site from development.ini::

  $ paster serve --reload development.ini

--

Start hacking!

Trac repository: 
http://knowledgeforge.net/okfn/tasks/query?status=assigned&status=new&status=reopened&component=projects.wdmmg&order=priority&col=id&col=summary&col=cc&col=status&col=owner&col=type&col=priority


How to Upgrade Production Service
=

3 dbs/systems:
  * data.wheredoesmymoneygo.org - P1
  * data.wheredoesmymoneygo.org.2 - P2
  * data.staging.wheredoesmymoneygo.org - S1

Suppose P1 = active production, P2 = inactive production

  * Shut down write to the main system (Hack way: LimitExcept GET in Apache)
  * Dump active production db and load into inactive production db
  * Upgrade inactiv

[Tutor] ImportError: No module named wdmmgext.load

2011-04-11 Thread Ben Teeuwen
Hi, 

Thanks Emile van Sebille for answering my last question.
I'm now testing my imported data and I get 21 errors (see attached). The 
majority sounds like:

from wdmmgext.load import uganda
ImportError: No module named wdmmgext.load

I've searched the files that use this module. Attached is an example file.

I see 2 more errors;
1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 
2) SolrException: HTTP code=404, reason=Not Found
Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and 
first try to find answer to my first question.

Thanks in advance for the help!

Ben

import json
import os
import pkg_resources
import wdmmg.model as model
from wdmmgext.load import uganda

class TestDepartments(object):

@classmethod
def setup_class(self):
model.repo.delete_all()
model.Session.remove()
self.name = uganda.dataset_name
filepath = 'wdmmg/tests/uganda_sample.xls'
test_file = os.path.abspath(filepath)
uganda.load_files(filename=test_file, commit_every=10)
model.Session.commit()
model.Session.remove()

@classmethod
def teardown_class(self):
model.repo.delete_all()
model.Session.commit()
model.Session.remove()

# check dataset exists
def test_01_dataset(self):
out = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).first()
assert out, out

# Get our keys, and check values exist for them.
def test_02_classification(self):
for key_name in [u'from', u'time', u'uganda_id', u'gou_vote',
u'vote_name', u'project_code', u'project_name', 
u'funded_by_donor',
u'funded_by_govt', u'mtef_sector', u'mtef_reference', 
u'swg', u'sector_objective', u'peap1_pillar', 
u'peap2_objective', u'peap3_area']:
key = 
model.Session.query(model.Key).filter_by(name=key_name).first()
assert key, key_name
count = (model.Session.query(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(key=key)
).count()
assert count, (key_name, count)

# Check there are some entries and none of them are null
def test_03_entry(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
count = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).count()
assert count, 'There are no Entries'
assert not (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
.filter_by(amount=None)
).first(), 'Some Entries have NULL amounts'

# Look for a 'to' field on the first entry in the dataset.
def test_04_entry_to(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
txn = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).first()
classif = txn.classification_as_dict()
print classif['to']
assert classif['to'] == 'uganda-society'
EE....EEE
==
ERROR: test suite for 
--
Traceback (most recent call last):
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 208, in run
self.setUp()
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 291, in setUp
self.setupContext(ancestor)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 314, in setupContext
try_run(context, names)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/util.py",
 line 478, in try_run
return func()
  File "/Users/bteeuwen/Sites/wdmmg/wdmmg/tests/functional/test_aggregate.py", 
line 8, in setup_class
Fixtures.setup()
  File "/Users/bteeuwen/Sites/wdmmg/wdmmg/lib/cli.py", line 101, in setup
from wdmmgext.load import cofog
ImportError: No module named wdmmgext.load
 >> begin captured logging << 
pylons.configuration: DEBUG: Initializing configuration, package: 'wdmmg'
pylons.configuration: DEBUG: Pushing process configuration
pylons.configuration: DEBUG: Adding mako engine with alias None and 
{'myghty.data_dir': &

[Tutor] ImportError: No module named wdmmgext.load

2011-04-15 Thread Ben Teeuwen
Hi, 

I'm trying to install the code from 
http://wheredoesmymoneygo.org/getting-started/ on my local machine. I've got a 
mac os 10.6.7, python 2.7.1, pip, and the most recent postgres installation. 
I'm now testing imported data and I get 21 errors (see attached). The majority 
sounds like:

   from wdmmgext.load import uganda
ImportError: No module named wdmmgext.load

I've searched the files that use this module. Attached is an example file.

I see 2 more errors;
1) that the file 'ukgov-finances-cra/cra_2009_db.csv' does not exist. 
2) SolrException: HTTP code=404, reason=Not Found
Maybe both are due to the wdmmgext.load error, so I'll ignore this for now and 
first try to find answer to my first question.

Thanks in advance for the help!

Ben

import json
import os
import pkg_resources
import wdmmg.model as model
from wdmmgext.load import uganda

class TestDepartments(object):

@classmethod
def setup_class(self):
model.repo.delete_all()
model.Session.remove()
self.name = uganda.dataset_name
filepath = 'wdmmg/tests/uganda_sample.xls'
test_file = os.path.abspath(filepath)
uganda.load_files(filename=test_file, commit_every=10)
model.Session.commit()
model.Session.remove()

@classmethod
def teardown_class(self):
model.repo.delete_all()
model.Session.commit()
model.Session.remove()

# check dataset exists
def test_01_dataset(self):
out = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).first()
assert out, out

# Get our keys, and check values exist for them.
def test_02_classification(self):
for key_name in [u'from', u'time', u'uganda_id', u'gou_vote',
u'vote_name', u'project_code', u'project_name', 
u'funded_by_donor',
u'funded_by_govt', u'mtef_sector', u'mtef_reference', 
u'swg', u'sector_objective', u'peap1_pillar', 
u'peap2_objective', u'peap3_area']:
key = 
model.Session.query(model.Key).filter_by(name=key_name).first()
assert key, key_name
count = (model.Session.query(model.ClassificationItem)
.join(model.EnumerationValue)
.filter_by(key=key)
).count()
assert count, (key_name, count)

# Check there are some entries and none of them are null
def test_03_entry(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
count = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).count()
assert count, 'There are no Entries'
assert not (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
.filter_by(amount=None)
).first(), 'Some Entries have NULL amounts'

# Look for a 'to' field on the first entry in the dataset.
def test_04_entry_to(self):
dataset_ = (model.Session.query(model.Dataset)
.filter_by(name=self.name)
).one()
txn = (model.Session.query(model.Entry)
.filter_by(dataset_=dataset_)
).first()
classif = txn.classification_as_dict()
print classif['to']
assert classif['to'] == 'uganda-society'
EE....EEE
==
ERROR: test suite for 
--
Traceback (most recent call last):
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 208, in run
self.setUp()
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 291, in setUp
self.setupContext(ancestor)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/suite.py",
 line 314, in setupContext
try_run(context, names)
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/util.py",
 line 478, in try_run
return func()
  File "/Users/bteeuwen/Sites/wdmmg/wdmmg/tests/functional/test_aggregate.py", 
line 8, in setup_class
Fixtures.setup()
  File "/Users/bteeuwen/Sites/wdmmg/wdmmg/lib/cli.py", line 101, in setup
from wdmmgext.load import cofog
ImportError: No module named wdmmgext.load
 >> begin captured logging << 
pylons.configuration: DEBUG: Initializing configuration, package: 'wdmmg'
pylons.configuration: DEBUG: Pushin

Re: [Tutor] running more than one python program at the same time

2012-08-28 Thread Ben Fishbein
I'm on a Mac. Using Lion. I just tried opening the terminal and typing
"python." And I'm able to open several terminal windows this way. I think
this should be able to run many programs simultaneously. Thanks for your
help.
-Ben


On Tue, Aug 28, 2012 at 6:04 PM, Brian van den Broek <
brian.van.den.br...@gmail.com> wrote:

>
> On 28 Aug 2012 18:33, "Benjamin Fishbein"  wrote:
> >
> > Hello,
> > I wrote a program that I want to have running 24/7. But the problem is
> that I also want to write and run other programs. I'm using Idle and it
> won't let me run more than one script at a time. Do you know if there's a
> way to do this? Or do I need to buy a second computer?
> > Thanks,
> > Ben
>
> Hi Ben,
>
> Idle may be useful for developing with (provided you aren't making an app
> with tkinter) but isn't always the best choice for running one.
>
> Do you know how to run python from a command prompt? (If not, post back to
> the list being sure to tell us your OS and I or someone else will help
> you.) If you run you 24/7 program that way, idle will be free for you to
> work. There are other ways to get your program to run in the background,
> but again these are OS-dependant.
>
> Best,
>
> Brian vdB
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] running more than one python program at the same time

2012-08-28 Thread Ben Fishbein
Stupid question: how do I run a program from the terminal? I've always just
gone to the drop down menu and clicked run to do it in idle.

On Tue, Aug 28, 2012 at 6:17 PM, Ben Fishbein  wrote:

> I'm on a Mac. Using Lion. I just tried opening the terminal and typing
> "python." And I'm able to open several terminal windows this way. I think
> this should be able to run many programs simultaneously. Thanks for your
> help.
> -Ben
>
>
> On Tue, Aug 28, 2012 at 6:04 PM, Brian van den Broek <
> brian.van.den.br...@gmail.com> wrote:
>
>>
>> On 28 Aug 2012 18:33, "Benjamin Fishbein"  wrote:
>> >
>> > Hello,
>> > I wrote a program that I want to have running 24/7. But the problem is
>> that I also want to write and run other programs. I'm using Idle and it
>> won't let me run more than one script at a time. Do you know if there's a
>> way to do this? Or do I need to buy a second computer?
>> > Thanks,
>> > Ben
>>
>> Hi Ben,
>>
>> Idle may be useful for developing with (provided you aren't making an app
>> with tkinter) but isn't always the best choice for running one.
>>
>> Do you know how to run python from a command prompt? (If not, post back
>> to the list being sure to tell us your OS and I or someone else will help
>> you.) If you run you 24/7 program that way, idle will be free for you to
>> work. There are other ways to get your program to run in the background,
>> but again these are OS-dependant.
>>
>> Best,
>>
>> Brian vdB
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How (not!) lengthy should functions be?

2015-04-16 Thread Ben Finney
boB Stepp  writes:

> My current understanding of function length best practice is that: 1)
> Each function should have preferably ONE clearly defined purpose.

Yes, that's a principle to follow firmly, improving the design every
time. I know of no exceptions.

“Clearly defined” also entails the function signature (its name, what
parameters it accepts, what return value it emits) is narrowly defined.

> 2) I have seen varying recommendations as to number of lines of code
> per function, but I have seem multiple recommendations that a function
> generally should fit into one screen on one's monitor.

A function that is clearly-designed, as above, should have no more than
a handful of statements. That's intentionally vague, but it's already
shorter than “a screenful”.

> Of course, some people have HUGE monitors! And I assume that any
> guidance applies equally well to methods.

Any function with statements stretching over 20 lines is already too
large, IMO.

Note that the docstring can be rather lengthy, if there is a lot to say
about the function's purpose or strange cases it handles.

> Am I on-track or am I getting carried away?

You're right to care about precision in your code. Overlong, overbroad,
overcomplex, overdetermined functions happen through laziness; it takes
diligence to keep the code readable through refactoring while you go.
That takes more effort at each edit, but saves a lot of debugging time.

Having such a principle in mind, and knowing that it's worth spending
effort to uphold, will serve you well.

-- 
 \ “Outside of a dog, a book is man's best friend. Inside of a |
  `\dog, it's too dark to read.” —Groucho Marx |
_o__)  |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lists, name semantics

2015-04-17 Thread Ben Finney
Bill Allen  writes:

> If I have a list defined as my_list = ['a','b','c'], what is the is
> differnce between refering to it as my_list or my_list[:]?

‘my_list’ is a reference to the object you've already described (the
existing object ‘['a', 'b', 'c']’).

‘my_list[:]’ is an operation that takes the original object and creates
a new one by slicing. In this case, the new object happens to be equal
to (but probably not identical to) the original, because of the slice
you specified.

> Is there any nuance I am missing here? Situations where one form
> should be used as opposed to the other?

You need to understand, when writing code, whether you are intending to
refer to the original object, or to create a new one. Neither is better,
they are both common but different operations.

-- 
 \  “Our products just aren't engineered for security.” —Brian |
  `\ Valentine, senior vice-president of Microsoft Windows |
_o__)development, 2002 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lists, name semantics

2015-04-17 Thread Ben Finney
Ben Finney  writes:

> Bill Allen  writes:
>
> > If I have a list defined as my_list = ['a','b','c'], what is the is
> > differnce between refering to it as my_list or my_list[:]?
>
> ‘my_list’ is a reference to the object you've already described (the
> existing object ‘['a', 'b', 'c']’).
>
> ‘my_list[:]’ is an operation that takes the original object and
> creates a new one by slicing. In this case, the new object happens to
> be equal to (but probably not identical to) the original, because of
> the slice you specified.

To demonstrate how identity differs from equality, use the appropriate
comparison operators::

$ python3

>>> foo = ['a', 'b', 'c']

>>> bar = foo # Bind the name ‘bar’ to the same object.
>>> bar   # Show me the object referred to by ‘bar’.
['a', 'b', 'c']
>>> bar == foo# Is the object ‘bar’ equal to the object ‘foo’?
True
>>> bar is foo# Is ‘bar’ referring to the same object as ‘foo’?
True

>>> baz = foo[:]  # Slice ‘foo’, creating a new list; bind ‘baz’ to that.
>>> baz   # Show me the object referred to by ‘baz’.
['a', 'b', 'c']
>>> baz == foo# Is the object ‘baz’ equal to the object ‘foo’?
True
>>> baz is foo# Is ‘baz’ referring to the same object as ‘foo’?
False

References which compare identical *are the same* object, guaranteed.
Object identity almost always implies equality.

(“almost always” because some object types have unusual behaviour like
“the object is not equal to itself”. Don't fret about that though, these
exceptions are clearly defined when you find them.)


References which compare equal *may under some conditions* be identical.
This is *not* ever a promise, though, and you should never rely on it,
not even in the same session of a program.

Some of Python's internal optimisations depend on the fact that object
equality *does not* imply object identity. If you happen to notice some
operations producing the same object at one point in time, but the
documentation doesn't promise it, then treat that as an unpredictable
implementation detail and don't rely on it in your code.

-- 
 \   “The best in us does not require the worst in us: Our love of |
  `\ other human beings does not need to be nurtured by delusion.” |
_o__) —Sam Harris, at _Beyond Belief 2006_ |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sample dictionairies

2015-04-19 Thread Ben Finney
Jim Mooney  writes:

> Where could I download Python sample dictionaries on different
> subjects.

I don't know what yoy mean by the “subject” of a dictionary.

A Python dict is a data structure. Its values can be any collection of
Python objects.

Is the “subject” of a dictionary its meaning? Its meaning is entirely up
to whoever wrote it and whoever reads it.

So I have to guess that you mean something else. What do you mean by
“dictionaries on different subjects”?

-- 
 \“Technology is neither good nor bad; nor is it neutral.” |
  `\   —Melvin Kranzberg's First Law of Technology |
_o__)      |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Life Grid Implementation

2015-04-20 Thread Ben Finney
niy mor  writes:

> Is my code completing the assignment???

Does it meet the requirements when you (and other people) run the code?

> I need some *guidance* on completing my assignment.

Can you be specific about what you don't understand?

If you don't understand the requirements, that is best discussed with
your course supervisor, not us.

-- 
 \   “Kissing a smoker is like licking an ashtray.” —anonymous |
  `\   |
_o__)      |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sample dictionairies

2015-04-20 Thread Ben Finney
Jim Mooney  writes:

> I should have known to simply try importing csv.

Better: You should now know to refer to the documentation
https://docs.python.org/3/library/>.

-- 
 \  “Speech is conveniently located midway between thought and |
  `\action, where it often substitutes for both.” —John Andrew |
_o__)  Holmes, _Wisdom in Small Doses_ |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] introspection

2015-04-20 Thread Ben Finney
Alex Kleider  writes:

> Does python provide the introspective ability to retrieve the name to
> which an object is bound?

Objects aren't bound to names. So, no.

The binding from a reference (a name is a reference) to objects is
one-way.

See this excellent presentation from PyCon US 2015 by Ned Batchelder
https://www.youtube.com/watch?v=_AEJHKGk9ns>.

-- 
 \ “I must say that I find television very educational. The minute |
  `\   somebody turns it on, I go to the library and read a book.” |
_o__)—Groucho Marx |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Ben Finney
Jim Mooney  writes:

> I can't seem to get my head around this 'simple' book example of
> binary-to-decimal conversion, which goes from left to right:
>
> B = '11011101'
> I = 0
> while B:
> I = I * 2 + int(B[0])
> B = B[1:]
>
> print(I)
> >>> 221

That is, IMO, a needlessly confusing way to write that code.

Whoever wrote it is clearly pleased with how clever it is; but
cleverness is almost always a property of *bad* code because it's
difficult to understand at a glance. That's the case here.

One significant problem with the code as written is that it uses a
‘while’ loop and mutates the list, where there's no point; it should
just iterate over items *from* the list without changing it.

Another significant problem is that it uses moronically-short,
completely unexpressive names. This is Python not FORTRAN.

Try this::

binary_text = '11011101'
result = 0

for binary_digit in binary_text:
# Accumulate powers of 2 for each digit.
result = result * 2 + int(binary_digit)

print(result)

> Both methods work but I just can't see how the first one does. Am I
> missing something obvious here?

No, you were missing something needlessly obscured by the badly-written
code. Which book is this? I will be sure never to recommend it.

Hope that helps.

-- 
 \ “Science is a way of trying not to fool yourself. The first |
  `\ principle is that you must not fool yourself, and you are the |
_o__)   easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-21 Thread Ben Finney
"Martin A. Brown"  writes:

> Good morning underscore underscore Peter underscore underscore,

The Pythonic way to pronounce that would be “dunder Pete dunder”
https://wiki.python.org/moin/DunderAlias>.

-- 
 \ “Geeks like to think that they can ignore politics. You can |
  `\leave politics alone, but politics won't leave you alone.” |
_o__) —Richard M. Stallman, 2002-07-26 |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] introspection

2015-04-21 Thread Ben Finney
Alex Kleider  writes:

> I was hoping that it would be possible to create a function
> that would do the following:
>
> def my_name(some_object):
>   return some_object.__name__

That hope is understandable.

It is also easy to be confused about why such a feature doesn't exist;
after all, it works for functions and classes and modules (oh my!)::

>>> def foo(): pass
... 
>>> foo.__name__
'foo'
>>> class Bar: pass
... 
>>> Bar.__name__
'Bar'
>>> import sys
>>> sys.__name__
'sys'

So why not arbitrary objects?

>>> spam = 4
>>> spam.__name__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute '__name__'

The answer is that functions, classes, and modules are all *defined*,
and (normally) have exactly one canonical name established at definition
time.

Arbitrary objects are merely *instantiated*, without that definition
step. Quite commonly they are used with no name bound to them; so the
behaviour of most objects does not have ‘__name__’ in the API.

If you would like to make a class that has that attribute on all its
instances, feel free. But you need to figure out how the instance
detects its own name!

class LockeanThing:
""" An object that knows the name by which others refer to it. """

def __init__(self):
self.__name__ = ???

> But I see what I think you and others have been trying to explain to
> me: that the expression some_object.__name__, if it existed, would
> indeed be schizophrenic since it would be an attribute of the object,
> not the name(s) to which it is bound.

That's why I prefer to be clear that the binding operation is one-way
only.

A reference (such as a name) is bound to an object, the object is not
bound to the reference — indeed, the object knows nothing about that
relationship.

-- 
 \“I washed a sock. Then I put it in the dryer. When I took it |
  `\ out, it was gone.” —Steven Wright |
_o__)  |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-22 Thread Ben Finney
Peter Otten <__pete...@web.de> writes:

> Ben Finney wrote:
>
> > The Pythonic way to pronounce that would be “dunder Pete dunder”
> > https://wiki.python.org/moin/DunderAlias>.
>
> Hm, should I campaign for a peter() builtin?

You'll need a working implementation first. Put it on BullCodes
https://bull.codes/> for bonus Python-based free-software
repository hosting points!

-- 
 \ “I'm a born-again atheist.” —Gore Vidal |
  `\   |
_o__)      |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-22 Thread Ben Finney
Albert-Jan Roskam  writes:

> - Original Message -
> > From: Ben Finney 
> > You'll need a working implementation first. Put it on BullCodes
> > https://bull.codes/> for bonus Python-based free-software
> > repository hosting points!
>
> Is bull.codes better than Github or Bitbucket?

Yes, because those are not free software.

http://mako.cc/writing/hill-free_tools.html>

Kallithea (which is what powers BullCodes) is free software, meaning
anyone is free to see how it works and change it and run their own
instance and share changes.

http://kallithea-scm.org/>

> Does it work with Travis CI and Appveyor?

Not until the Kallithea community adds that support. Since it is free
software that's more likely than if it were proprietary :-)

-- 
 \  “Reichel's Law: A body on vacation tends to remain on vacation |
  `\unless acted upon by an outside force.” —Carol Reichel |
_o__)      |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pun panic

2015-04-22 Thread Ben Finney
Alex Kleider  writes:

> On 2015-04-22 05:40, Ben Finney wrote:
> > http://mako.cc/writing/hill-free_tools.html>
> >
> > Kallithea (which is what powers BullCodes) is free software, meaning
> > anyone is free to see how it works and change it and run their own
> > instance and share changes.
> >
> > http://kallithea-scm.org/>
>
> […] I've been unable to find anything resembling a user (i.e. someone
> who wants to keep a project hosted on bull.code) 'howto' with regard
> to bull.code. Any suggestions?

I don't think BullCodes has a pointer to it yet, but: Kallithea's
documentation contains a “General Kallithea usage” section
https://docs.kallithea-scm.org/en/latest/usage/general.html>, is
that what you're looking for?

-- 
 \   “I have always wished for my computer to be as easy to use as |
  `\   my telephone; my wish has come true because I can no longer |
_o__)  figure out how to use my telephone.” —Bjarne Stroustrup |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Please disable “digest mode” before participating (was: Tutor Digest, Vol 134, Issue 86)

2015-04-25 Thread Ben Finney
Juanald Reagan  writes:

> Okay, so it doesn't look like that worked...here is the traceback. I don't
> understand the second part of your request.

Juanold, to keep the context and thread of the discussion, please
respond to individual messages, not digests.

To do that, you first need to disable “digest mode” on your
subscription. Change your settings by logging in here
https://mail.python.org/mailman/listinfo/python-list>.

Digest mode should only ever be used if you know for certain you will
never be responding to any message.

-- 
 \  “I moved into an all-electric house. I forgot and left the |
  `\   porch light on all day. When I got home the front door wouldn't |
_o__)open.” —Steven Wright |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   >