Re: [Tutor] PLEASE HELP

2018-04-13 Thread Mayo Adams
 discrete, not discreet.

On Fri, Apr 13, 2018 at 11:38 AM, Neil Cerutti  wrote:

> On 2018-04-13, David Rock  wrote:
> >
> >> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
> >>
> >> On 2018-04-12, Scharrer, Brianna  wrote:
> >>> Applications of basic language syntax
> >>>
> >>> Date/time string parsing
> >>>
> >>> Time stamps on data are often recorded in the standard ISO date
> >>> and time format as shown below
> >>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
> >>>
> >>> Write code that when given a datetime string and outputs a
> >>> human readable version exactly in the format specified below.
> >>
> >> I disagree that the first version isn't human readable. It is
> >> both human readable and stores the date/time in lexicographic
> >> order, which is extremly useful for both humans and machines.
> >
> > Don???t nitpick the definition of ???human readable;??? it
> > isn???t relevant to the assignment and just serves to confuse
> > the student.  Using the phrase ???human readable??? is just a
> > poor choice for describing the assignment parameters: changing
> > from one format to another (ISO -> ???standard English??? (for
> > lack of a better description of the target format).  That???s
> > the only thing that matters in this context.
>
> It is relevant to the assignment if the student hadn't noticed
> that the date was human readable. I was hoping to correct this
> possible misapprehension resulting from the poor assignment
> language.
>
> --
> Neil Cerutti
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Mayo Adams

287 Erwin Rd.
Chapel Hill, NC 27514
(919)-780-3917
mayoad...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PLEASE HELP

2018-04-13 Thread Neil Cerutti
On 2018-04-13, David Rock  wrote:
>
>> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
>> 
>> On 2018-04-12, Scharrer, Brianna  wrote:
>>> Applications of basic language syntax
>>> 
>>> Date/time string parsing
>>> 
>>> Time stamps on data are often recorded in the standard ISO date
>>> and time format as shown below
>>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>>> 
>>> Write code that when given a datetime string and outputs a
>>> human readable version exactly in the format specified below.
>> 
>> I disagree that the first version isn't human readable. It is
>> both human readable and stores the date/time in lexicographic
>> order, which is extremly useful for both humans and machines.
>
> Don???t nitpick the definition of ???human readable;??? it
> isn???t relevant to the assignment and just serves to confuse
> the student.  Using the phrase ???human readable??? is just a
> poor choice for describing the assignment parameters: changing
> from one format to another (ISO -> ???standard English??? (for
> lack of a better description of the target format).  That???s
> the only thing that matters in this context.

It is relevant to the assignment if the student hadn't noticed
that the date was human readable. I was hoping to correct this
possible misapprehension resulting from the poor assignment
language.

-- 
Neil Cerutti

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


Re: [Tutor] PLEASE HELP

2018-04-13 Thread David Rock

> On Apr 13, 2018, at 09:24, Neil Cerutti  wrote:
> 
> On 2018-04-12, Scharrer, Brianna  wrote:
>> Applications of basic language syntax
>> 
>> Date/time string parsing
>> 
>> Time stamps on data are often recorded in the standard ISO date
>> and time format as shown below
>> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>> 
>> Write code that when given a datetime string and outputs a
>> human readable version exactly in the format specified below.
> 
> I disagree that the first version isn't human readable. It is
> both human readable and stores the date/time in lexicographic
> order, which is extremly useful for both humans and machines.

Don’t nitpick the definition of “human readable;” it isn’t relevant to the 
assignment and just serves to confuse the student.  Using the phrase “human 
readable” is just a poor choice for describing the assignment parameters: 
changing from one format to another (ISO -> “standard English” (for lack of a 
better description of the target format).  That’s the only thing that matters 
in this context.

For the assignment, think about the following:

How to separate the date from the time
How to separate the -MM-DD into discreet variables
How to convert the digit month into a Full name (e.g, convert 2 -> February)
How to convert a 24-hour time into a 12-hour am/pm time
How to print the bits into a specific format

Tackle each part separately, and it should be fairly straightforward.  Look up 
methods for parsing formatted strings as a place to start.

— 
David Rock
da...@graniteweb.com




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


Re: [Tutor] PLEASE HELP

2018-04-13 Thread Neil Cerutti
On 2018-04-12, Scharrer, Brianna  wrote:
> Applications of basic language syntax
>
> Date/time string parsing
>
> Time stamps on data are often recorded in the standard ISO date
> and time format as shown below
>
> -mm-ddThh:mm:ss
>
> 2018-01-02T18:31:16 > 6:31pm on January 2, 2018
>
> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
>
> Write code that when given a datetime string and outputs a
> human readable version exactly in the format specified below.

I disagree that the first version isn't human readable. It is
both human readable and stores the date/time in lexicographic
order, which is extremly useful for both humans and machines.

> [Morning, Noon, Afternoon, Evening, or Night], X:XX[am or pm] on [Month as a 
> word] [day], [year]
>
> E.g. 1999-02-14T21:02:37 would be ?Night, 9:02pm on February 14, 1999?

You will need to ask for clarification from your teacher for the
deliniation between morning, noon, afternoon, evening and night.
There's no international standard I'm aware of.

>
> Do not use any datetime string function, though depending on
> your language they would be useful to do this in practice.

They certainly would!

> Hint: you?ll have to cast strings to integers in order to
> perform the if statements which place [Morning, Noon?], [am or
> pm] and [Month as a word] appropriately.

With the exception of converting string to integer (as Alan
discussed) I recommend using a dictionaries for conversion,
rather than if statements, if you're allowed.

-- 
Neil Cerutti

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


Re: [Tutor] PLEASE HELP

2018-04-12 Thread Alan Gauld via Tutor
On 12/04/18 18:24, Scharrer, Brianna wrote:

What appears below seems to be an assignment of some kind.
We do not do your work for you although we will offer help.
But it is best if you show us your work so far, or at
least describe how you intend to tackle it.

In this case you are being given a string and need to
convert it to a different format. It is not clear how
you should expect to "be given" the input data but
I assume you can read it from a user?

In Python you have many string methods to help you
slice/split the input into its parts. Look at the slice
operations and the split method. Given the fixed
lengths involved here slicing is probably easiest.

The assignment suggests "casting" the string to integers
but I think this is poor terminology and what is meant
is that you should convert the substrings into integers
(casting and conversion are very different things!).

Get back to us when you have something to show us or
a specific query.

> Applications of basic language syntax
> 
> Date/time string parsing
> 
> Time stamps on data are often recorded in the standard ISO date and time 
> format as shown below
> 
> -mm-ddThh:mm:ss
> 
> 2018-01-02T18:31:16 > 6:31pm on January 2, 2018
> 
> 1999-02-14T21:02:37 > 9:02pm on February 14, 1999
> 
> 
> Write code that when given a datetime string and outputs a human readable 
> version exactly in the format specified below.
> 
> [Morning, Noon, Afternoon, Evening, or Night], X:XX[am or pm] on [Month as a 
> word] [day], [year]
> 
> E.g. 1999-02-14T21:02:37 would be “Night, 9:02pm on February 14, 1999”
> 
> Do not use any datetime string function, though depending on your language 
> they would be useful to do this in practice.
> 
> Hint: you’ll have to cast strings to integers in order to perform the if 
> statements which place [Morning, Noon…], [am or pm] and [Month as a word] 
> appropriately.



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


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


[Tutor] PLEASE HELP

2018-04-12 Thread Scharrer, Brianna
Applications of basic language syntax

Date/time string parsing


Time stamps on data are often recorded in the standard ISO date and time format 
as shown below

-mm-ddThh:mm:ss

2018-01-02T18:31:16 > 6:31pm on January 2, 2018

1999-02-14T21:02:37 > 9:02pm on February 14, 1999


Write code that when given a datetime string and outputs a human readable 
version exactly in the format specified below.

[Morning, Noon, Afternoon, Evening, or Night], X:XX[am or pm] on [Month as a 
word] [day], [year]

E.g. 1999-02-14T21:02:37 would be “Night, 9:02pm on February 14, 1999”

Do not use any datetime string function, though depending on your language they 
would be useful to do this in practice.

Hint: you’ll have to cast strings to integers in order to perform the if 
statements which place [Morning, Noon…], [am or pm] and [Month as a word] 
appropriately.


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


Re: [Tutor] please help me with after method

2016-11-17 Thread Alan Gauld via Tutor
Always use REply-All or Reply-List to the tutor list.

On 17/11/16 18:34, Freedom Peacemaker wrote:
> Thank you Alan for answer but i still cant make it. I have improved my
> program but it still uses root.update() and now my app looks
> professional :) It is my first program. I am self learning Python
> since july this year but still i need a lot of knowledge. Could you
> help me improve my app with root.after?

OK, I'll try.

> And there is problem - when im closing app with X button after using
> app it shows two windows. One with messagebox i wrote, and second
> blank new tk window. I dont know where im doing mistake, or it is
> caused by root.update maybe? Maybe with using root.after problem will
> be no more.

Maybe, but I'll need to look at the code more closely.
There are a couple of things that could cause this
Having looked, I think you need to bind the window
manager close button to root.quit Take a look at
the wm_ methods in the Tkinter docs.


>
> def displayCountdown():
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> setTime -= 1
> if setTime > 0:
> root.after(1000,displayCountdown)
>

Where is 't' (used in the divmod) defined? Looking below I think
it should use setTime?

Otherwise it looks like it should work. All you need to do is insert
a call to displayCountdown() in your START button event handler.


> There are problems with my app but im so proud that i wrote myself

Its rare that anything is ever perfect but the buzz of getting
something to work more or less as you want it to is always good. :-)

> import sys, time, os
> import tkinter as tk
> from tkinter import *
>

You should probably only ose one of the tkinter imports.
And the first is the preferred method for production code.

> def change_1():
> B1['state'] = tk.DISABLED
> B2['state'] = tk.NORMAL  
>
> def change_2():
> B1['state'] = tk.NORMAL
> B2['state'] = tk.DISABLED
>
> def change_3():
> B1['state'] = tk.DISABLED
> B2['state'] = tk.DISABLED


Add the displayCountdown() definition here

>
> def startCount():
> setTime = setMinutes.get() * 60
> strTime = str(setTime)
> timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
> os.system(timeSet)
> change_1()
displayCountdown() # uses the after() method.

This removes the need for all of the code below.

> for t in range(setTime, -1, -1):
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> try:
> root.update()
> except TclError:
> messagebox.showinfo('Info', 'Closing app wont stop timer.')
> return
> time.sleep(1)
> return
>

The rest of your code is unchanged.
But note I haven't tested this! :-)

> def stopCount():
> passwd = "science"
> passwdGet = getPass.get()
> if passwd != passwdGet:

You could make this more secure.
You should probably do some reading about best [practice
for handling passwords. But for now it probably meets your needs.


> messagebox.showinfo('Wrong', 'It wasnt correct password')
> change_3()
> else:
> messagebox.showinfo('Good', 'Shutdown canceled')
> os.system("shutdown /a")
> change_2()
> return
>
> root = tk.Tk()
> setMinutes = IntVar()
> getPass = StringVar()
> timeString = StringVar()
> label_font = ('Verdana', 30)
> root.geometry('260x150+200+200')
> root.title('Timer v1.4')
> root.resizable(0, 0)
>
> L1 = tk.Label(root, text='How much time you have?')
> L1.grid(row=0, columnspan=3, sticky='WE')
>
> L2 = tk.Label(root, textvariable=timeString, font=label_font, bg='white',
>  fg='orange', relief='raised', bd=3)
> L2.grid(row=1, columnspan=3, sticky='WE', padx=5, pady=5)
>
> E1 = tk.Entry(root, textvariable=setMinutes, bg='lightgreen')
> E1.grid(row=2, column=1, padx=5, pady=5)
>
> B1 = tk.Button(root, text='S T A R T', fg='green', bg='black',
> command=startCount)
> B1.grid(row=2, rowspan=2, sticky='NS', column=0, padx=5, pady=5)
>
> E2 = tk.Entry(root, textvariable=getPass, bg='red')
> E2.grid(row=3, column=1, padx=5, pady=5)
>
> B2 = tk.Button(root, text='S T O P', fg='red', bg='black',
> command=stopCount,
> state=tk.DISABLED)
> B2.grid(row=2, rowspan=2, sticky='NS', column=2, padx=5, pady=5)
>
> root.mainloop()
>
>
>
> 2016-11-17 1:03 GMT+01:00 Alan Gauld via Tutor  >:
>
> On 16/11/16 18:48, Freedom Peacemaker wrote:
> > Hi, i need help. I am using Python 3.4 and I have wrote little
> app for
> > windows only ( windows 7 and higher). Its timer and my app
> working but not
> > good. Some people said that i should use after method instead of
> update()
>
> after() executes a function after a delay.
> In your case you could use it to trigger an
> immediate shutdown after the delay elapses.
> But I'm not sure that would be much better
> than doing what you are doing.
>
> The other use 

Re: [Tutor] please help me with after method

2016-11-16 Thread Alan Gauld via Tutor
On 16/11/16 18:48, Freedom Peacemaker wrote:
> Hi, i need help. I am using Python 3.4 and I have wrote little app for
> windows only ( windows 7 and higher). Its timer and my app working but not
> good. Some people said that i should use after method instead of update()

after() executes a function after a delay.
In your case you could use it to trigger an
immediate shutdown after the delay elapses.
But I'm not sure that would be much better
than doing what you are doing.

The other use of after is to avoid loops in
event handlers such as the one you have here.
This allows control to return to the GUI window.

See below...

> When you run app first enter minutes in entry then press start. If you
> first press start your pc will shutdown with no time to stop it

You can fix that by setting a default value for the time.
But you still need to write some code to cancel the shutdown
(by killing the process perhaps?)

> def startCount():
> setTime = setMinutes.get() * 60
> strTime = str(setTime)
> timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
> os.system(timeSet)

Up to here is fine but you don't want a long running loop
inside an event handler. Although, in this case, it probably
doesn't run for long, it just counts down very quickly.

Instead you want it to count down  every second or so.

So you want to call a function that displays the time
remaining then calls after() with a delay of 1 second.
The call to after should have the same function in it.
Like so:

def displayCountdown():
# display the time here
# decrement the time by 1 second
# if any time remains:
#call after(1000,displayCountdown) # 1000ms = 1s

Note that after only needs the function name, don't
include any parentheses.

> for t in range(setTime, -1, -1):
> lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
> timeString.set(lcd)
> try:
> root.update()
> except TclError:
> messagebox.showinfo('Info', 'Closing app wont stop timer.')
> return
> time.sleep(1)
> return


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


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


[Tutor] please help me with after method

2016-11-16 Thread Freedom Peacemaker
Hi, i need help. I am using Python 3.4 and I have wrote little app for
windows only ( windows 7 and higher). Its timer and my app working but not
good. Some people said that i should use after method instead of update()
and nobody told me how. Ive tried many times but i dont know how do it
correctly. Please help me improve my app.

When you run app first enter minutes in entry then press start. If you
first press start your pc will shutdown with no time to stop it

my code:

from tkinter import *
import tkinter as tk
import time, os

def startCount():
setTime = setMinutes.get() * 60
strTime = str(setTime)
timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"")
os.system(timeSet)
for t in range(setTime, -1, -1):
lcd = "{:02d}:{:02d}".format(*divmod(t, 60))
timeString.set(lcd)
try:
root.update()
except TclError:
messagebox.showinfo('Info', 'Closing app wont stop timer.')
return
time.sleep(1)
return

root = tk.Tk()
setMinutes = IntVar()
timeString = StringVar()
label_font = ('Verdana', 30)
root.geometry('210x120+200+200')
root.title('Timer v1.0')
root.resizable(0, 0)

L1 = tk.Label(root, text='How much time you have?')
L1.grid(row=0, columnspan=3, sticky='WE')

L2 = tk.Label(root, textvariable=timeString, font=label_font, bg='white',
 fg='orange', relief='raised', bd=3)
L2.grid(row=1, columnspan=3, sticky='WE', padx=5, pady=5)

E1 = tk.Entry(root, textvariable=setMinutes).grid(row=2, column=1, padx=5,
pady=5)

B1 = tk.Button(root, text='S T A R T', fg='green', bg='black',
command=startCount)
B1.grid(row=2, rowspan=2, sticky='NS', column=0, padx=5, pady=5)

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


Re: [Tutor] please help me modify this code so that I can utilize raw_input

2016-10-05 Thread Oscar Benjamin
On 4 October 2016 at 19:11, Alan Gauld via Tutor  wrote:
>> """Define a function sum() and a function multiply() that sums and
>> multiplies (respectively) all the numbers in a list of numbers. For
>> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
>> should return 24."""
>
> 
> I do wish teachers would not ask students to reinvent the wheel.

You may be misunderstanding the teacher's objectives here. Sometimes
Python is used to introduce the concept of programming more generally
rather than specifically to prepare someone for professional
programming using Python. I don't know about you but I came to Python
after a number of other programming languages. Now that I teach
programming I can see that it's important in a first programming
introduction to cover nuts and bolts type algorithmic thinking. sum()
is a good example of an algorithm that most people are already used to
performing on pen and paper making it a good candidate for learning to
use loops and functions.

> Python already has a perfectly good sum() function.

Writing your own sum function helps to understand what actually
happens when using the standard sum function. I do the same thing with
my students in C teaching them how to make their own e.g. strlen
function. I will tell them that strlen exists afterwards but I want
them to understand what the null byte is and writing your own (or just
looking at a) strlen implementation helps with that. Likewise simply
using a function e.g. strcat without understanding its implementation
can lead to segfaults so there can be a relevance in understanding the
implementation even if you don't intend to reimplement something in
your own code. The implications of the implementation of sum are also
non-trivial which is why the stdlib contains at least 3 different sum
functions.

It's great that Python comes with so many functions to do common
tasks. However from personal experience teaching Python as a first
language can lead to the disadvantage that many students become spoilt
programmers. They will learn to assume that there is a function for
exactly what they want and all they ever need to do is ask a precise
question in a search engine and read the first stackoverflow page.
That may be the correct approach for many problems but it isn't
always. A programmer should have the ability to implement basic
algorithms (e.g. sum) for themselves when necessary.

> And both problems become trivial if using functools.reduce()
> 

Different people think in different ways but I reckon most people -
and especially most beginners - would find a loop more straightforward
than reduce. I doubt that the OP is at a stage where using reduce
seems trivial.

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


Re: [Tutor] please help me modify this code so that I can utilize raw_input

2016-10-04 Thread Alan Gauld via Tutor
On 04/10/16 15:04, Richard Koeman wrote:
> I would like to modify this code so that instead of me calling the function
> with the list as shown [1,2,3,4], the user inputs the list with raw_input.
> 

You don't need to modify your code you just need ton write a function
that reads a list from the user. Notice that this can e done by either
repeatedly asking the user to input values until they are done or by
reading a string containing the values and converting the string to a
list of numbers.


> """Define a function sum() and a function multiply() that sums and
> multiplies (respectively) all the numbers in a list of numbers. For
> example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
> should return 24."""


I do wish teachers would not ask students to reinvent the wheel.
Python already has a perfectly good sum() function.
And both problems become trivial if using functools.reduce()


> 
> def sum(mylist = [], *args):
>   print mylist
>   sum_of_number = 0
>   for i in mylist:
> sum_of_number += i
>   print "The sum of the digits in your number is %s" %(sum_of_number)

> def multiply(mylist = [], *args):
>   product_of_number = 1
>   for i in mylist:
> product_of_number = product_of_number * i
>   print "The product of the digits in your number is %s"
> %(product_of_number)
> 
> sum([1,2,3,4])
> multiply([1,2,3,4])

Incidentally, notice that the assignment asks you to *return* the
results not print them. This is good practice, keep the printing
separate from the calculation. You can then print the result,
if you wish, with

print( sum([]) )

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


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


[Tutor] please help me modify this code so that I can utilize raw_input

2016-10-04 Thread Richard Koeman
I would like to modify this code so that instead of me calling the function
with the list as shown [1,2,3,4], the user inputs the list with raw_input.

Thanks in advance


"""Define a function sum() and a function multiply() that sums and
multiplies (respectively) all the numbers in a list of numbers. For
example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4])
should return 24."""

def sum(mylist = [], *args):
  print mylist
  sum_of_number = 0
  for i in mylist:
sum_of_number += i
  print "The sum of the digits in your number is %s" %(sum_of_number)
def multiply(mylist = [], *args):
  product_of_number = 1
  for i in mylist:
product_of_number = product_of_number * i
  print "The product of the digits in your number is %s"
%(product_of_number)

sum([1,2,3,4])
multiply([1,2,3,4])

-- 
This is a staff email account managed by Simcoe Muskoka Catholic District 
School Board.  This email and any files transmitted with it are 
confidential and intended solely for the use of the individual or entity to 
whom they are addressed. If you have received this email in error please 
notify the sender.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help to build an addon for Anki

2015-04-20 Thread Alan Gauld

On 20/04/15 09:54, Mahesh Chiramure wrote:


I liked the addon "Picture-flasher" written for anki very much
and I was wondering if the same thing could be done with mp3 and/or
flac files.


Probably, but I (and probably most of the list) have no idea what anki 
is or what the addon does. This is a list for learning Python and its 
standard library. You could try asking on the general Python 
mailinglist/newsgroup where you might find someone familiar with it.


If you do try that you sould try explaining what anki is,
and what the addon does. ie how it 'adds on'.

Better still is if you can find an anki forum, since they will 
understand anki, addons and probably be familiar with the PictureFlasher 
one you describe.



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


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


[Tutor] Please Help to build an addon for Anki

2015-04-20 Thread Mahesh Chiramure
Hi

I liked the addon "Picture-flasher" written for anki very much
and I was wondering if the same thing could be done with mp3 and/or
flac files. Means I am looking for an addon that chooses a random mp3
and/or flac file from a directory provided by me (to the addon as we
have to provide in "Picture-flasher") and plays it on successful
reviewing of a certain number of cards (as does the addon
"Picture-flasher"). As a music lover, I feel that this addon can
motivate a whole lot of music lovers out there to pay a visit to Anki
on their PC and review to listen to their favorite mp3 and/or flac
files as a reward.

I am not a programmer yet, please guide.

Hoping for a quick response.

Mahesh Chirmure
# -*- coding: utf-8 -*-
# Picture-Flasher (a plugin for Anki)
# Authors:
#   Emanuel Rylke, ema-...@web.de
#   D_Malik, malik6...@gmail.com
# Version 2
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html

"""
A simple plugin that flashes pictures on-screen to reinforce reviews.

Before using:
- Get pictures from someplace. I downloaded pictures off reddit using the 
script at https://github.com/dpbrown/RedditImageGrab
- Change all lines (in the plugin source) marked with "CHANGEME" according to 
your preferences.

For more details, see the post at For more details, see the post at 
http://lesswrong.com/r/discussion/lw/frc/two_anki_plugins_to_reinforce_reviewing/
"""

from anki.hooks import addHook
from aqt import mw
from random import random, choice
from aqt.qt import QSplashScreen, QPixmap, QTimer
from os import listdir

#-- begin configuration --#
pictureDirectory = "E://Family stuff//22 Feb//Personal//College//A J//" 
#CHANGEME to the directory where you're storing your pictures. NB: This MUST 
end with a trailing slash e.g. D://Family stuff//19 Jan//Imgs//Wallys//, 
D://Family stuff//22 Feb//Imgs//Windows 7//.

flashTime = 3000 #CHANGEME to change how long pictures stay on the screen. The 
number is time in milliseconds.

#flashPosition = [20, 1050] #CHANGEME if you want the picture to be shown at a 
specific location. The numbers are x- and y-coordinates.

#CHANGEME: The next lines are a python dictionary associating deck names 
with probabilities of pictures being shown.
#Eg, when using the deck "brainscience", you will get a picture after 30% 
of cards. When using a deck without a listed name, "other" is used.
#Change this according to your decks. Decks with shorter, easier cards need 
lower probabilities.
deckPicsProbabilities = {
"rocketsurgery":   0.3,
"brainscience" :   0.5,
"other":   0.1,
}
#--- end configuration ---#

pics = listdir(pictureDirectory)

def showPics():
if mw.col.decks.current()['name'] in deckPicsProbabilities:
picsProbability = deckPicsProbabilities[mw.col.decks.current()['name']]
else:
picsProbability = deckPicsProbabilities["other"]

if random() < picsProbability:
mw.splash = QSplashScreen(QPixmap(pictureDirectory + choice(pics)))
try:
mw.splash.move(flashPosition[0], flashPosition[1])
except NameError:
pass
mw.splash.show()
QTimer.singleShot(flashTime, mw.splash.close)

addHook("showQuestion", showPics)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-22 Thread spir

On 03/21/2014 10:39 PM, Cameron Simpson wrote:

On 21Mar2014 20:31, Mustafa Musameh  wrote:

Please help. I have been search the internet to understand how to write a 
simple program/script with python, and I did not do anything.
I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.
.
.
in other words, it contains several IDs each one has a sequence of 'acgt' 
letters
I need to write a script in python where the output will be, for example, like 
this

ID 1

a = 10%, c = 40%,  g=40%, t = 10%

ID 2

a = 15%, c = 35%,  g=35%, t = 15%
.
.
.
(i mean the first line is the ID and the second line is the frequency of each 
letter )
How I can tell python to print the first line as it is and count characters 
starting from the second line till the beginning of the next '>' and so on


You want a loop that reads lines in pairs. Example:

   while True:
 line1 = fp.readline()
 print line1,
 line2 = fp.readline()
 ... process the line and report ...

Then to process the line, iterate over the line. Because a line is
string, and a string is a sequence of characters, you can write:

   for c in line2:
 ... collect statistics about c ...
   ... print report ...

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.


I think it would be easier to do that in 2 loops:
* first read the file line by line, building a list of pairs (id, base-sequence)
  (and on the fly check the input is correct, if needed)
* then traverse the sequences of bases to get numbers & percentages, and write 
out

d

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


Re: [Tutor] please help

2014-03-22 Thread Cameron Simpson
On 22Mar2014 00:04, Mark Lawrence  wrote:
> On 21/03/2014 21:39, Cameron Simpson wrote:
> >On 21Mar2014 20:31, Mustafa Musameh  wrote:
> >
> >I would collect the statistics using a dictionary to keep count of
> >the characters. See the dict.setdefault method; it should be helpful.
> >
> 
> Delightfully old fashioned but I'd now prefer
> http://docs.python.org/3/library/collections.html#collections.Counter
> :)

Maybe, but using a dictionary is easy and Mustafa will learn more.

Cheers,
-- 
Cameron Simpson 

Do not underestimate your abilities.  That is your boss's job.
It is your job to find ways around your boss's roadblocks.
- Glen Appleby  http://www.armory.com/~glena/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Mark Lawrence

On 21/03/2014 21:39, Cameron Simpson wrote:

On 21Mar2014 20:31, Mustafa Musameh  wrote:

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.



Delightfully old fashioned but I'd now prefer 
http://docs.python.org/3/library/collections.html#collections.Counter :)


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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: [Tutor] please help

2014-03-21 Thread Steven D'Aprano
On Fri, Mar 21, 2014 at 08:31:07PM +1100, Mustafa Musameh wrote:

> Please help. I have been search the internet to understand how to 
> write a simple program/script with python, and I did not do anything. 
> I have a file that look like this
> >ID 1
> agtcgtacgt…
> >ID 2
> acccttcc
> .
> .
> .
> in other words, it contains several IDs each one has a sequence of 'acgt' 
> letters
> I need to write a script in python where the output will be, for example, 
> like this 
> > ID 1
> a = 10%, c = 40%,  g=40%, t = 10%
> >ID 2
> a = 15%, c = 35%,  g=35%, t = 15%
> .
> .
> .
> (i mean the first line is the ID and the second line is the frequency of each 
> letter )
> How I can tell python to print the first line as it is and count 
> characters starting from the second line till the beginning of the 
> next '>' and so on


This sounds like a homework exercise, and I have a policy of trying not 
to do homework for people. But I will show you the features you need.

Firstly, explain what you would do if you were solving this problem in 
your head. Write out the steps in English (or the language of your 
choice). Don't worry about writing code yet, you're writing instructions 
for a human being at this stage.

Those instructions might look like this:

Open a file (which file?).
Read two lines at a time.
The first line will look like ">ID 42". Print that line unchanged.
The second line will look line "gatacacagtatta...". Count how 
many "g", "a", "t", "c" letters there are, then print the
results as percentages.
Stop when there are no more lines to be read.

Now that you know what needs to be done, you can start using Python for 
it. Start off by opening a file for reading:

f = open("some file")

There are lots of ways to read the file one line at a time. Here's one 
way:

for line in f:
print(line)


But you want to read it *two* lines at a time. Here is one way:

for first_line in f:
second_line = next(f, '')
print(first_line)
print(second_line)


Here's another way:

first_line = None
while first_line != '':
first_line = f.readline()
second_line = f.readline()


Now that you have the lines, what do you do with them? Printing the 
first line is easy. How about the second?


second_line = "gatacattgacaaccggaataccgagta"

Now you need to do four things:

- count the total number of characters, ignoring the newline at the end
- count the number of g, a, t, c characters individually
- work out the percentages of the total
- print each character and its percentage


Here is one way to count the total number of characters:

count = 0
for c in second_line:
count += 1


Can you think of a better way? Do you think that maybe Python has a 
built-in command to calculate the length of a string?


Here is one way to count the number of 'g' characters:

count_of_g = 0
for c in second_line:
count_of_g += 1


(Does this look familiar?)

Can you think of another way to count characters? Hint: strings have a 
count method:

py> s = "fjejevffveejf"
py> s.count("j")
3


Now you need to calculate the percentages. Do you know how to calculate 
the percentage of a total? Hint: you'll need to divide two numbers and 
multiply by 100.

Finally, you need to print the results.


Putting all these parts together should give you a solution. Good luck! 
Write as much code as you can, and come back with any specific questions 
you may have.



-- 
Steven

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


Re: [Tutor] please help

2014-03-21 Thread Cameron Simpson
On 21Mar2014 20:31, Mustafa Musameh  wrote:
> Please help. I have been search the internet to understand how to write a 
> simple program/script with python, and I did not do anything.
> I have a file that look like this
> >ID 1
> agtcgtacgt…
> >ID 2
> acccttcc
> .
> .
> .
> in other words, it contains several IDs each one has a sequence of 'acgt' 
> letters
> I need to write a script in python where the output will be, for example, 
> like this 
> > ID 1
> a = 10%, c = 40%,  g=40%, t = 10%
> >ID 2
> a = 15%, c = 35%,  g=35%, t = 15%
> .
> .
> .
> (i mean the first line is the ID and the second line is the frequency of each 
> letter )
> How I can tell python to print the first line as it is and count characters 
> starting from the second line till the beginning of the next '>' and so on

You want a loop that reads lines in pairs. Example:

  while True:
line1 = fp.readline()
print line1,
line2 = fp.readline()
... process the line and report ...

Then to process the line, iterate over the line. Because a line is
string, and a string is a sequence of characters, you can write:

  for c in line2:
... collect statistics about c ...
  ... print report ...

I would collect the statistics using a dictionary to keep count of
the characters. See the dict.setdefault method; it should be helpful.

Cheers,
-- 
Cameron Simpson 

... in '59 I ran out of brakes *four times* -- and I don't mean they didn't
work very well, I mean I had none.  Like the main oil line had sheared.  You
know, so that oil, you know, when you put your foot on the floor, the oil
just went squirting out into the atmosphere.  Things like that.  You know,
I'd always believed that Colin was close to genius in his design ability
and everything -- if he could just get over this failing of his of making
things too bloody light.  I mean, Colin's idea of a Grand Prix car was
it should win the race and, as it crossed the finishing line, it should
collapse in a heap of bits.  If it didn't do that, it was built too strongly.
- Innes Ireland
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help

2014-03-21 Thread Alan Gauld

On 21/03/14 09:31, Mustafa Musameh wrote:

Please help. I have been search the internet to understand how to write a

> simple program/script with python, and I did not do anything.

There are ma y tutorials on how to write Python for every level
of programmer.

What is your level? If you can already program then the official 
tutorial on the python.org web site is a good start.


https://wiki.python.org/moin/BeginnersGuide/Programmers

and

http://docs.python.org/2/tutorial/
or
http://docs.python.org/3/tutorial/

Depending on wheher you are using Pyton v2 or v3 - there are
significant differences.

If you cannot already program then this project will require quite a bit 
of work to learn the basics  before you can start to solve your problem. 
For that you should look at the list of tutors for non 
programmers(including mine as cited below).


https://wiki.python.org/moin/BeginnersGuide/NonProgrammers


I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.


This looks like bioscience? If so there are standard
libraries available to help with processing that.
Once you understand how to write basic Python you
should probably download one of those libraries.

There is a page for bioscientists using Python here:

http://www.onlamp.com/pub/a/python/2002/10/17/biopython.html

If you try one of the tutorials and have specific questions
come back here and we can try to clarify things,

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

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


Re: [Tutor] please help

2014-03-21 Thread Mark Lawrence

On 21/03/2014 09:31, Mustafa Musameh wrote:

Please help. I have been search the internet to understand how to write a 
simple program/script with python, and I did not do anything.
I have a file that look like this

ID 1

agtcgtacgt…

ID 2

acccttcc
.
.
.
in other words, it contains several IDs each one has a sequence of 'acgt' 
letters
I need to write a script in python where the output will be, for example, like 
this

ID 1

a = 10%, c = 40%,  g=40%, t = 10%

ID 2

a = 15%, c = 35%,  g=35%, t = 15%
.
.
.
(i mean the first line is the ID and the second line is the frequency of each 
letter )
How I can tell python to print the first line as it is and count characters 
starting from the second line till the beginning of the next '>' and so on

Please help


Welcome :)

Start here http://docs.python.org/3/tutorial/index.html and then come 
back with specific questions about any problems that you may encounter.



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


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


[Tutor] please help

2014-03-21 Thread Mustafa Musameh
Please help. I have been search the internet to understand how to write a 
simple program/script with python, and I did not do anything.
I have a file that look like this
>ID 1
agtcgtacgt…
>ID 2
acccttcc
.
.
.
in other words, it contains several IDs each one has a sequence of 'acgt' 
letters
I need to write a script in python where the output will be, for example, like 
this 
> ID 1
a = 10%, c = 40%,  g=40%, t = 10%
>ID 2
a = 15%, c = 35%,  g=35%, t = 15%
.
.
.
(i mean the first line is the ID and the second line is the frequency of each 
letter )
How I can tell python to print the first line as it is and count characters 
starting from the second line till the beginning of the next '>' and so on

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


[Tutor] Please help with beautifulsoup and web scraping

2013-09-23 Thread Kevin Ndung'u
http://stackoverflow.com/q/18974172/2390312
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help replace Long place-names with short place-names in many files with Python

2013-09-01 Thread Joel Goldstick
On Sun, Sep 1, 2013 at 4:19 PM, mc UJI  wrote:
> Dear Pythonistas,
>
> I am totally new to Python. This means a know the basics. And by basics I
> mean the very, very basics.
>
> I have a problem with which I need help.
>
> in short, I need to:
>
> a) Open many files (in a dir) with an .html extension

Do you know how to do this?  Its not hard.  Google 'python reading all
files in a directory' to get started
> b)  Find Long name-places (Austria)
> c) Replace them by short name.places (AT)

In python strings are objects and they have the replace method  (look
here:  http://docs.python.org/2/library/string.html#string.replace)

If you figure out how to read each file into a string (see above), you
just run the string.replace method on it for each long-short country
pair.  Then write the file.

Try first to write this code.  If you apply yourself, it will take you
maybe an hour to get something working.
Then come back with your code and tell us what went wrong.


> d) In the context of the xml tags ( and
> )
>
> At length:
>
> I have many xml files containing a day of speeches at the European
> Parliament each file. Each file has some xml-label for the session metadata
> and then the speakers (MPs) interventions. These interventions consist of my
> metadata and text. I include here a sample of two speeches (Please pay
> attention to xml labels  and  country=".*?"/> ):
>
> 
>SAMPLE OF INTERVENTIONS
> 
> 
> Knapman, Roger
> 19440220
> Crediton
> NA
> male
> 
> 
> 
> 
> 
> 
> 
> UK Independence Party
> 
> 
> on behalf of the group
> 
> 
> Mr President, Mr Juncker's speech was made with
> all the passion that a civil servant is likely to raise.
> Mr Juncker, you say that the Stability and
> Growth Pact will be your top priority, but your past statements serve to
> illustrate only the inconsistencies. Whilst I acknowledge
> that you played a key role in negotiating the pact's original rules, you
> recently said that the credibility of the pact had been buried and that the
> pact was dead. Is that still your opinion?
> You also said that you have a window of
> opportunity to cut a quick deal on the EU budget, including the British
> rebate of some EUR 4 billion a year. Is that so, Mr
> Juncker? The rebate took five years to
> negotiate. If your comments are true and you can cut a
> deal by June, then Mr Blair must have agreed in principle to surrender the
> rebate. Is that the case? With whom in
> the British Government precisely are you negotiating? Will
> the British electorate know about this at the time of the British general
> election, probably in May?
> Finally, the UK Independence Party, and in
> particular my colleague Mr Farage, has drawn attention to the criminal
> activities of more than one Commissioner. More details
> will follow shortly and regularly. Are you to be tainted
> by association with them, or will you be expressing your concerns and the
> pressing need for change?
> 
> 
>
> 
> 
> Angelilli, Roberta
> 19650201
> Roma
> NA
> female
> 
> 
> 
> 
> 
> 
> 
> Alleanza nazionale
> 
> 
> on behalf of the group
> 
> 
> Mr President, the Luxembourg Presidency’s
> programme is packed with crucial issues for the future of Europe, including
> the priorities on the economic front: the Lisbon strategy, reform of the
> Stability Pact and approval of the financial perspective up to 2013.
> My first point is that it will soon be time for
> the mid-term review of the level of implementation of the Lisbon
> strategy. To give it a greater chance of success, the
> programme needs to make the individual Member States responsible for
> achieving the targets that were set. To that end, I
> consider the proposal to specify an individual at national level to be
> responsible for putting the strategy into practice to be a very useful
> idea.
> Secondly, with regard to the review of the
> Stability Pact, it has also been emphasised this morning that a reform is
> needed which can propose a more flexible interpretation of the Pact during
> times of recession, without bypassing the Maastricht criteria and without
> giving up the commitment to reduce the debt. I am also
> convinced that steps could be taken to exclude certain specific types of
> investment from the calculation of the deficit in order to give a new boost
> to Europe’s growth and competitiveness.
> Thirdly, I hope that we can really succeed in
> approving the financial perspective up to 2013 by June, so that the
> resources can be used to the full from the very beginning of the period in
> question. I especially hope that the proposals – the
> Council’s and the Commission’s proposals on those important topics – are
> adequately discussed in advance by Parliament which, let us recall, is the
> only European institution that directly represents the sovereignty of the
> people.
> Lastly, I hope that a European civil protection
> agenc

[Tutor] Please help replace Long place-names with short place-names in many files with Python

2013-09-01 Thread mc UJI
Dear Pythonistas,

I am totally new to Python. This means a know the basics. And by basics I
mean the very, very basics.

I have a problem with which I need help.

in short, I need to:

a) Open many files (in a dir) with an .html extension
b)  Find Long name-places (Austria)
c) Replace them by short name.places (AT)
d) In the context of the xml tags ( and
)

At length:

I have many xml files containing a day of speeches at the European
Parliament each file. Each file has some xml-label for the session metadata
and then the speakers (MPs) interventions. These interventions consist of
my metadata and text. I include here a sample of two speeches (Please pay
attention to xml labels  and  ):


   SAMPLE OF INTERVENTIONS


Knapman, Roger
19440220
Crediton
NA
male







UK Independence Party


on behalf of the group


Mr President, Mr Juncker's speech was made with
all the passion that a civil servant is likely to raise.
Mr Juncker, you say that the Stability and
Growth Pact will be your top priority, but your past statements serve to
illustrate only the inconsistencies. Whilst I acknowledge
that you played a key role in negotiating the pact's original rules, you
recently said that the credibility of the pact had been buried and that the
pact was dead. Is that still your opinion?
You also said that you have a window of
opportunity to cut a quick deal on the EU budget, including the British
rebate of some EUR 4 billion a year. Is that so, Mr
Juncker? The rebate took five years to
negotiate. If your comments are true and you can cut a
deal by June, then Mr Blair must have agreed in principle to surrender the
rebate. Is that the case? With whom in
the British Government precisely are you negotiating? Will the British electorate know about this at the time of the
British general election, probably in May?
Finally, the UK Independence Party, and in
particular my colleague Mr Farage, has drawn attention to the criminal
activities of more than one Commissioner. More details
will follow shortly and regularly. Are you to be tainted
by association with them, or will you be expressing your concerns and the
pressing need for change?





Angelilli, Roberta
19650201
Roma
NA
female







Alleanza nazionale


on behalf of the group


Mr President, the Luxembourg Presidency’s
programme is packed with crucial issues for the future of Europe, including
the priorities on the economic front: the Lisbon strategy, reform of the
Stability Pact and approval of the financial perspective up to 2013.
My first point is that it will soon be time for
the mid-term review of the level of implementation of the Lisbon
strategy. To give it a greater chance of success, the
programme needs to make the individual Member States responsible for
achieving the targets that were set. To that end, I
consider the proposal to specify an individual at national level to be
responsible for putting the strategy into practice to be a very useful
idea.
Secondly, with regard to the review of the
Stability Pact, it has also been emphasised this morning that a reform is
needed which can propose a more flexible interpretation of the Pact during
times of recession, without bypassing the Maastricht criteria and without
giving up the commitment to reduce the debt. I am also
convinced that steps could be taken to exclude certain specific types of
investment from the calculation of the deficit in order to give a new boost
to Europe’s growth and competitiveness.
Thirdly, I hope that we can really succeed in
approving the financial perspective up to 2013 by June, so that the
resources can be used to the full from the very beginning of the period in
question. I especially hope that the proposals – the
Council’s and the Commission’s proposals on those important topics – are
adequately discussed in advance by Parliament which, let us recall, is the
only European institution that directly represents the sovereignty of the
people.
Lastly, I hope that a European civil protection
agency will at last be set up during the Luxembourg Presidency so that
natural disasters can be dealt with in an appropriate manner, with
particular emphasis on prevention.



  END OF SAMPLE OF INTERVENTIONS
*


Now, as you see, label:

 and 

Have long place-names. For instance

 and 

But I would like short place-names (UK instead of United Kingdom, for
instance)

The long-names I have are all the members of the European Union.


LIST OF LONG PLACE-NAMES AND EQUIVALENT SHORT PLACE-NAMES

Austria = AT
Belgium = BE
Bulgaria = BG
Croatia = HR
Cyprus = CY
Czech Republic = CS
Denmark = DK
Estonia = EE
Finland = FI
France = FR
Germany = DE
Greece = GR
Hungary = HU
Ireland = IE
Italy = IT
Latv

[Tutor] please help with read_until, write script

2013-08-15 Thread cindy chao
Hi, all Python Experts,
I am a Python beginner.
I am trying to script the following steps.
I have problem to match the step after 'signature check?'
'[999.daisyse.07260019]:' the value of 0726009 is dynamic, every time it will 
be different, so I don't know how to do it. 
For sure I have problem to match 'directory and config file? (Yes/No) [Yes]:' 
and 'current configuration? (Yes/No) [Yes]:'
I use IDLE in pc to write and run the script.

Please help, thank you very much.

All the steps I want to script.

vyatta@Daisy-BGP1:~$ add sys image 
http://packages.vyatta.com/vyatta-dev/daisy-se/unstable/iso/livecd_2013-07-26-0018-7e824ac_i386.iso
Trying to fetch ISO file from 
http://packages.vyatta.com/vyatta-dev/daisy-se/unstable/iso/livecd_2013-07-26-0018-7e824ac_i386.iso
  % Total    % Received % Xferd  Average Speed   Time    Time Time  Current
 Dload  Upload   Total   Spent    Left  Speed
100  223M  100  223M    0 0  45.6M  0  0:00:04  0:00:04 --:--:-- 45.2M
ISO download succeeded.
Checking for digital signature file...
  % Total    % Received % Xferd  Average Speed   Time    Time Time  Current
 Dload  Upload   Total   Spent    Left  Speed
  0 0    0 0    0 0  0  0 --:--:-- --:--:-- --:--:-- 0
curl: (22) The requested URL returned error: 404
Unable to fetch digital signature file.
Do you want to continue without signature check? (yes/no) [yes] yes
Checking MD5 checksums of files on the ISO image...OK.
Done!
What would you like to name this image? [999.daisyse.07260019]:
OK.  This image will be named: 999.daisyse.07260019
Installing "999.daisyse.07260019" image.
Copying new release files...
Would you like to save the current configuration
directory and config file? (Yes/No) [Yes]: yes
Copying current configuration...
Would you like to save the SSH host keys from your
current configuration? (Yes/No) [Yes]: yes
Copying SSH keys...
Setting up grub configuration...
Done.

=
Here is my code.

session = telnetlib.Telnet("10.1.34.21", timeout=5)
...skip some write and read_until...
session.write('yes'+'\n')
h1=session.read_until('[999.daisyse.07260019]:')
print h1
session.write('\n')
    
#h20=session.read_until('(Yes/No) [Yes]:')- never match
#h20=session.read_until('[Yes]:') - never match
#h20=session.expect('(Yes/No)', '[Yes]:')- script just terminate
#h20=session.read_lazy('[Yes]:')-script just terminate
#h20=session.read_expect('.*\(Yes\/No\)')- script just terminate
h20=session.read_expect('.*\s\(Yes\/No\)')- script just terminate

print h20

===
#h20=session.read_until('(Yes/No) [Yes]:')- never match, just wait there, never 
finish.


OUtput from IDLE:

[Kvyatta@Daisy-BGP1:~$
 add sys image http://packages.vyatta.com/vyatta-dev/daisy-s 
e/unstable/iso/livecd_2013-07-26-0018-7e824ac_i386.iso 

Trying to fetch ISO file from 
http://packages.vyatta.com/vyatta-dev/daisy-se/unstable/iso/livecd_2013-07-26-0018-7e824ac_i386.iso

  % Total    % Received % Xferd  Average Speed   Time    Time Time  Current

 Dload  Upload   Total   Spent    Left  Speed


  0 0    0 0    0 0  0  0 --:--:-- --:--:-- --:--:-- 0
 34  223M   34 77.1M    0 0  87.1M  0  0:00:02 --:--:--  0:00:02 87.4M
 60  223M   60  135M    0 0  71.6M  0  0:00:03  0:00:01  0:00:02 71.8M
 69  223M   69  154M    0 0  53.4M  0  0:00:04  0:00:02  0:00:02 53.5M
 70  223M   70  156M    0 0  19.2M  0  0:00:11  0:00:08  0:00:03 19.2M
100  223M  100  223M    0 0  25.2M  0  0:00:08  0:00:08 --:--:-- 25.2M

ISO download succeeded.

Checking for digital signature file...

  % Total    % Received % Xferd  Average Speed   Time    Time Time  Current

 Dload  Upload   Total   Spent    Left  Speed


  0 0    0 0    0 0  0  0 --:--:-- --:--:-- --:--:-- 0
  0 0    0 0    0 0  0  0 --:--:-- --:--:-- --:--:-- 0

curl: (22) The requested URL returned error: 404

Unable to fetch digital signature file.

Do you want to continue without signature check? (yes/no) [yes]
 yes

Checking MD5 checksums of files on the ISO image...OK.

Done!

What would you like to name this image? [999.daisyse.07260019]:


==


#h20=session.expect('(Yes/No)', '[Yes]')- script just terminate

Do you want to continue without signature check? (yes/no) [yes]
 yes

Checking MD5 checksums of files on the ISO image...OK.

Done!

What would you like to name this image? [999.daisyse.07260019]:
>>> 

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


Re: [Tutor] Please Help

2013-03-22 Thread Martin A. Brown

Greetings,

 : I have the following data points.
 : data = [1,2,0,9,0,1,4]
 : I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 
 : (considering index starts at 0)
 : 
 : I have written the following code which is not running:
 : 
 : import math
 : 
 : number_list = [1,2,0,9,0,1,4]
 : 
 : number_list_1 = []
 : for k in range(math.floor(float(len(number_list)/2))):
 : if (k< math.floor(float(len(number_list)/2))):
 : number_list_1[k] = number_list[k*2 + 1]
 : 
 : print 'data: ', number_list_1 

My first thought when I see the above is that you appear to be
taking a circuitous route to the market!  You must really want to
get your exercise on your journey to fetch the list of [2, 9, 1].

My second observation is that the looping over a list using the
technique you showed here (and in your prior mail) is something
that looks more like C or Java.  Looping on an list (array, or any
sort of sequence) is a bit easier here in the lands of Python.
You can simply:

  for item in list_data:
  # -- do something with item

Since you are in the lands of Python (and welcome, by the way),
the Python docs are pretty good (and not overwhelming), and
include some excellent examples, so try reading about sequences
and how to manipulate them at this online doc:

  
http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

Anyway, I think you may benefit from seeing this solution a bit
more Pythonically, so I have offered two different solutions.

-Martin

data = number_list = [1,2,0,9,0,1,4]

# -- you call it 'number_list_1'; I will call it 'outlist'
#
outlist = []
for idx,val in enumerate(data):
print idx, val
if 0 == (idx % 2):  # -- skip even entries; do not append
continue
outlist.append(val)

print 'loop over enumerate() to get your data: ', outlist

# -- OR, given how simple your operation on the list is, consider
#learning about slicing; see the standard docs on sequences:
#
#
http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange
#

print 'slice out from your original data: ', data[1::2]

-- 
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread Asokan Pichai
On Fri, Mar 22, 2013 at 6:07 PM, Arijit Ukil  wrote:

> I have the following data points.
> data = [1,2,0,9,0,1,4]
> I like to store in an array and print the odd-indexed points, i.e. 2, 9,1
> (considering index starts at 0)
>
> *I have written the following code which is** not **running:*
>
> import math
>
> number_list = [1,2,0,9,0,1,4]
>
> number_list_1 = []
> for k in range(math.floor(float(len(number_list)/2))):
> if (k< math.floor(float(len(number_list)/2))):
> number_list_1[k] = number_list[k*2 + 1]
>
> print *'data: '*, number_list_1
>
> Please help
>
> Regards,
>


I would suggest that your roblems have more to do with insufficient
understanding of basic constructs, and
that you should work on them, "Learn Python the hard way" a book by Zed
Shaw is a good one.

Why do I say that? Among other things,

k< math.floor(float(len(number_list)/2))

is very poor in any language.

Asokan Pichai

The root of all superstition is that men observe when a thing hits, but not
when it misses. -- Francis Bacon
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-22 Thread Andreas Perstinger

Please use a meaningful subject.

On 22.03.2013 13:37, Arijit Ukil wrote:

I have the following data points.
data = [1,2,0,9,0,1,4]
I like to store in an array and print the odd-indexed points, i.e. 2, 9,1
(considering index starts at 0)


You can simply slice your list:

>>> data = [1, 2, 0, 9, 0, 1, 4]
>>> number_list = data[1::2]
>>> number_list
[2, 9, 1]

See also
http://docs.python.org/3/library/stdtypes.html#common-sequence-operations

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


[Tutor] Please Help

2013-03-22 Thread Arijit Ukil
I have the following data points.
data = [1,2,0,9,0,1,4]
I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 
(considering index starts at 0)

I have written the following code which is not running:

import math

number_list = [1,2,0,9,0,1,4]

number_list_1 = []
for k in range(math.floor(float(len(number_list)/2))):
if (k< math.floor(float(len(number_list)/2))):
number_list_1[k] = number_list[k*2 + 1]

print 'data: ', number_list_1 

Please help

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing

=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


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


Re: [Tutor] Please Help

2013-03-22 Thread Alan Gauld

On 22/03/13 07:24, Arijit Ukil wrote:


f = open ("digi_2.txt", "r+")
lines = f.readlines()
for line in lines:
 number_list = []
 for number in line.split(','):
 number_list.append(float(number))

s_data = []
for i in range(len(number_list)):


You hardly ever need to do this, its much simpler to just iterate over 
the list items directly:


for number in number_list:


 if number_list[i] > 5:
 s_data = number_list[i]


Note that you are overwriting your list with a single value.
You need to do what you did above and use append().


*The problem is: it is printing only the last value, not all the values.
In this case '10', **not**'9,8,6,10'.*


Because you overwrote the list each time. You need to remember to append 
data to lists not replace the list.




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

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


Re: [Tutor] Please Help

2013-03-22 Thread suhas bhairav
Hi Arijit,
I have modified your program a bit and it is working fine for me. Values 
greater than 5 are being printed. Here is the code:
f = open ("D:\\digi_2.txt", "r+") lines = f.readlines() number_list = [] for 
line in lines: print line  for number in line.split(','):   
   #number_list.append(float(number))  
number_list.append(int(number)) 
s_data = [] for i in number_list:   print i #if number_list[i] > 5: 
if(i>5):s_data.append(i)
for x in s_data:print 'Data val:', float(x) 


RegardsSuhas
To: tutor@python.org
From: arijit.u...@tcs.com
Date: Fri, 22 Mar 2013 12:54:01 +0530
Subject: [Tutor] Please Help

Hi,



I have another small problem. Pls help.



I have written the following code:



f = open ("digi_2.txt", "r+")

lines = f.readlines()

for line in lines:

number_list = []

for number in line.split(','):

number_list.append(float(number))



s_data = []

for i in range(len(number_list)):

if number_list[i] >
5:

s_data =
number_list[i]



print 'Data val:', s_data





The problem is: it is printing only
the last value, not all the values. In this case '10', not
'9,8,6,10'.







Regards,

Arijit Ukil

Tata Consultancy Services

Mailto: arijit.u...@tcs.com

Website: http://www.tcs.com



Experience certainty.IT Services


   Business Solutions


   Outsourcing

____








From:
Amit Saha 

To:
Arijit Ukil 

Cc:
tutor@python.org

Date:
03/21/2013 05:30 PM

Subject:
Re: [Tutor] Please Help








Hi Arijit,



On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil 
wrote:

>

> I am new to python. I like to calculate average of the numbers by
reading

> the file 'digi_2.txt'. I have written the following code:

>

> def average(s): return sum(s) * 1.0 / len(s)

>

> f = open ("digi_2.txt", "r+")

>

> list_of_lists1 = f.readlines()

>

>

> for index in range(len(list_of_lists1)):

>

>

> tt = list_of_lists1[index]

>

> print 'Current value :', tt

>

> avg =average (tt)

>

>

> This gives an error:

>

> def average(s): return sum(s) * 1.0 / len(s)

> TypeError: unsupported operand type(s) for +: 'int' and 'str'

>

> I also attach the file i am reading.

>

>

>

> Please help to rectify.



The main issue here is that when you are reading from a file, to

Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +

5 isn't (for example). Hence, besides the fact that your average

calculation is not right, you will have to 'convert' the string to an

integer/float to do any arithmetic operation on them. (If you know C,

this is similar to typecasting). So, coming back to your program, I

will first demonstrate you a few things and then you can write the

program yourself.



If you were to break down this program into simple steps, they would be:



1. Read the lines from a file (Assume a generic case, where you have

more than one line in the file, and you have to calculate the average

for each such row)

2. Create a list of floating point numbers for each of those lines

3. And call your average function on each of these lists



You could of course do 2 & 3 together, so you create the list and call

the average function.



So, here is step 1:



with open('digi.txt','r') as f:

lines = f.readlines()



Please refer to

http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

for an explanation of the advantage of using 'with'.



Now, you have *all* the lines of the file in 'lines'. Now, you want to

perform step 2 for each line in this file. Here you go:



for line in lines:

number_list = []

for number in line.split(','):

number_list.append(float(number))



 (To learn more about Python lists, see

http://effbot.org/zone/python-list.htm).
It is certainly possible to

use the index of an element to access elements from a list, but this

is more Pythonic way of doing it. To understand this better, in the

variable 'line', you will have a list of numbers on a single line. For

example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they

are separated by a ',' ? To get each element, we use the split( )

function, which returns a list of the individual numbers. (See:

http://docs.python.org/2/library/stdtypes.html#str.split).
And then,

we use the .append() method to create the list. Now, you have a

number_list which is a list of floating point numbers for each line.



Now, step 2 & 3 combined:



for line in lines:

  

[Tutor] Please Help

2013-03-22 Thread Arijit Ukil
Hi,

I have another small problem. Pls help.

I have written the following code:

f = open ("digi_2.txt", "r+")
lines = f.readlines()
for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))

s_data = []
for i in range(len(number_list)):
if number_list[i] > 5:
s_data = number_list[i]

print 'Data val:', s_data


The problem is: it is printing only the last value, not all the values. In 
this case '10', not '9,8,6,10'.



Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing




From:
Amit Saha 
To:
Arijit Ukil 
Cc:
tutor@python.org
Date:
03/21/2013 05:30 PM
Subject:
Re: [Tutor] Please Help



Hi Arijit,

On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil  wrote:
>
> I am new to python. I like to calculate average of the numbers by 
reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
> tt = list_of_lists1[index]
>
> print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I also attach the file i am reading.
>
>
>
> Please help to rectify.

The main issue here is that when you are reading from a file, to
Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +
5 isn't (for example). Hence, besides the fact that your average
calculation is not right, you will have to 'convert' the string to an
integer/float to do any arithmetic operation on them. (If you know C,
this is similar to typecasting). So, coming back to your program, I
will first demonstrate you a few things and then you can write the
program yourself.

If you were to break down this program into simple steps, they would be:

1. Read the lines from a file (Assume a generic case, where you have
more than one line in the file, and you have to calculate the average
for each such row)
2. Create a list of floating point numbers for each of those lines
3. And call your average function on each of these lists

You could of course do 2 & 3 together, so you create the list and call
the average function.

So, here is step 1:

with open('digi.txt','r') as f:
lines = f.readlines()

Please refer to
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
for an explanation of the advantage of using 'with'.

Now, you have *all* the lines of the file in 'lines'. Now, you want to
perform step 2 for each line in this file. Here you go:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))

 (To learn more about Python lists, see
http://effbot.org/zone/python-list.htm). It is certainly possible to
use the index of an element to access elements from a list, but this
is more Pythonic way of doing it. To understand this better, in the
variable 'line', you will have a list of numbers on a single line. For
example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they
are separated by a ',' ? To get each element, we use the split( )
function, which returns a list of the individual numbers. (See:
http://docs.python.org/2/library/stdtypes.html#str.split). And then,
we use the .append() method to create the list. Now, you have a
number_list which is a list of floating point numbers for each line.

Now, step 2 & 3 combined:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))
print average(number_list)

Where average( ) is defined as:

def average(num_list):
return sum(num_list)/len(num_list)



There may be a number of unknown things I may have talked about, but i
hope the links will help you learn more and write your program now.

Good Luck.
-Amit.


--
http://amitsaha.github.com/


=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


1,0,9,0,8,6,0,10___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help

2013-03-21 Thread Dave Angel

On 03/21/2013 08:09 AM, Arijit Ukil wrote:

Thanks for the help.



You're welcome.

You replied privately, instead of including the list, so I'm forwarding 
the response so everyone can see it.  You also top-posted, so the 
context is backwards.



After running your code, I am getting the following error:

Traceback (most recent call last):
   File "C:\Documents and Settings\207564\Desktop\Imp privacy analyzer\New
Folder\test\src\test.py", line 53, in ?
 nums.append(float(numstsrings))
TypeError: float() argument must be a string or a number




Check carefully, apparently the copy/paste on your machine inserts extra 
letters.


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


Re: [Tutor] Please Help

2013-03-21 Thread Amit Saha
Hi Arijit,

On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil  wrote:
>
> I am new to python. I like to calculate average of the numbers by reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
> tt = list_of_lists1[index]
>
> print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>
> I also attach the file i am reading.
>
>
>
> Please help to rectify.

The main issue here is that when you are reading from a file, to
Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' +
5 isn't (for example). Hence, besides the fact that your average
calculation is not right, you will have to 'convert' the string to an
integer/float to do any arithmetic operation on them. (If you know C,
this is similar to typecasting). So, coming back to your program, I
will first demonstrate you a few things and then you can write the
program yourself.

If you were to break down this program into simple steps, they would be:

1. Read the lines from a file (Assume a generic case, where you have
more than one line in the file, and you have to calculate the average
for each such row)
2. Create a list of floating point numbers for each of those lines
3. And call your average function on each of these lists

You could of course do 2 & 3 together, so you create the list and call
the average function.

So, here is step 1:

with open('digi.txt','r') as f:
lines = f.readlines()

Please refer to
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
for an explanation of the advantage of using 'with'.

Now, you have *all* the lines of the file in 'lines'. Now, you want to
perform step 2 for each line in this file. Here you go:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))

 (To learn more about Python lists, see
http://effbot.org/zone/python-list.htm). It is certainly possible to
use the index of an element to access elements from a list, but this
is more Pythonic way of doing it. To understand this better, in the
variable 'line', you will have a list of numbers on a single line. For
example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they
are separated by a ',' ? To get each element, we use the split( )
function, which returns a list of the individual numbers. (See:
http://docs.python.org/2/library/stdtypes.html#str.split). And then,
we use the .append() method to create the list. Now, you have a
number_list which is a list of floating point numbers for each line.

Now, step 2 & 3 combined:

for line in lines:
number_list = []
for number in line.split(','):
number_list.append(float(number))
print average(number_list)

Where average( ) is defined as:

def average(num_list):
return sum(num_list)/len(num_list)



There may be a number of unknown things I may have talked about, but i
hope the links will help you learn more and write your program now.

Good Luck.
-Amit.


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


Re: [Tutor] Please Help

2013-03-21 Thread Dave Angel

On 03/21/2013 06:42 AM, Arijit Ukil wrote:

I am new to python.


Since you're new to Python, I won't try to supply you an answer using 
list comprehensions, since you've probably not learned them yet.




I like to calculate average of the numbers by reading
the file 'digi_2.txt'. I have written the following code:

def average(s): return sum(s) * 1.0 / len(s)


This function presumably expects to be passed a list (or iterable) of 
ints or a list of floats as its argument.  It'll fail if given a list of 
strings.  A comment or docstring to that effect would be useful to 
remind yourself.




f = open ("digi_2.txt", "r+")


Why is there a "plus sign" in the mode string?  Not necessary, since 
you're just going to read the file straight through.




list_of_lists1 = f.readlines()



Not a good name, since that's not what readlines() returns.  It'll 
return a list of strings, each string representing one line of the file.




for index in range(len(list_of_lists1)):


Since your file is only one line long, this loop doesn't do much.




 tt = list_of_lists1[index]

 print 'Current value :', tt



At this point, It is the string read from the last line of the file. 
The other lines are not represented in any way.



avg =average (tt)


This gives an error:

def average(s): return sum(s) * 1.0 / len(s)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I also attach the file i am reading.

You shouldn't assume everyone can read the "attached" data.  Since it's 
short, you should just include it in your message.  It's MUCH shorter 
than all the irrelevant data you included at the end of your message.


For those others who may be reading this portion of the hijacked thread, 
here's the one line in digi_2.txt


1350696461, 448.0, 538660.0, 1350696466, 448.0


Now to try to solve the problem.  First, you don't specify what the 
numbers in the file will look like.  Looking at your code, I naturally 
assumed you had one value per line.  Instead I see a single line with 
multiple numbers separated by commas.


I'll assume that the data will always be in a single line, or that if 
there are multiple lines, every line but the last will end with a comma, 
and that the last one will NOT have a trailing comma.  If I don't assume 
something, the problem can't be solved.



Since we don't care about newlines, we can read the whole file into one 
string, with the read() function.



f = open ("digi_2.txt", "r")
filedata = f.read()
f.close()

Now we have to separate the data by the commas.

numstsrings = filedata.split(",")

And now we have to convert each of these "numstring" values from a 
string into a float.


nums = []
for numstring in numstrings:
nums.append(float(numstring))

Now we can call the average function, since we have a list of floats.

avg = average(nums)

Completely untested, so there may be typos in it.





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


Re: [Tutor] Please Help

2013-03-21 Thread Sven
Please trim unrelated text from emails.

On 21 March 2013 10:42, Arijit Ukil  wrote:

> I am new to python. I like to calculate average of the numbers by reading
> the file 'digi_2.txt'. I have written the following code:
>
> def average(s): return sum(s) * 1.0 / len(s)
>
> f = open ("digi_2.txt", "r+")
>
> list_of_lists1 = f.readlines()
>
>
> for index in range(len(list_of_lists1)):
>
>
> tt = list_of_lists1[index]
>
> print 'Current value :', tt
>
> avg =average (tt)
>
>
> This gives an error:
>
> def average(s): return sum(s) * 1.0 / len(s)
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>

tt is a string as it's read from the file. int(tt) would fix the problem.
But in addition you're also not actually calculating the average.


def average(s):
return sum(s) / len(s)


# convert the list of strings to a list of floats
tt = [float(x) for x in list_of_lists1]

avg = average(tt)

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


[Tutor] Please Help

2013-03-21 Thread Arijit Ukil
I am new to python. I like to calculate average of the numbers by reading 
the file 'digi_2.txt'. I have written the following code:

def average(s): return sum(s) * 1.0 / len(s)

f = open ("digi_2.txt", "r+")

list_of_lists1 = f.readlines()


for index in range(len(list_of_lists1)):
 

tt = list_of_lists1[index]

print 'Current value :', tt

avg =average (tt)


This gives an error:

def average(s): return sum(s) * 1.0 / len(s)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I also attach the file i am reading.



Please help to rectify.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.u...@tcs.com
Website: http://www.tcs.com

Experience certainty.   IT Services
Business Solutions
Outsourcing




From:
Alan Gauld 
To:
tutor@python.org
Date:
03/21/2013 06:00 AM
Subject:
Re: [Tutor] Help
Sent by:
"Tutor" 



On 20/03/13 19:57, travis jeanfrancois wrote:
> I create a function that allows the user to a create sentence by
>   inputing  a string and to end the sentence with a  period meaning
> inputing "." .The problem is while keeps overwriting the previuos input

'While' does not do any such thing. Your code is doing that all by 
itself. What while does is repeat your code until a condition
becomes false or you explicitly break out of the loop.

> Here is my code:
>
> def B1():

Try to give your functions names that describe what they do.
B1() is meaningless, readSentence() would be better.


>   period = "."
>   # The variable period is assigned

Its normal programming practice to put the comment above
the code not after it. Also comments should indicate why you
are doing something not what you are doing - we can see that
from the code.

>   first = input("Enter the first word in your sentence ")
>   next1 = input("Enter the next word in you sentence or enter period:")

>   # I need store the value so when while overwrites next1 with the next
> input the previous input is stored and will print output when I call it
> later along with last one
>   # I believe the solution is some how implenting this expression x = x+
> variable

You could be right. Addition works for strings as well as numbers.
Although there are other (better) options but you may not have covered 
them in your class yet.

>   while  next1 != (period) :

You don;t need the parentheses around period.
Also nextWord might be a better name than next1.
Saving 3 characters of typing is not usually worthwhile.

>  next1  = input("Enter the next word in you sentence or enter 
period:")

Right, here you are overwriting next1. It's not the while's
fault - it is just repeating your code. It is you who are
overwriting the variable.

Notice that you are not using the first that you captured?
Maybe you should add next1 to first at some point? Then you
can safely overwrite next1 as much as you like?

>  if next1 == (period):

Again you don;t need the parentheses around period

>  next1 = next1 + period

Here, you add the period to next1 which the 'if' has
already established is now a period.

>  print ("Your sentence is:",first,next1,period)

And now you print out the first word plus next1 (= 2 periods) plus a 
period = 3 periods in total... preceded by the phrase "Your sentence 
is:" This tells us that the sample output you posted is not from this 
program... Always match the program and the output when debugging or you 
will be led seriously astray!

> PS : The" #"  is I just type so I can understand what each line does

The # is a comment marker. Comments are a very powerful tool that 
programmers use to explain to themselves and other programmers
why they have done what they have.

When trying to debug faults like this it is often worthwhile
grabbing a pen and drawing a chart of your variables and
their values after each time round the loop.
In this case it would have looked like

iterationperiod  first   next1
0.   I   am
1.   I   a
2.   I   novice
3.   I   ..

If you aren't sure of the values insert a print statement
and get the program to tell you, but working it out in
your head is more likely to show you the error.


HTH,

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

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


=-=-=
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, d

Re: [Tutor] Please help

2013-01-01 Thread Asokan Pichai
I saw the code;

I see too many formatting errors:
Line No 24 starts a function definition and the
next few lines are indented by two spaces, but
Line 29 is a print statement that is in line with
the def; IOW it completes the function. It is
very likely wrong.

You are defining functions within functions;
again it is very likely to be wrong.

My advice, look at PEP 8 and also some
sample python code in the tutorial to
understand how to format code. Remember:
Leading whitespace is syntactically significant

HTH


Asokan Pichai

Religion offers hope against all the strife and misery of
the world caused by religions.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help

2013-01-01 Thread Jack Little
Maybe tomorrow I can just email you the code

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


Re: [Tutor] Please help

2013-01-01 Thread Steven D'Aprano

On 02/01/13 13:02, Jack Little wrote:

I do not understand my error (it says something about an out-of-function return 
on line 179)


You cannot use "return" unless it is inside a function.

# This is okay.
def test():
print "test"
return "testing complete"  # indented, therefore inside the function


# this is not okay
def test():
print "test"
return "testing complete"  # not indented, therefore not inside the function



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


Re: [Tutor] Please help

2013-01-01 Thread Ryan Macy

Jack Little wrote:


I do not understand my error (it says something about an
out-of-function return on line 179)
my code is at the link
http://www.mediafire.com/download.php?4ga0weu4ifc6s1u
___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



I'd like to help, but I'm not going to download anything from that site.

Can you instead post it on gist.github.com or bpaste.com?

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


[Tutor] Please help

2013-01-01 Thread Jack Little
I do not understand my error (it says something about an out-of-function return 
on line 179)
 
my code is at the link
http://www.mediafire.com/download.php?4ga0weu4ifc6s1u___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Alan Gauld

On 17/11/11 23:12, ADRIAN KELLY wrote:

i know i should use input but when i changed to raw_input

In Python v3 use input()

In python v2 input() is dangerous, use raw_input() instead.


> ... it wouldn't recognise the word print on the next line.

Show us the exact code and error. You may be missing
a parenthesis, or maybe you are just expecting the wrong
behaviour... It won't execute the print until after it
has read your input.


everything to get this working..
i am 6 hrs at one program


Heh, I've got one I've been working on for over 10 years,
6 hours is nothing! :-)


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

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


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread ADRIAN KELLY

i know i should use input but when i changed to raw_input it wouldn't recognise 
the word print on the next line. honestly i have tried everything to get this 
working..i am 6 hrs at one program


 

  

Adrian Kelly 
1 Bramble Close

Baylough

Athlone

County Westmeath

0879495663


From: waynejwer...@gmail.com
Date: Thu, 17 Nov 2011 16:53:59 -0600
Subject: Re: [Tutor] please help - stuck for hours
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY  wrote:








thanks very much, great response really really appreciated it and now i 
understand. i hate to ask again but can you see why it won't print the  'enter 
and amount over 50' in the right place??


Computers are unfailingly stupid machines. They will do whatever wrong thing 
you tell them to do every single time. 

 def main():amount=0while amount<50:amount = input('how 
much do you want to change:')

print 'enter an amount over €50: 'else:
total=exchange(amount)print 'Your exchange comes to: ',total


Sometimes it helps writing out the logic in steps before you translate it to 
code. In this case my guess is that these are the steps you want:
  1. Get a value from the user (you're still using input - stop that, it's 
dangerous! input is   only a good function in 3.x where it replaces raw_input)

   2. If the value is less than 50, tell the user to enter an amount > 50 and 
repeat step 1
  3. Otherwise, exchange the amount and display that.
Right now, these are the steps that you're doing:


  1. Get a value from the user
  2. Display the error message
  3. If the value is < 50, go to 1
  4. exchange the amount


  5. display the amount.
HTH,Wayne ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Wayne Werner
On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote:

>
> thanks very much, great response really really appreciated it and now i
> understand. i hate to ask again but can you see why it won't print the
>  'enter and amount over 50' in the right place??
>

Computers are unfailingly stupid machines. They will do whatever wrong
thing you tell them to do every single time.


>  
> def main():
> amount=0
> while amount<50:
> amount = input('how much do you want to change:')
> print 'enter an amount over €50: '
> else:
> total=exchange(amount)
> print 'Your exchange comes to: ',total
>

Sometimes it helps writing out the logic in steps before you translate it
to code. In this case my guess is that these are the steps you want:

  1. Get a value from the user (you're still using input - stop that, it's
dangerous! input is   only a good function in 3.x where it replaces
raw_input)

  2. If the value is less than 50, tell the user to enter an amount > 50
and repeat step 1

  3. Otherwise, exchange the amount and display that.

Right now, these are the steps that you're doing:

  1. Get a value from the user

  2. Display the error message

  3. If the value is < 50, go to 1

  4. exchange the amount

  5. display the amount.

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


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread ADRIAN KELLY


thanks very much, great response really really appreciated it and now i 
understand. i hate to ask again but can you see why it won't print the  'enter 
and amount over 50' in the right place?? 

  # -*- coding: cp1252 -*-def exchange(cash_in):euro=1dollar=1.35
base=50if cash_in>base:totalreturn=cash_in*dollarelse:
totalreturn=0return totalreturn

def main():amount=0while amount<50:amount = input('how much do 
you want to change:')print 'enter an amount over €50: 'else:
total=exchange(amount)print 'Your exchange comes to: ',total  main()

Adrian Kelly 
1 Bramble Close

Baylough

Athlone

County Westmeath

0879495663


From: waynejwer...@gmail.com
Date: Thu, 17 Nov 2011 15:35:29 -0600
Subject: Re: [Tutor] please help - stuck for hours
To: kellyadr...@hotmail.com
CC: tutor@python.org

On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY  wrote:







i have tried everything, i am trying to build in a loop to my 2 functions which 
worked fine up until my latest sorti.
please have a look if you can..



def exchange(cash_in):euro=1dollar=1.35

base=50if cash_in>base:totalreturn=cash_in*dollar

else:totalreturn=0return totalreturn



def main():

amount=""while amount<50:print 'Sorry, cannot convert an amount 
under €50 '

amount = input('how much do you want to change:')else:

total=exchange(amount)print 'Your exchange comes to: ',total

  main()


 
Traceback (most recent call last):

  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in 
main()  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 19, in main

total=exchange(amount)  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollar

TypeError: can't multiply sequence by non-int of type 'float'
Thank you for posting the full traceback - this last line tells you the exact 
problem - you're trying to multiply a sequence by a float (in this case your 
sequence is a string). The line right above that tells you the what you tried 
to do: multiply `cash_in` by `dollar`.


Take a look at your code and what do you see? Well, you set `dollar = 1.35`, 
and you don't change the value elsewhere so that's certainly a float. What 
about cash_in? Well if you work your way backwards through the traceback you 
see that it was called with the parameter "amount".


Where is amount set? Ah, on that line:
amount = input()
This line is extremely problematic. First, I see by your print statement that 
you're using  Python 2.x, so input is actually executing arbitrary code. What 
you *want* is raw_input which returns a string and is much MUCH safer.


I don't know what your input value was, but I suspect that you did something 
like '30' (with the quotes), because otherwise it would evaluate to an integer. 
It's also possible that you used `amount`, which would evaluate to "" since you 
already declared it. None of these things are good.


Change your initial assignment to :
amount = 0
and the input line to:
amount = float(raw_input("How much would you like to exchange? "))


This will first get a string from the user and then convert it to a float - 
which I suspect you'll want, since you're dealing with monetary 
values.HTH,Wayne  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread delegbede
Where do you intend the variable cash_in to come from?

The system doesn't know what cash_in is beyond that you mentioned it and that 
makes it impossible to multiply it with dollar which is a float type. 

If cash_in is supposed to be an input from the user, you probably should make 
it an int type right away before doing the multiplication. 

Hope this helps. 

Cheers. 
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: ADRIAN KELLY 
Sender: tutor-bounces+delegbede=dudupay@python.org
Date: Thu, 17 Nov 2011 21:19:45 
To: 
Subject: [Tutor] please help - stuck for hours

___
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


Re: [Tutor] please help - stuck for hours

2011-11-17 Thread Wayne Werner
On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote:

>  i have tried everything, i am trying to build in a loop to my 2 functions
> which worked fine up until my latest sorti.
>
> please have a look if you can..
>
> def exchange(cash_in):
> euro=1
> dollar=1.35
> base=50
> if cash_in>base:
> totalreturn=cash_in*dollar
> else:
> totalreturn=0
> return totalreturn
>
>
> def main():
> amount=""
> while amount<50:
> print 'Sorry, cannot convert an amount under €50 '
> amount = input('how much do you want to change:')
> else:
> total=exchange(amount)
> print 'Your exchange comes to: ',total
>
>
> main()
>
>
>
> Traceback (most recent call last):
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27,
> in 
> main()
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19,
> in main
> total=exchange(amount)
>   File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in
> exchange
> totalreturn=cash_in*dollar
> TypeError: can't multiply sequence by non-int of type 'float'
>

Thank you for posting the full traceback - this last line tells you the
exact problem - you're trying to multiply a sequence by a float (in this
case your sequence is a string). The line right above that tells you the
what you tried to do: multiply `cash_in` by `dollar`.

Take a look at your code and what do you see? Well, you set `dollar =
1.35`, and you don't change the value elsewhere so that's certainly a
float. What about cash_in? Well if you work your way backwards through the
traceback you see that it was called with the parameter "amount".

Where is amount set? Ah, on that line:

amount = input()

This line is extremely problematic. First, I see by your print statement
that you're using  Python 2.x, so input is actually executing arbitrary
code. What you *want* is raw_input which returns a string and is much MUCH
safer.

I don't know what your input value was, but I suspect that you did
something like '30' (with the quotes), because otherwise it would evaluate
to an integer. It's also possible that you used `amount`, which would
evaluate to "" since you already declared it. None of these things are good.

Change your initial assignment to :

amount = 0

and the input line to:

amount = float(raw_input("How much would you like to exchange? "))

This will first get a string from the user and then convert it to a float -
which I suspect you'll want, since you're dealing with monetary values.
HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] please help - stuck for hours

2011-11-17 Thread ADRIAN KELLY

i have tried everything, i am trying to build in a loop to my 2 functions which 
worked fine up until my latest sorti.
please have a look if you can..

def exchange(cash_in):euro=1dollar=1.35base=50if cash_in>base:  
  totalreturn=cash_in*dollarelse:totalreturn=0return 
totalreturn

def main():amount=""while amount<50:print 'Sorry, cannot 
convert an amount under €50 'amount = input('how much do you want to 
change:')else:total=exchange(amount)print 'Your exchange 
comes to: ',total  main()
 
Traceback (most recent call last):  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 27, in main()  File "F:\VTOS 
ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main
total=exchange(amount)  File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign 
exchange\f_ex3.py", line 7, in exchangetotalreturn=cash_in*dollarTypeError: 
can't multiply sequence by non-int of type 'float'>>> 
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help understanding unittest fixtures

2011-08-22 Thread Peter Otten
Steven D'Aprano wrote:

> D. Guandalino wrote:

>> In this case is there a
>> way to force just one setUp() call?
> 
> 
> I don't know if this is the best way, but the first way that comes to
> mind is this:
> 
> 
> class C(TestCase):
>  initialised = False
>  def setUp(self):
>  if self.initialised:
>  return
>  # Make sure you save the flag on the class, not the instance!
>  self.__class__.initialised = True
>  ...

Python 2.7 and 3.2 support setUpClass()/tearDownClass() classmethods, see

http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass

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


Re: [Tutor] Please help understanding unittest fixtures

2011-08-21 Thread Steven D'Aprano

D. Guandalino wrote:

Suppose I have this TestCase class.

class C(TestCase):
   def setUp():
  # very time consuming and resources intensive stuffs.
  pass

   def test_A(self):
   pass
   def test_B(self):
   pass
   def test_C(self):
   pass

The unittest docs says:


Each instance of the TestCase will only be used to run a single test
method, so a new fixture is created for each test.



Does this mean that the setUp() method, which is called to prepare the test
fixture, get called for test_A, test_B and test_C? 


That's easy enough to find out:

def setUp(self):
print("calling setUp")
...


See how many times "calling setUp" is printed.



In this case is there a
way to force just one setUp() call?



I don't know if this is the best way, but the first way that comes to 
mind is this:



class C(TestCase):
initialised = False
def setUp(self):
if self.initialised:
return
# Make sure you save the flag on the class, not the instance!
self.__class__.initialised = True
...


--
Steven

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


[Tutor] Please help understanding unittest fixtures

2011-08-21 Thread D. Guandalino
Suppose I have this TestCase class.

class C(TestCase):
   def setUp():
  # very time consuming and resources intensive stuffs.
  pass

   def test_A(self):
   pass
   def test_B(self):
   pass
   def test_C(self):
   pass

The unittest docs says:

> Each instance of the TestCase will only be used to run a single test
> method, so a new fixture is created for each test.


Does this mean that the setUp() method, which is called to prepare the test
fixture, get called for test_A, test_B and test_C? In this case is there a
way to force just one setUp() call?

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


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Prasad, Ramit
Start solving the problem by viewing the text around what is being returned. 
Look at the +- 10-100 characters from what is being returned.

Where exactly on the page is the return coming from? Is this centered near 
where you expected it? If not, what could be causing that? If it is actually 
close (and not just an error that is returning something that looks close but 
is actually not related) to what you want then why are the boundaries for the 
slice not what you expect? Play around with the boundaries and see if you can 
get it closer. Goldstein's second email has narrowed down some of your 
problems, if you cannot find it.

Since you are doing text matches, be careful of case. What if WAter is typed 
instead of Water or water (as Andre noted) is typed?


Ramit



Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

From: tutor-bounces+ramit.prasad=jpmchase@python.org 
[mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of I. 
Dooba
Sent: Tuesday, May 17, 2011 11:54 AM
To: tutor@python.org
Subject: Re: [Tutor] Please help, the program is not behaving as I want

Thanks, Joel Goldstick

There is no error message.
But the program is returning incomplete or too many characters.  For example, 
instead of "Halal" it will return "l Hala"
or "nol" depending on the length of the word the user inputs.

Since I can't predict the words the user will search for, I'm finding it 
difficult to tackle the problem.
___
I. Dooba
Hybrid Intelligence & Digital Infrastructure Research Group
Universiti Teknologi PETRONAS
+6014 644 5086
ibraheem_g01...@utp.edu.my<mailto:ibraheem_g01...@utp.edu.my>



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 12:54 PM, I. Dooba  wrote:

> Thanks, Joel Goldstick
>
> There is no error message.
> But the program is returning incomplete or too many characters.  For
> example, instead of "Halal" it will return "l Hala"
> or "nol" depending on the length of the word the user inputs.
>
> Since I can't predict the words the user will search for, I'm finding it
> difficult to tackle the problem.
> ___
> I. Dooba
> Hybrid Intelligence & Digital Infrastructure Research Group
> Universiti Teknologi PETRONAS
> +6014 644 5086
> ibraheem_g01...@utp.edu.my
>
>
> I haven't read the book you are using, so I don't know what lessons they
are trying to teach in this example.  However, you should be aware that if
you read the input into a variable first, then do the .find() method
separately on the next line, you can later find out how long the word your
user typed (google python length of string if you don't know how).  Use this
length value to add to the start of your index so that you can start your
result at the beginning of Halal or Haram.  Then at least, if the word is in
your list you will get the answer you expect.

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


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


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread I. Dooba
Thanks, Joel Goldstick

There is no error message.
But the program is returning incomplete or too many characters.  For
example, instead of "Halal" it will return "l Hala"
or "nol" depending on the length of the word the user inputs.

Since I can't predict the words the user will search for, I'm finding it
difficult to tackle the problem.
___
I. Dooba
Hybrid Intelligence & Digital Infrastructure Research Group
Universiti Teknologi PETRONAS
+6014 644 5086
ibraheem_g01...@utp.edu.my
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 11:20 AM, I. Dooba  wrote:

> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
>
> However, I've the following problem.
>
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
>

You don't have a simple table in this webpage.  You should use 'View Source"
from your browser to actually see what your program is reading.  What you do
have quite far down are words like this between  tags:

 
 
Water Halal
Ethanol Halal
Blood Haram
Alcohol Haram
Benzoic Acid Halal



>
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
>
> What am I doing wrong?
>
> import urllib.request
>
> this gets access to  the webpage

> page = urllib.request.urlopen("
> http://halalingredients.theparleyonline.com/";)
>

this reads the whole page into your text variable

> text = page.read().decode("utf8")
>
>
this lets you type in a word, and uses that word to see if it can find it in
the text.  If it does, it returns the index where it finds the start of the
word

> halal_haram_status = text.find(input("Enter the ingredient:  "))
>

if it can't find a match it will return -1

This is strange.  I believe you want to add the length of the word you input
plus 1 (for the space) to the index you found above.

> begin_final_status = halal_haram_status + 3
>

This is ok since halal and haram are both 5 characters long

> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
>
>
Be careful to type the word exactly as printed.  If you the a word that is
not in your list, you might get what looks like nonsense since it will just
look to the 5 characters after the word you give it to find

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
> Since I'm on my lunch break I thought I'd dig into this


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


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Andre Engels
I am not able to check your code (I get an error message about the
usage of urllib, but that might be a difference in Python
installations); however, my first guess is that you neglected to take
case into account: The page contains the text "Water", not "water", so
if you input "water", halal_haram_status will be -1.

As another remark, find() will give the value of the _beginning_ of
the match, thus when all goes right, what is returned will contain
part of the text sought rather than "Halal" or "Haram" - you will get
"er Ha" for water, "anol " for ethanol and "k cho" for pork chops
(also, ethanol is the same as alcohol, so I guess it should be haram).

On Tue, May 17, 2011 at 5:20 PM, I. Dooba  wrote:
> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
> However, I've the following problem.
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
> What am I doing wrong?
> import urllib.request
> page =
> urllib.request.urlopen("http://halalingredients.theparleyonline.com/";)
> text = page.read().decode("utf8")
>
> halal_haram_status = text.find(input("Enter the ingredient:  "))
> begin_final_status = halal_haram_status + 3
> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>



-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread Joel Goldstick
On Tue, May 17, 2011 at 11:20 AM, I. Dooba  wrote:

> I'm new to programming and have decided to start with Python following the
> advice of experts including Eric S. Raymond.
> So far I've learnt quite a lot from this list.
>
> However, I've the following problem.
>
> The program was designed (as part of my practice with Head First
> Programming) to check whether an ingredient is Halal or Haram.
> I've a simple table online where some ingredients are either halal or
>  haram.
>
> For example, if the user enters "water" the program is supposed to tell him
> that it's halal;
> but it's returning ">" and other characters I don't want to see.
>
> What am I doing wrong?
>
> import urllib.request
>
> page = urllib.request.urlopen("
> http://halalingredients.theparleyonline.com/";)
> text = page.read().decode("utf8")
>
> halal_haram_status = text.find(input("Enter the ingredient:  "))
> begin_final_status = halal_haram_status + 3
> end_final_status = begin_final_status + 5
> status = text[begin_final_status:end_final_status]
> print(status)
>
>
> __


Can you copy and paste the error message traceback that you get?

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


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


[Tutor] Please help, the program is not behaving as I want

2011-05-17 Thread I. Dooba
I'm new to programming and have decided to start with Python following the
advice of experts including Eric S. Raymond.
So far I've learnt quite a lot from this list.

However, I've the following problem.

The program was designed (as part of my practice with Head First
Programming) to check whether an ingredient is Halal or Haram.
I've a simple table online where some ingredients are either halal or
 haram.

For example, if the user enters "water" the program is supposed to tell him
that it's halal;
but it's returning ">" and other characters I don't want to see.

What am I doing wrong?

import urllib.request

page = urllib.request.urlopen("http://halalingredients.theparleyonline.com/
")
text = page.read().decode("utf8")

halal_haram_status = text.find(input("Enter the ingredient:  "))
begin_final_status = halal_haram_status + 3
end_final_status = begin_final_status + 5
status = text[begin_final_status:end_final_status]
print(status)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] please help me

2010-01-31 Thread Luke Paireepinart
Please reply on-list unless you really need to speak to me off-list.
Use "reply-all" to reply to everyone.

Tutor doesn't work in that you get one of us as a tutor and we help you with
every problem you have.  For this mailing list you e-mail us a specific
problem and everyone collaborates to guide you through it.  When we say
"specific problem" we mean "you have coded a solution that looks to you like
it would work but it doesn't and you're stuck" and then we'll help you
figure out why you're stuck and what you need to do to fix the program.

(P.S. Sorry for the top-post, I'm not sure how to reply in-line to a
forwarded message.)


-- Forwarded message --
From: invincible patriot 
Date: Sun, Jan 31, 2010 at 4:05 AM
Subject: RE: [Tutor] please help me
To: rabidpoob...@gmail.com


 m sorry but i am not asking u to solve these for me rather i send all the
questions to u just to let u know what i want to do n now i m looking
froward for ur guidance so that i can write programme for thhem
i think itz fair enough to ask what should i do, but i am not asking u to
solve them for me
m just looking forward for some help


--
From: rabidpoob...@gmail.com
Date: Sat, 30 Jan 2010 19:39:05 -0600
Subject: Re: [Tutor] please help me
To: invincible_patr...@hotmail.com
CC: tutor@python.org


[snip homework]



please help me


This is a tutor mailing list.  Tutor means we will help you learn, not that
we will write your homework assignments for you for free.  That is the
opposite of learning.

Try all of the programs.  Give us what you have tried and what didn't work,
why you thought it would work, why you think it didn't work, and anything
else helpful (eg. if you get an error message include the whole traceback,
don't paraphrase it.)

In other words, if you don't have code that you've tried and a specific
problem you're having, you're not going to get a reply.  We're busy people,
make it easy for us to help you.

-Luke


--
Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. Sign up
now.<http://clk.atdmt.com/GBL/go/196390709/direct/01/>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2010-01-30 Thread Luke Paireepinart
[snip homework]

>
>
> please help me
>
>
This is a tutor mailing list.  Tutor means we will help you learn, not that
we will write your homework assignments for you for free.  That is the
opposite of learning.

Try all of the programs.  Give us what you have tried and what didn't work,
why you thought it would work, why you think it didn't work, and anything
else helpful (eg. if you get an error message include the whole traceback,
don't paraphrase it.)

In other words, if you don't have code that you've tried and a specific
problem you're having, you're not going to get a reply.  We're busy people,
make it easy for us to help you.

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


[Tutor] please help me

2010-01-30 Thread invincible patriot

hii am stuck in these questions can someone please help me in solving and 
writing programme for these tasks
please help me




1 1.1 Write a Python program with a loop that prints out a sequence of numbers 
as follows:151311...31-1

1.2 Write a small Python program that generates the list of all pairs of 
characters c andits doubling 2  c, where c moves through all the letters of 
the string "foobar" and prints it out.The result will look like:[(’f’, ’ff’), 
(’o’, ’oo’), (’o’, ’oo’), (’b’, ’bb’), (’a’, ’aa’), (’r’, ’rr’)]Hint: use list 
comprehensions.
1.3 Write a small Python program that
1. prints out the length of the 
string’taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu’
2. prints out how many different characters this string contains
3. replaces all the non-’t’ characters in above string with dots ’.’. So, if 
the word were’tattoo’, it would print ’t.tt..’.Hints:
(a) use a function to t-ify the string
(b) there are various ways to construct the string, either using the join 
method or by runninga loop accumulating substrings.
(c) check also out what happens if you apply the conversion list(s) to a string 
s.
2 2.1 Write a function count char(s, c) that takes a string s, and a character 
c and returnshow often the character c appears in the string.For example 
count_char("tattoo", "t") should return 3.

2.2 Write a Python function char_freqency(s)that returns a dictionary which, 
for eachcharacter of s as a key, stores as value how often this character 
appears.For example, char_frequency("tattoo") could return {’a’: 1, ’t’: 3, 
’o’: 2} (the order ofkey:value pairs does not matter here).
Hint: Consider using the function count_char defined in 2.1.
2.3 Write a program that translates a given string (of arbitrary length) of DNA 
bases intothe RNA strand that it will produce. For this, research which DNA 
bases correspond to RNA basesand create a translation table (not an if...else 
clause!) in the Python program. [4 marks]


3 
3.1 consider the following list of base 
sequences:ACGTACCTTACTTACCATATCGTACCTCTTACTCATThe task consists of writing a 
Python program that performs a simple alignment algorithm onthese two strings 
and prints out this alignment in a suitable readable form. Give a brief 
commentexplaining the output format.Hints:1. Matching means the following: for 
a given sequence to be matched, your program should denotewhich bases 
correspond to bases in the reference sequence and which do not; in addition, 
markgaps where the reference sequence contains bases which are not present in 
the sample sequence.For a given sample sequence, your matching algorithm will 
attempt to match as many basesas possible to those of the reference sequence.2. 
This is a difficult assignment. Do not attempt it before you have solved the 
others.3. For this purpose, you are allowed to research and implement publicly 
documented versions ofthe Needleman-Wunsch algorithm or similar algorithms 
(however, make sure that you refer-ence them properly!). Also make sure that 
your program prints out the matches/mismatchesbetween the sequences. You should 
demonstrate at least two different alignments by usingdifferent gap 
penalties.Instead of following this hint, you can develop an alternative 
solution to the matching problem,e.g. based on the Levenshtein distance.


please help me
_
Hotmail: Trusted email with Microsoft’s powerful SPAM protection.
http://clk.atdmt.com/GBL/go/196390706/direct/01/___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2009-06-18 Thread Emile van Sebille

On 6/18/2009 1:30 AM suzee Eslam said...

to every one help me please ..
i need the code to do chatting by python in mobiles over bluetooth 
technology .. i need it please if any one know it send it to me as soon 
as possible..

thanks for all.


Maybe this will get you started...

http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html

Emile

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


[Tutor] please help me

2009-06-18 Thread suzee Eslam
to every one help me please ..
i need the code to do chatting by python in mobiles over bluetooth technology 
.. i need it please if any one know it send it to me as soon as possible..
thanks for all.


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


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote


Please try what sqlite3.version shows on your machine?


I also have ActiveState's python (mainly for its very good doc) and 
I get:

>>> import sqlite3
sqlite3.sqlite_version

'3.3.4'


Me too with Python 2.5.1 from Activestate.

Alan G 



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


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread aivars
Hello, Denis,

Please try what sqlite3.version shows on your machine?

Thanks

aivars


2008/11/7 spir <[EMAIL PROTECTED]>:
> aivars a écrit :
>>
>> Thanks, John,
>> Yes it seems you are right. The ActiveState python version I have
>> installed have sqlite 2.3.2 only. I find it strange.
>
> I also have ActiveState's python (mainly for its very good doc) and I get:
 >>> import sqlite3
 sqlite3.sqlite_version
> '3.3.4'
>
> Denis
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-07 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote


Yes it seems you are right. The ActiveState python version I have
installed have sqlite 2.3.2 only. I find it strange.


Why? SQLite is a separate product. Python bundled the then
current version in its standard distribution, but time has moved on.
You have apparently installed a more recent version of SQLite.


I see that on a python website there is is a new version Python26


2.6 may or may not have the same version as you but regardless
you should be able to get the older version of Python to work
with the newer SQLite instal;l, provided the newer version has
a Python library available - which it usually has.


Mark Hammonds PythonWin to get other things for windows? Or maybe I
will reinstall ActiveState Python25 and install Python25 from the
official website


I don't thing the vanilla Python will make any difference. SQLite is
bundled with Python not with ActiveState.


Copying dll to c:\python25\DLLs directory did not help - it still
shows version sqlite version 2.3.2. which I also do not understand 
why


I think you might need to install more than the DLL. Check
the SQLite web site for a new Ptython interface and install
that version.

Alan G. 



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


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread aivars
John, just to add to my previous post.

after copying sqlite3.dll (3.6.2) version into Python25\DLLs directory
and running

import sqlite3
dir(sqlite3)

>>> sqlite3.version
'2.3.2'

>>> sqlite3.version_info
(2, 3, 2)

>>> sqlite3.sqlite_version_info
(3, 6, 2)

>>> sqlite3.sqlite_version
'3.6.2'

and now my scrip happily runs with sqlite replace function.

I am just curious why there are so many different version properties
and why now they differ from sqlite3.version?
Of course it seems Python now is running sqlite version 3.6.2 since my
script accepts replace function

Thanks,
Aivars



2008/11/7 aivars <[EMAIL PROTECTED]>:
> Thanks, John,
> Yes it seems you are right. The ActiveState python version I have
> installed have sqlite 2.3.2 only. I find it strange.
> I see that on a python website there is is a new version Python26
> relesed. Should i go on and install Python26? I understand that I can
> install pure Python from python website and after that I can install
> Mark Hammonds PythonWin to get other things for windows? Or maybe I
> will reinstall ActiveState Python25 and install Python25 from the
> official website
>
> Copying dll to c:\python25\DLLs directory did not help - it still
> shows version sqlite version 2.3.2. which I also do not understand why
>
> Re user defined function - it is one of the ways to go probably
> quickest but I would like to have newer version of sqlite being
> already with python
>
> I am noob in Python still
>
> Thanks for your input
>
> Aivars
>
>
>
> 2008/11/6 John Fouhy <[EMAIL PROTECTED]>:
>> 2008/11/7 aivars <[EMAIL PROTECTED]>:
>>> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2
>>
>> Hi Aivars,
>>
>> I believe python has its own built-in sqlite, rather than using the
>> version you installed independently.  So it is possible that the
>> python version of sqlite is older than 3.6.2 and does not yet have the
>> replace() function.
>>
>> (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
>> what version you are using)
>>
>> You could try replacing sqlite3.dll in your python25\dlls directory
>> with the DLL from your sqlite installation (make a backup first :-) ).
>>  Alternatively, you could define the replace() function in python and
>> then add it to your database: see
>> http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
>> .
>>
>> HTH.
>>
>> --
>> John.
>>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread aivars
Thanks, John,
Yes it seems you are right. The ActiveState python version I have
installed have sqlite 2.3.2 only. I find it strange.
I see that on a python website there is is a new version Python26
relesed. Should i go on and install Python26? I understand that I can
install pure Python from python website and after that I can install
Mark Hammonds PythonWin to get other things for windows? Or maybe I
will reinstall ActiveState Python25 and install Python25 from the
official website

Copying dll to c:\python25\DLLs directory did not help - it still
shows version sqlite version 2.3.2. which I also do not understand why

Re user defined function - it is one of the ways to go probably
quickest but I would like to have newer version of sqlite being
already with python

I am noob in Python still

Thanks for your input

Aivars



2008/11/6 John Fouhy <[EMAIL PROTECTED]>:
> 2008/11/7 aivars <[EMAIL PROTECTED]>:
>> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2
>
> Hi Aivars,
>
> I believe python has its own built-in sqlite, rather than using the
> version you installed independently.  So it is possible that the
> python version of sqlite is older than 3.6.2 and does not yet have the
> replace() function.
>
> (run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
> what version you are using)
>
> You could try replacing sqlite3.dll in your python25\dlls directory
> with the DLL from your sqlite installation (make a backup first :-) ).
>  Alternatively, you could define the replace() function in python and
> then add it to your database: see
> http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
> .
>
> HTH.
>
> --
> John.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with sqlite replace function

2008-11-06 Thread John Fouhy
2008/11/7 aivars <[EMAIL PROTECTED]>:
> I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2

Hi Aivars,

I believe python has its own built-in sqlite, rather than using the
version you installed independently.  So it is possible that the
python version of sqlite is older than 3.6.2 and does not yet have the
replace() function.

(run 'import sqlite3' and then examine 'sqlite3.sqlite_version' to see
what version you are using)

You could try replacing sqlite3.dll in your python25\dlls directory
with the DLL from your sqlite installation (make a backup first :-) ).
 Alternatively, you could define the replace() function in python and
then add it to your database: see
http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html#creating-user-defined-functions
.

HTH.

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


[Tutor] please help with sqlite replace function

2008-11-06 Thread aivars
Hello,
I am stuck now.

I have a sqlite database with a table calendar (which is an auxilary
calendar table containing dates, years, months, days)
>From sqlite prompt I can run the following query without any problem:

SELECT  replace( datums,'-','' ) FROM calendar where Y='2008' and M='5'

It gives me back date strings in the format MMDD.

But when I run it from the python script it gives me the following error:

sqlite3.OperationalError: no such function: replace.

Script is simple as follows:

import sqlite3
spath=r'e:\pythonexamples\aivars2.db'
sql="SELECT  replace(datums,'-','') FROM Calendar where Y='2008' and M='5'"
cn=sqlite3.connect(spath)

for row in cn.execute(sql):
print row[0]

When I run the script without the replace function in select statement
it runs OK.


I use python 2.5.2.2 (activestate), WinXP, sqlite version 3.6.2

Thanks for any tip.
maybe I should ask this to sqlite mailing list?

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


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread Steve Willoughby

aivars wrote:

Hello, Lie,
I renamed the directory back to Cgi-bin and the scripts are NOT
working. Going back to cgi-bin it works. I also do not understand why.

Aivars

2008/10/26 Lie Ryan <[EMAIL PROTECTED]>:

On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:


"aivars" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan
told.

I'm glad it worked but I confess I'm not sure why it worked. The
interpreter was apparently finding your script OK but it was the
environment that was messed up. I don't fully understand the interaction
going on  there. But in things web related I've learned that consistency
throughout is usually helpul!

Alan G.


I wouldn't have thought it could work, since Windows is case insensitive
and web server is required understand URL as case insensitive. Why that
Cgi-bin and cgi-bin differs on a windows-based server is beyond me.


Why do you think web servers are required to understand URLs as case
insensitive?  This is not the case (other than the domain name itself).


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


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread aivars
Hello, Lie,
I renamed the directory back to Cgi-bin and the scripts are NOT
working. Going back to cgi-bin it works. I also do not understand why.

Aivars

2008/10/26 Lie Ryan <[EMAIL PROTECTED]>:
> On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:
>
>> "aivars" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>>I finally get the script working!
>>>
>>> I renamed the script directory from Cgi-bin to cgi-bin just as Alan
>>> told.
>>
>> I'm glad it worked but I confess I'm not sure why it worked. The
>> interpreter was apparently finding your script OK but it was the
>> environment that was messed up. I don't fully understand the interaction
>> going on  there. But in things web related I've learned that consistency
>> throughout is usually helpul!
>>
>> Alan G.
>>
>
> I wouldn't have thought it could work, since Windows is case insensitive
> and web server is required understand URL as case insensitive. Why that
> Cgi-bin and cgi-bin differs on a windows-based server is beyond me.
>
> ___
> 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] please help with simple python CGI script

2008-10-26 Thread Lie Ryan
On Sun, 26 Oct 2008 08:32:52 +, Alan Gauld wrote:

> "aivars" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>>I finally get the script working!
>>
>> I renamed the script directory from Cgi-bin to cgi-bin just as Alan
>> told.
> 
> I'm glad it worked but I confess I'm not sure why it worked. The
> interpreter was apparently finding your script OK but it was the
> environment that was messed up. I don't fully understand the interaction
> going on  there. But in things web related I've learned that consistency
> throughout is usually helpul!
> 
> Alan G.
> 

I wouldn't have thought it could work, since Windows is case insensitive 
and web server is required understand URL as case insensitive. Why that 
Cgi-bin and cgi-bin differs on a windows-based server is beyond me.

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


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan 
told.


I'm glad it worked but I confess I'm not sure why it worked.
The interpreter was apparently finding your script OK but it
was the environment that was messed up. I don't fully
understand the interaction going on  there. But in things
web related I've learned that consistency throughout is
usually helpul!

Alan G.



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


Re: [Tutor] please help with simple python CGI script

2008-10-26 Thread aivars
I finally get the script working!

I renamed the script directory from Cgi-bin to cgi-bin just as Alan told.

Many thanks to all you who responded

Aivars


2008/10/26 aivars <[EMAIL PROTECTED]>:
> Thanks John and Alan
>
> I get the following error when I run the script from IDLE:
>
> Traceback (most recent call last):
>  File "C:\Cgi-bin\friends1.py", line 15, in 
>who = form['person'].value
>  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>raise KeyError, key
> KeyError: 'person'
>
>
> Aivars
> Windows XP, python 2.5
>
> 2008/10/26 John Pomni <[EMAIL PROTECTED]>:
>> what error do you get? It works without any changes on my Linux machine
>> with python 2.5
>>
>> John
>>
>> On Sat, 2008-10-25 at 21:33 +0300, aivars wrote:
>>> It does not work neither as script or from command line. I will try to
>>> find the guy Wesley Chun and ask him
>>>
>>> 2008/10/25 John Pomni <[EMAIL PROTECTED]>:
>>> > Hi,
>>> >
>>> > The script does not work from command line but I guess you do not have
>>> > any problems running it as CGI?
>>> >
>>> > I like cgitb modules for debugging purposes very much.
>>> >
>>> > http://www.python.org/doc/2.5.2/lib/node566.html
>>> >
>>> > Jan
>>> >
>>> > On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>>> >> Thanks very much, Kent,
>>> >>
>>> >> So it seems that directory /cgi-bin should be a subdirectory to that
>>> >> directory from which the web server was started/is running. That
>>> >> worked and Deitel's script - getting time displayed finally worked.
>>> >>
>>> >> still banging mu head with Wesley Chun's simple example -
>>> >>
>>> >> #!C:\python25\python.exe
>>> >>
>>> >> import cgi
>>> >>
>>> >> reshtml = '''Content-Type: text/html\n
>>> >> 
>>> >> Friends CGI Demo (dynamic screen)
>>> >> 
>>> >> Friends list for: %s
>>> >> Your name is: %s
>>> >> You have %s friends.
>>> >> '''
>>> >>
>>> >> form = cgi.FieldStorage()
>>> >> who = form['person'].value
>>> >> howmany = form['howmany'].value
>>> >> print reshtml % (who, who, howmany)
>>> >>
>>> >> It gives me the following error:
>>> >> Traceback (most recent call last):
>>> >>   File "C:\Cgi-bin\friends1.py", line 15, in 
>>> >> who = form['person'].value
>>> >>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>>> >> raise KeyError, key
>>> >> KeyError: 'person'
>>> >>
>>> >> I understand python is saying that there is no such a key in a directory.
>>> >>
>>> >> The HTML form looks like this. it is displayed correctly both in FF and 
>>> >> IE
>>> >>
>>> >>
>>> >> 
>>> >> Friends CGI Demo (static screen)
>>> >>
>>> >>   Friends list for: NEW USER
>>> >>
>>> >>   Enter your Name:
>>> >>   
>>> >>How many friends do you have?
>>> >> 0
>>> >>10
>>> >>25
>>> >>50
>>> >>100
>>> >>   
>>> >>
>>> >> Thanks again,
>>> >>
>>> >> Aivars
>>> >>
>>> >>
>>> >>
>>> >>
>>> >>
>>> >>
>>> >> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>>> >> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>>> >> >> Hello,
>>> >> >>
>>> >> >> I am learning python.
>>> >> >>
>>> >> >> I start the python CGI server like this:
>>> >> >>
>>> >> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>>> >> >> Python Programming chapter 20.5)
>>> >> >>
>>> >> >> The server starts in command prompt on windows XP by answering:
>>> >> >> Serving HTTP on 0.0.0.0 port 8000...
>>> >> >>
>>> >> >> Next I want to run this simple CGI script (from Deitel Python How to
>>> >> >> Program chapter 6). it is supposed to print out current date and time
>>> >> >> in a browser
>>> >> >
>>> >> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>>> >> > you run the script. The URL to run the CGI will then be something like
>>> >> > http:://localhost:8000/cgi-bin/myscript.py
>>> >> >
>>> >> > Kent
>>> >> >
>>> >> ___
>>> >> 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] please help with simple python CGI script

2008-10-25 Thread aivars
Thanks John and Alan

I get the following error when I run the script from IDLE:

Traceback (most recent call last):
  File "C:\Cgi-bin\friends1.py", line 15, in 
who = form['person'].value
  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
raise KeyError, key
KeyError: 'person'


Aivars
Windows XP, python 2.5

2008/10/26 John Pomni <[EMAIL PROTECTED]>:
> what error do you get? It works without any changes on my Linux machine
> with python 2.5
>
> John
>
> On Sat, 2008-10-25 at 21:33 +0300, aivars wrote:
>> It does not work neither as script or from command line. I will try to
>> find the guy Wesley Chun and ask him
>>
>> 2008/10/25 John Pomni <[EMAIL PROTECTED]>:
>> > Hi,
>> >
>> > The script does not work from command line but I guess you do not have
>> > any problems running it as CGI?
>> >
>> > I like cgitb modules for debugging purposes very much.
>> >
>> > http://www.python.org/doc/2.5.2/lib/node566.html
>> >
>> > Jan
>> >
>> > On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>> >> Thanks very much, Kent,
>> >>
>> >> So it seems that directory /cgi-bin should be a subdirectory to that
>> >> directory from which the web server was started/is running. That
>> >> worked and Deitel's script - getting time displayed finally worked.
>> >>
>> >> still banging mu head with Wesley Chun's simple example -
>> >>
>> >> #!C:\python25\python.exe
>> >>
>> >> import cgi
>> >>
>> >> reshtml = '''Content-Type: text/html\n
>> >> 
>> >> Friends CGI Demo (dynamic screen)
>> >> 
>> >> Friends list for: %s
>> >> Your name is: %s
>> >> You have %s friends.
>> >> '''
>> >>
>> >> form = cgi.FieldStorage()
>> >> who = form['person'].value
>> >> howmany = form['howmany'].value
>> >> print reshtml % (who, who, howmany)
>> >>
>> >> It gives me the following error:
>> >> Traceback (most recent call last):
>> >>   File "C:\Cgi-bin\friends1.py", line 15, in 
>> >> who = form['person'].value
>> >>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>> >> raise KeyError, key
>> >> KeyError: 'person'
>> >>
>> >> I understand python is saying that there is no such a key in a directory.
>> >>
>> >> The HTML form looks like this. it is displayed correctly both in FF and IE
>> >>
>> >>
>> >> 
>> >> Friends CGI Demo (static screen)
>> >>
>> >>   Friends list for: NEW USER
>> >>
>> >>   Enter your Name:
>> >>   
>> >>How many friends do you have?
>> >> 0
>> >>10
>> >>25
>> >>50
>> >>100
>> >>   
>> >>
>> >> Thanks again,
>> >>
>> >> Aivars
>> >>
>> >>
>> >>
>> >>
>> >>
>> >>
>> >> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>> >> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> >> >> Hello,
>> >> >>
>> >> >> I am learning python.
>> >> >>
>> >> >> I start the python CGI server like this:
>> >> >>
>> >> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> >> >> Python Programming chapter 20.5)
>> >> >>
>> >> >> The server starts in command prompt on windows XP by answering:
>> >> >> Serving HTTP on 0.0.0.0 port 8000...
>> >> >>
>> >> >> Next I want to run this simple CGI script (from Deitel Python How to
>> >> >> Program chapter 6). it is supposed to print out current date and time
>> >> >> in a browser
>> >> >
>> >> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>> >> > you run the script. The URL to run the CGI will then be something like
>> >> > http:://localhost:8000/cgi-bin/myscript.py
>> >> >
>> >> > Kent
>> >> >
>> >> ___
>> >> 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] please help with simple python CGI script

2008-10-25 Thread Alan Gauld


"aivars" <[EMAIL PROTECTED]> wrote 




still banging mu head with Wesley Chun's simple example -


I'm not sure if this is significant but


It gives me the following error:
Traceback (most recent call last):
 File "C:\Cgi-bin\friends1.py", line 15, in 


Notice that the file path has Cgi not cgi
Case may be significant...


  


The action expects cgi

Just a thought.


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] please help with simple python CGI script

2008-10-25 Thread aivars
It does not work neither as script or from command line. I will try to
find the guy Wesley Chun and ask him

2008/10/25 John Pomni <[EMAIL PROTECTED]>:
> Hi,
>
> The script does not work from command line but I guess you do not have
> any problems running it as CGI?
>
> I like cgitb modules for debugging purposes very much.
>
> http://www.python.org/doc/2.5.2/lib/node566.html
>
> Jan
>
> On Fri, 2008-10-24 at 18:55 +0300, aivars wrote:
>> Thanks very much, Kent,
>>
>> So it seems that directory /cgi-bin should be a subdirectory to that
>> directory from which the web server was started/is running. That
>> worked and Deitel's script - getting time displayed finally worked.
>>
>> still banging mu head with Wesley Chun's simple example -
>>
>> #!C:\python25\python.exe
>>
>> import cgi
>>
>> reshtml = '''Content-Type: text/html\n
>> 
>> Friends CGI Demo (dynamic screen)
>> 
>> Friends list for: %s
>> Your name is: %s
>> You have %s friends.
>> '''
>>
>> form = cgi.FieldStorage()
>> who = form['person'].value
>> howmany = form['howmany'].value
>> print reshtml % (who, who, howmany)
>>
>> It gives me the following error:
>> Traceback (most recent call last):
>>   File "C:\Cgi-bin\friends1.py", line 15, in 
>> who = form['person'].value
>>   File "C:\Python25\lib\cgi.py", line 567, in __getitem__
>> raise KeyError, key
>> KeyError: 'person'
>>
>> I understand python is saying that there is no such a key in a directory.
>>
>> The HTML form looks like this. it is displayed correctly both in FF and IE
>>
>>
>> 
>> Friends CGI Demo (static screen)
>>
>>   Friends list for: NEW USER
>>
>>   Enter your Name:
>>   
>>How many friends do you have?
>> 0
>>10
>>25
>>50
>>100
>>   
>>
>> Thanks again,
>>
>> Aivars
>>
>>
>>
>>
>>
>>
>> 2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
>> > On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> >> Hello,
>> >>
>> >> I am learning python.
>> >>
>> >> I start the python CGI server like this:
>> >>
>> >> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> >> Python Programming chapter 20.5)
>> >>
>> >> The server starts in command prompt on windows XP by answering:
>> >> Serving HTTP on 0.0.0.0 port 8000...
>> >>
>> >> Next I want to run this simple CGI script (from Deitel Python How to
>> >> Program chapter 6). it is supposed to print out current date and time
>> >> in a browser
>> >
>> > The CGI script should me in a /cgi-bin subdirectory of the dir where
>> > you run the script. The URL to run the CGI will then be something like
>> > http:://localhost:8000/cgi-bin/myscript.py
>> >
>> > Kent
>> >
>> ___
>> 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] please help with simple python CGI script

2008-10-24 Thread aivars
Thanks very much, Kent,

So it seems that directory /cgi-bin should be a subdirectory to that
directory from which the web server was started/is running. That
worked and Deitel's script - getting time displayed finally worked.

still banging mu head with Wesley Chun's simple example -

#!C:\python25\python.exe

import cgi

reshtml = '''Content-Type: text/html\n

Friends CGI Demo (dynamic screen)

Friends list for: %s
Your name is: %s
You have %s friends.
'''

form = cgi.FieldStorage()
who = form['person'].value
howmany = form['howmany'].value
print reshtml % (who, who, howmany)

It gives me the following error:
Traceback (most recent call last):
  File "C:\Cgi-bin\friends1.py", line 15, in 
who = form['person'].value
  File "C:\Python25\lib\cgi.py", line 567, in __getitem__
raise KeyError, key
KeyError: 'person'

I understand python is saying that there is no such a key in a directory.

The HTML form looks like this. it is displayed correctly both in FF and IE



Friends CGI Demo (static screen)
   
  Friends list for: NEW USER
   
  Enter your Name:
  
   How many friends do you have?
0
   10
   25
   50
   100
  

Thanks again,

Aivars






2008/10/24 Kent Johnson <[EMAIL PROTECTED]>:
> On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> I am learning python.
>>
>> I start the python CGI server like this:
>>
>> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
>> Python Programming chapter 20.5)
>>
>> The server starts in command prompt on windows XP by answering:
>> Serving HTTP on 0.0.0.0 port 8000...
>>
>> Next I want to run this simple CGI script (from Deitel Python How to
>> Program chapter 6). it is supposed to print out current date and time
>> in a browser
>
> The CGI script should me in a /cgi-bin subdirectory of the dir where
> you run the script. The URL to run the CGI will then be something like
> http:://localhost:8000/cgi-bin/myscript.py
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help with simple python CGI script

2008-10-24 Thread Kent Johnson
On Fri, Oct 24, 2008 at 10:25 AM, aivars <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am learning python.
>
> I start the python CGI server like this:
>
> python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
> Python Programming chapter 20.5)
>
> The server starts in command prompt on windows XP by answering:
> Serving HTTP on 0.0.0.0 port 8000...
>
> Next I want to run this simple CGI script (from Deitel Python How to
> Program chapter 6). it is supposed to print out current date and time
> in a browser

The CGI script should me in a /cgi-bin subdirectory of the dir where
you run the script. The URL to run the CGI will then be something like
http:://localhost:8000/cgi-bin/myscript.py

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


[Tutor] please help with simple python CGI script

2008-10-24 Thread aivars
Hello,

I am learning python.

I start the python CGI server like this:

python -m CGIHTTPServer (this syntax I saw in Wesley Chun's Core
Python Programming chapter 20.5)

The server starts in command prompt on windows XP by answering:
Serving HTTP on 0.0.0.0 port 8000...

Next I want to run this simple CGI script (from Deitel Python How to
Program chapter 6). it is supposed to print out current date and time
in a browser

#!C:\python25\python.exe
import time

def printHeader(title):
print """Content-type: text/html



http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>
http://www.w3.org/1999/xhtml"; >
%s

""" % title

printHeader("Current date and time")
print time.ctime(time.time())
print ""


And The server prints the script text in the browser. It does not run
the script.
The server response is 200.
The script itself runs OK if being run from python/command line

I also could not run the script from wesley chun's book. I think also
because it seems the python cgi web server does not understand that it
should run the script and not to print it out in web browser

I am using python 2.5 on windows XP.

What I am missing?

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


Re: [Tutor] please help formating

2007-05-25 Thread Kent Johnson
Just for fun, here is a parser written with pyparsing. It treats 
newlines as whitespace so it will work with the split data you posted.
http://pyparsing.wikispaces.com/

data = '''(39577484, 39577692) [['NM_003750']]
(107906, 108011) [['NM_002443']]
(113426, 113750) [['NM_138634', 'NM_002443']]
(106886, 106991) [['NM_138634', 'NM_002443']]
(100708, 100742) [['NM_138634', 'NM_002443']]
(35055935, 35056061) [['NM_002313', 'NM_001003407',
  'NM_001003408']]
'''

from pyparsing import *
keys = Suppress('(') + Word(nums) + Suppress(',') + Word(nums) + 
Suppress(')')
values = Group(Suppress('[[') + 
delimitedList(sglQuotedString.setParseAction(removeQuotes)) + 
Suppress(']]'))
expr = keys + values

for result, start, end in expr.scanString(data):
 print '%s %s\t%s' % (result[0], result[1], ','.join(result[2]))


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


Re: [Tutor] please help formating

2007-05-25 Thread Kent Johnson
kumar s wrote:
> hi group,
> 
> i have a data obtained from other student(over 100K)
> lines that looks like this:
> (39577484, 39577692) [['NM_003750']]
> (107906, 108011) [['NM_002443']]
> (113426, 113750) [['NM_138634', 'NM_002443']]
> (106886, 106991) [['NM_138634', 'NM_002443']]
> (100708, 100742) [['NM_138634', 'NM_002443']]
> (35055935, 35056061) [['NM_002313', 'NM_001003407',
> 'NM_001003408']]
> 
> I know that first two items in () are tuples, and the
> next [[]] a list of list. I was told that the tuples
> were keys and the list was its value in a dictionary.
> 
> how can I parse this into a neat structure that looks
> like this:
> 39577484, 39577692 \t NM_003750
> 107906, 108011 \t NM_002443
> 113426, 113750 \t  NM_138634,NM_002443
> 106886, 106991 \t  NM_138634,NM_002443
> 100708, 100742 \t  NM_138634,NM_002443
> 35055935, 35056061 \t
> NM_002313,NM_001003407,NM_001003408

How about this (assuming the line wrap at the end was done by mail; if 
it is in the data it is a little harder to parse it):

data = '''(39577484, 39577692) [['NM_003750']]
(107906, 108011) [['NM_002443']]
(113426, 113750) [['NM_138634', 'NM_002443']]
(106886, 106991) [['NM_138634', 'NM_002443']]
(100708, 100742) [['NM_138634', 'NM_002443']]
(35055935, 35056061) [['NM_002313', 'NM_001003407', 'NM_001003408']]
'''.splitlines()

import re
for line in data:
 match = re.match(r'\((\d*), (\d*)\) \[\[(.*)\]\]', line)
 if match:
 t1, t2, data = match.group(1, 2, 3)
 data = data.replace("'", "").replace(' ', '')
 print '%s %s\t%s' % (t1, t2, data)
 else:
 print 'no match:', line


Note the format of the data here is different from what you showed in 
your post last night...

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


Re: [Tutor] please help formating

2007-05-22 Thread Andreas Kostyrka
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Why does my "homework-alert" ring with this post?

Andreas

kumar s wrote:
> hi group,
> 
> i have a data obtained from other student(over 100K)
> lines that looks like this:
> (39577484, 39577692) [['NM_003750']]
> (107906, 108011) [['NM_002443']]
> (113426, 113750) [['NM_138634', 'NM_002443']]
> (106886, 106991) [['NM_138634', 'NM_002443']]
> (100708, 100742) [['NM_138634', 'NM_002443']]
> (35055935, 35056061) [['NM_002313', 'NM_001003407',
> 'NM_001003408']]
> 
> I know that first two items in () are tuples, and the
> next [[]] a list of list. I was told that the tuples
> were keys and the list was its value in a dictionary.
> 
> how can I parse this into a neat structure that looks
> like this:
> 39577484, 39577692 \t NM_003750
> 107906, 108011 \t NM_002443
> 113426, 113750 \t  NM_138634,NM_002443
> 106886, 106991 \t  NM_138634,NM_002443
> 100708, 100742 \t  NM_138634,NM_002443
> 35055935, 35056061 \t
> NM_002313,NM_001003407,NM_001003408
> 
> 
> I treid substituting in vim editor but it is not
> effective. 
> 
> Thank you
> 
> kum
> 
> 
>
> Pinpoint
>  customers who are looking for what you sell. 
> http://searchmarketing.yahoo.com/
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.2 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGU2ZmHJdudm4KnO0RAnIgAJ4oHRPSfYFId7C7TzeWYXPobf9l+QCg34Ja
bRtlufQ7K/TKPsLOOBNEmJI=
=QeIu
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] please help formating

2007-05-22 Thread kumar s
hi group,

i have a data obtained from other student(over 100K)
lines that looks like this:
(39577484, 39577692) [['NM_003750']]
(107906, 108011) [['NM_002443']]
(113426, 113750) [['NM_138634', 'NM_002443']]
(106886, 106991) [['NM_138634', 'NM_002443']]
(100708, 100742) [['NM_138634', 'NM_002443']]
(35055935, 35056061) [['NM_002313', 'NM_001003407',
'NM_001003408']]

I know that first two items in () are tuples, and the
next [[]] a list of list. I was told that the tuples
were keys and the list was its value in a dictionary.

how can I parse this into a neat structure that looks
like this:
39577484, 39577692 \t NM_003750
107906, 108011 \t NM_002443
113426, 113750 \t  NM_138634,NM_002443
106886, 106991 \t  NM_138634,NM_002443
100708, 100742 \t  NM_138634,NM_002443
35055935, 35056061 \t
NM_002313,NM_001003407,NM_001003408


I treid substituting in vim editor but it is not
effective. 

Thank you

kum


   
Pinpoint
 customers who are looking for what you sell. 
http://searchmarketing.yahoo.com/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2007-04-13 Thread Greg Perry
Let no good deed go unpunished!

-Original Message-
From: Daniel Yoo
Date: Friday, Apr 13, 2007 8:24 pm
Subject: Re: [Tutor] please help me

> If this is homework, please tell your teacher I helped - I need the 
> extra credit.
>
>Please avoid giving homework answers like this.  Rather than actually help 
>the person, it can do harm, because it encourages a lazy attitude toward 
>solving problems.



___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] please help me

2007-04-13 Thread Daniel Yoo
> If this is homework, please tell your teacher I helped - I need the 
> extra credit.

Please avoid giving homework answers like this.  Rather than actually help 
the person, it can do harm, because it encourages a lazy attitude toward 
solving problems.
___
Tutor maillist  -  [EMAIL PROTECTED]
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


Re: [Tutor] please help me!

2007-04-12 Thread Kent Johnson
suryo agung wrote:
> pleate tell me how to make
> 
> input number=4
> result
> 
> 1
> 22
> 333
> 
> 
> in python
> please give me your answer.

This looks a lot like homework to me. What have you tried? What have you 
learned?

Kent
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


[Tutor] please help me!

2007-04-12 Thread suryo agung
pleate tell me how to make

input number=4
result

1
22
333


in python
please give me your answer.
___
Tutor maillist  -  [EMAIL PROTECTED]
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Danny Yoo
>> def hello():
>>   return "Hello World"
>>
>>   server = SOAP.SOAPServer(("localhost", 23000))
>>   server.registerFunction(hello)
>>   server.serve_forever()
>
> Have you tried running server.py?  There's a glaring error in it. (Hint: SOAP 
> != SOAPpy)


Actually, there's a much more glaring error in it.  Note the early exit 
from 'return "hello world".  The program is escaping out too quickly.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Danny Yoo
> *#server.py*
> import SOAPpy
>
>
> def hello():
>   return "Hello World"
>
>   server = SOAP.SOAPServer(("localhost", 23000))
>   server.registerFunction(hello)
>   server.serve_forever()

Hi Asrarahmed,

I also want to reiterate what Luke said: it does get a little irritating 
if we see the same question repeated.  Try reading:

 http://catb.org/esr/faqs/smart-questions.html

to get a better feel for what kind of things help us answer your questions 
better.


Have you tried running server.py?  There's a glaring error in it. (Hint: 
SOAP != SOAPpy)

I know it might sound silly, but just to make sure you understand: the 
server must be up and running before you try contacting it with the 
client.

Also, you may want to reconsider SOAPpy: we've had previous discussion 
where it was apparent SOAPpy is a dead project:

 http://mail.python.org/pipermail/tutor/2006-November/050530.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
> Hi,
Asrarahmed:
You posted this exact question only 4 hours ago.
Reposting questions this quickly is an abuse of the mailing list, as far 
as I'm concerned.
If you don't wait at _minimum_ a full day, preferably at least 2, for an 
answer, it just irritates
people and makes it less likely for you to get an answer.
People may completely disregard this question now, just as a matter of 
principle,
so that they don't give you the idea that reposting is appreciated.
Not mad or anything, just informing you.

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


Re: [Tutor] Please help to resolve this...

2006-11-08 Thread Andreas Kostyrka
* Asrarahmed Kadri <[EMAIL PROTECTED]> [061108 19:51]:
> Hi,
> 
> I have successfully installed the SOAPpy module. The version is 0.11.6
> 
> I am trying to run simple test program for server and cliet. The script for
> server is executing without any error; but the client script is giving me

Well, the error means that nothing is listening on port 23000 on localhost. 
Firewall?

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


[Tutor] Please help to resolve this...

2006-11-08 Thread Asrarahmed Kadri
Hi,
 
I have successfully installed the SOAPpy module. The version is 0.11.6
 
I am trying to run simple test program for server and cliet. The script for server is executing without any error; but the client script is giving me the error as below. 
TRACEBACK:
 
C:\project stuff-programs>python client.pyTraceback (most recent call last):  File "client.py", line 4, in ?    print server.hello()  File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 453, in __call__ 
    return self.__r_call(*args, **kw)  File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 475, in __r_call    self.__hd, self.__ma)  File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 347, in __call 
    config = self.config)  File "C:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in call    r.endheaders()  File "C:\Python24\lib\httplib.py", line 798, in endheaders    self._send_output() 
  File "C:\Python24\lib\httplib.py", line 679, in _send_output    self.send(msg)  File "C:\Python24\lib\httplib.py", line 646, in send    self.connect()  File "C:\Python24\lib\httplib.py", line 630, in connect 
    raise socket.error, msgsocket.error: (10061, 'Connection refused') 
 
#server.py
import SOAPpy
def hello():    return "Hello World"
    server = SOAP.SOAPServer(("localhost", 23000))    server.registerFunction(hello)    server.serve_forever()
# client.py

import SOAPpy
server = SOAPpy.SOAPProxy("http://localhost:23000/")print server.hello()

TIA.
 
 
Best Regards,
Asrarahmed-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function..

2006-11-07 Thread ALAN GAULD
Reposting to the list.

--- Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:

> > >except ValueError:
> > >flag = False
> > >startdate = None
> > >enddate = None
> > >err_msg = traceback.format_exc()
> > >index = string.find(err_msg,'Value')
> > >print err_msg[index:]
> > >return (flag,startdate,enddate)
> >
> >Since this block is essentially identical to the except
> >block above you could package them both as a function 
> >which would shorten the code a little.

> It might seem silly, but can you just give a hint as to how to
> put the code in a function..

def handleValueError():
flag = False
startdate = None
enddate = None
err_msg = traceback.format_exc()
index = err_msg.find('Value')
print err_msg[index:]
return (flag,startdate,enddate)

And in your code above:

except ValueError:
return handleValueError()

> > It would be better to raise a ValueError which can be caught
> > by the external program:

> How to catch the exception from one module into another ..???

Just use try/except as usual. There is no difference 
to exceptions thrown by your code and the ones thrown 
by the standard Python functions. Consider:

### module.py ###

def f():
   raise ValueError

##

## main.py ##
import module

try:
   module.f()
except ValueError:
   print "It broke!"

#

Is that clear?

Alan G








___ 
All new Yahoo! Mail "The new Interface is stunning in its simplicity and ease 
of use." - PC Magazine 
http://uk.docs.yahoo.com/nowyoucan.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function.. it takes a date and num. of days and returns startdate and enddate (fwd)

2006-11-06 Thread Danny Yoo
[Forwarding to Tutor; busy at the moment]

-- Forwarded message --
Date: Mon, 6 Nov 2006 18:41:54 +
From: Asrarahmed Kadri <[EMAIL PROTECTED]>
To: Danny Yoo <[EMAIL PROTECTED]>
Subject: Re: [Tutor] Please help to debug this function.. it takes a date and
 num. of days and returns startdate and enddate

Hi Danny,

Can you please test it !!!
Also I would like to know if it can be coded in a better way...

TIA.

Regards,
Asrarahmed


On 11/6/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
>
> On Mon, 6 Nov 2006, Asrarahmed Kadri wrote:
>
>> I have written a function that takes a date and an integer representing
>> the number of days.
>>
>> Please test it, comment on the logic .
>
>
> Hi Asrarahmed,
>
> You should be able to write your own tests too.  You might want to look
> at:
>
> http://www.diveintopython.org/unit_testing/index.html
>
> for an example of how to write unit tests; the author there goes through
> an example with a Roman Numeral program written with unit tests.
>



-- 
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please help to debug this function.. it takes a date andnum. of days and returns startdate and enddate

2006-11-06 Thread Alan Gauld

"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote

> Please test it, comment on the logic .

I haven't tested it but here are some comments:

> import string
> import datetime
> import traceback
>
> def dateCheck(date1,num_days):
>flag = True
>startdate = None
>enddate = None
>
>if num_days < 0 or num_days > 31:
>flag = False
>print "The argument for -n has to be between 0 and 31"
>return (flag,startdate,enddate)
>
>else:

You don't need the else since the if block returns.
Thus you only reach the followiong code if the test is false.
This reduces the anumber of levels of indenting by one which
improves readability and thus maintenance.

>date_lst = string.split(date1,"/")

better to use the string methods. ie date1.split('/')

>ln = len(date_lst)
>if ln != 3 :

you could have combined those lines into one since you never
use 'ln' except in the test.

if len(date1.split('/') != 3:


>flag = False
>print "The argument for -D option has to be in the 
> format:
> dd/mm/"
>return (flag,startdate,enddate)
>else:

Same as above, the else is just adding levels of indentation.

>date_lst.reverse()
>print date_lst
>try:
>if int(date_lst[0]) < 2000:
>flag = False
>print "The year cannot be earlier than 2000 and 
> it
> should be in the format ''."
>return (flag,startdate,enddate)
>except ValueError:
>flag = False
>err_msg = traceback.format_exc()
>index = string.find(err_msg,'Value')

Again use the string method:

index = err_msg.find('Value')

>print err_msg[index:]
>return (flag,startdate,enddate)
>
>try:
>startdate = datetime.date
> (int(date_lst[0]),int(date_lst[1]),int(date_lst[2]))
>enddate = startdate + 
> datetime.timedelta(days=num_days)
>print startdate, enddate
>
>except ValueError:
>
>flag = False
>startdate = None
>enddate = None
>err_msg = traceback.format_exc()
>index = string.find(err_msg,'Value')
>print err_msg[index:]
>return (flag,startdate,enddate)

Since this block is essentially identical to the except block above
you could package them both as a function which would shorten
the code a little.

>if enddate > datetime.date.today():
>enddate = datetime.date.today()
>if startdate > datetime.date.today():
>flag = False
>startdate = None
>enddate = None
>print "The -D option should have a date not later 
> than
> today's date"

Since this is a function and not part of the user interface there
shouldn't really be any knowledge of the -D option in this code.
What if you want to call it from another module that uses
different options?

It would be better to raise a ValueError which can be caught
by the external program:

 raise ValueEerror ("startdate later than today")


>return (flag,startdate,enddate)
> 

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


  1   2   >