[Tutor] networking

2004-12-27 Thread Marco
Hi python tutors,
Im interested on learning python but i would like to focus in a specific topic, 
networking, where can i find documention networking in python? sockets and all 
that stuff? i looked for some information but all of them were just vague.
thanks in advance,
Marco


-- 
"If knowledge can create problems, it is not through ignorance that we can 
solve them."
- Isaac Asimov

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


[Tutor] documentation tut.html Error 404

2008-10-17 Thread Marco
hi list,

the link provided in one of the initiation mails from the tutor-mailinglist:

...
http://www.python.org/doc/current/tut/tut.html
...

responds with a 404 error.

Best regards, 
 marco

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


[Tutor] Using Python with a Mac

2010-02-21 Thread Marco Rompré
Hi everyone, I would like to know how to use python with a mac.

For now, I go to spotlight, open terminal then type IDLE and a window pops
up but its like the window that opens when you run your programs already
saved and I'm not able to open another window to write a script from
scratch.

Could someone help me please please

I have the latest Macbook Pro so 2,88ghz 15 inches screen.

Thank you in advance

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


[Tutor] Macbook Pro+python programming

2010-03-09 Thread Marco Rompré
Does anybody know any good python emulator that would work perfectly with
Mac OSX Leopard?

Because I just got a brand new Mac (the one on apple store) and it seems
that the build in Python 2.6.1 from darwin is garbage I'm running a 2,88 ghz
dual core and each time I open terminal, then type idle and try to use IDLE
the screen freezes (something you would never expect with a computer with my
specs) and I must force quit the application to be able to continue using my
computer.

Please someone help me
I'm at university and I always do python in my intro course.

Thank you
-- 
Marc-O. Rompré
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem with turtle

2010-03-11 Thread Marco Rompré
Hi! I am relatively new to python and turtle and I really need your help.

Here what I wanted turtle to do: I created a function named carré which
would draw a square with 3 different parameters (color, size, angle).
  I did the same for a function
named triangle that would draw an equilateral triangle with the same
parameters
  With the help of these 2
functions I wanted turtle to draw a yellow square then lift my pointer let a
space and then draw a blue triangle five times in a row.

Here's my code: ignore my comments

def carre(taille, couleur, angle):
"fonction qui dessine un carré de taille et de couleur déterminées"
color(couleur)
c=0
while c<4:
left(angle)
forward(taille)
right(90)
c = c+1

def triangle(taille, couleur, angle):
"fonction qui dessine un triangle équilatéral de taille, de couleur et
d'angle déterminés"
color(couleur)
c=0
while c<3:
left(angle)
forward(taille)
right(120)
c = c+1

from dessins_tortue import *

n=0
while n < 10 :
down() # abaisser le crayon
carre(25, 'yellow', 0) # tracer un carré
up()
forward(30)
triangle(90, 'blue',0)
n = n + 1


If I am to vague I wanted to do successfully exercise 7.6 in Gérard Swinnen
tutorial for Python

It was supposed to look like this

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


Re: [Tutor] Problem with turtle

2010-03-11 Thread Marco Rompré
I wanted turtle to draw alternatively a square and a triangle with a space
between them each with a specific color, angle(orientation as you said),
size. Instead, turtle was drawing a yellow square then it was drawing a
triangle on the sqare but with no lines whatsovever like it was just going
over it and the last problem was that it was never stopping and i had to
rstart the shell to make it stop.

I hope I am more precis with my explanations.

Thanks for helping me learn

On Thu, Mar 11, 2010 at 1:26 PM, Alan Gauld wrote:

>
> "Marco Rompré"  wrote
>
>
>  Hi! I am relatively new to python and turtle and I really need your help.
>>
>
> Thats what we are hee for but
>
>
>  Here's my code: ignore my comments
>>
>
> n=0
> while n < 10 :
>   down() # abaisser le crayon
>   carre(25, 'yellow', 0) # tracer un carré
>   up()
>   forward(30)
>   triangle(90, 'blue',0)
> n = n + 1
>
>
>  If I am to vague I wanted to do successfully exercise 7.6 in Gérard
>> Swinnen
>> tutorial for Python
>>
>> It was supposed to look like this
>>
>
> So what happens? Is there an error message or does it just draw
> the wrong thing? Don't make us guess...
>
>
>
> --
> Alan Gauld
> 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
>



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


Re: [Tutor] Problem with turtle

2010-03-11 Thread Marco Rompré
It does not work either with the for n in range (10):

On Thu, Mar 11, 2010 at 2:53 PM, Vern Ceder wrote:

> Ooops... missed a closing parenthese... that should be:
>
>
> for n in range(10):
> 
>
> Vern Ceder wrote:
>
>> It looks like the indentation of n = n + 1 is wrong - it will be outside
>> of the while loop and so n will never increment and the loop will never end.
>>
>> Instead of a while loop I would suggest a for loop:
>>
>> for n in range(10:
>>
>>
>> HTH,
>>
>> Vern
>>
>> Marco Rompré wrote:
>>
>>> I wanted turtle to draw alternatively a square and a triangle with a
>>> space between them each with a specific color, angle(orientation as you
>>> said), size. Instead, turtle was drawing a yellow square then it was drawing
>>> a triangle on the sqare but with no lines whatsovever like it was just going
>>> over it and the last problem was that it was never stopping and i had to
>>> rstart the shell to make it stop.
>>>
>>> I hope I am more precis with my explanations.
>>>
>>> Thanks for helping me learn
>>>
>>> On Thu, Mar 11, 2010 at 1:26 PM, Alan Gauld 
>>> >> alan.ga...@btinternet.com>> wrote:
>>>
>>>
>>>"Marco Rompré" >><mailto:marcodrom...@gmail.com>> wrote
>>>
>>>
>>>Hi! I am relatively new to python and turtle and I really need
>>>your help.
>>>
>>>
>>>Thats what we are hee for but
>>>
>>>
>>>Here's my code: ignore my comments
>>>
>>>
>>>n=0
>>>while n < 10 :
>>>  down() # abaisser le crayon
>>>  carre(25, 'yellow', 0) # tracer un carré
>>>  up()
>>>  forward(30)
>>>  triangle(90, 'blue',0)
>>>n = n + 1
>>>
>>>
>>>If I am to vague I wanted to do successfully exercise 7.6 in
>>>Gérard Swinnen
>>>tutorial for Python
>>>
>>>It was supposed to look like this
>>>
>>>
>>>So what happens? Is there an error message or does it just draw
>>>the wrong thing? Don't make us guess...
>>>
>>>
>>>
>>>-- Alan Gauld
>>>Author of the Learn to Program web site
>>>http://www.alan-g.me.uk/
>>>
>>>___
>>>Tutor maillist  -  Tutor@python.org <mailto:Tutor@python.org>
>>>To unsubscribe or change subscription options:
>>>http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>>
>>>
>>> --
>>> Marc-O. Rompré
>>>
>>>
>>> 
>>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
> --
> This time for sure!
>   -Bullwinkle J. Moose
> -
> Vern Ceder, Director of Technology
> Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804
> vce...@canterburyschool.org; 260-436-0746; FAX: 260-436-5137
>
> The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW
>



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


Re: [Tutor] Problem with turtle

2010-03-12 Thread Marco Rompré
The thing is that the teacher wanted us to use a while loop like in the
notes but even in the notes I copied the code and it was not working either.

Now, I'm more on the right track, I am able to draw the forms and the
counter is almost working, the reason I say that is because turtle is doin
what I want it to do but twice and then its bugs.

For example it will trace my 10  red squares with a specific space between
them then it will redraw them all once but all on the same squares like it
would want the trace to be stronger or somehting like that.

Here's my code now:

from turtle import *

def carre(taille, couleur, angle):
"fonction qui dessine un carré de taille et de couleur déterminées"
color(couleur)
c=0
while c<4:
left(angle)
forward(taille)
right(90)
c = c+1

def triangle(taille, couleur, angle):
"fonction qui dessine un triangle équilatéral de taille, de couleur et
d'angle déterminés"
color(couleur)
c=0
while c<3:
left(angle)
forward(taille)
right(120)
c = c+1

from dessins_tortue import *
up()
goto(-400,0)

n=0
while n < 10:
down() # abaisser le crayon
carre(25*n, 'red', 0)# tracer un carré
up()
forward(30*n)
n=n+1
#triangle(90, 'blue',0)
#up()
#forward(115)

I put the triangle fucntion in comments cause I was trying to make the carré
function working before.


Thank You


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


[Tutor] Problem with little program

2010-03-13 Thread Marco Rompré
Hello I have a little problem, I am trying to define a function ligneCar(n,
ca) that would print n times the caracters ca.
For now I have the user entering a short sentence corresponding to ca.

Here is my code:

def ligneCar(n,ca):
c=0
while c___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hi there!

2010-03-16 Thread Marco Rompré
Hi! Does anyone of you know where to find all the solutions of Gerard
Swinnen Python tutorial exercises 

In the tutorial we just have the solutions to half of the exercises.

Thank you

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


[Tutor] Simple bank account oriented object

2010-03-30 Thread Marco Rompré
Hi im doin a programmin course at university and in one on my exercise i
have to do that

I had to define a class CompteBancaire(CompteBancaire is bankaccount in
french), that would allow me to create objects Compte1, Compte2,etc.

 The following methods need to be defined
  - depot(somme) would allow me to add cash to my account
balance
  - retrait(somme)would allow me to withdraw some cash from my
account
  - ajouterInterest()  would allow me to add interest
  - affiche() would allow me to display the account
owner and his account balance

the retrait(somme) method is not supposed to let the account balance being
negative.



3.2

Create a sub-class to CompteBancaire and name it  CompteEtudiant. Each
CompteEtudiant (student account) should have a $1000CAD credit line. Write a
builder or constructor for this new class. Surcharge the retrait(somme)
method to make sure that the student can withdraw to their limit.
Test the class

Here's my code for now this is 3.1and 3.2 in the same code

Please help me i think im on the right track but i need some guidance in the
dark. lol

Thank you tutors


#Exercice 3,1 - Gestion d'un compte bancaire

class CompteBancaire:
"définition d'un compte bancaire"

def __init__(self,nom,solde,interet):   #Nous allons instancier et
initialiser les objets à la classe
self.nom, self.solde, self.interet = nom,solde,interet

def depot(self,somme=0):#Définition des fonctions
self.solde=self.solde+somme #Pour additionner les dépôts
au compte

def retrait(self,somme=0):  #Pour soustraire les dépôts
au compte
if self.solde-somme<0:
print "Les fonds sont insuffisants. Essayez un autre montant
pour votre retrait!"
else:
self.solde=self.solde-somme

def calculInteret(self,calculInteret=0): #Calcul des intérêts et du
solde résiduel
self.interet=self.solde*calculInteret/100
self.solde=(self.solde*calculInteret/100)+self.solde

def affiche_solde(self):
print "Le solde du compte bancaire de %s est de %d $CAD"
%(self.nom,self.solde)
print "Vous avez récolté %d $CDN en intérêt"%(self.interet)
#
##
# création de la gestion d'un compte étudiant autorisant une marge de crédit
de (1 000$)

class CompteEtudiant(CompteBancaire):
"définition du compte bancaire pour étudiant dérivé du compte bancaire
standard"
def __init__(self, nom='Étudiant', solde=200, margeCre = 1000):
#Limite de marge de crédit fixé à 1 000$
CompteBancaire.__init__(self, nom='Sandon', solde=800, interet=0)
self.nom, self.solde, self.margeCre = nom, solde, margeCre

def margeCre (self, somme=0):
if somme-self.solde>margeCre:
print "Désolé vous dépassez la marge de crédit autorisé"
else:
self.solde = (self.solde-somme)
margeCre=margeCre+self.solde


def affiche_solde(self, somme=0):
print "Le solde du compte bancaire de %s est de %d $CAD"
%(self.nom,self.solde)
print "Le solde de votre marge de crédit est de %d $CAD"
%(self.margeCre)
print "Vous avez récolté %d $CDN en intérêt"%(self.interet)

##
#jeux d'essai avec des valeurs fictives
if __name__=='__main__':#Référence au corps principal du programme.
compte1 = CompteBancaire('Sandon',800,0)
compte1.depot(0)
compte1.retrait(1200)
compte1.calculInteret(10)
compte1.affiche_solde()
compte2 = CompteEtudiant('Étudiant', 800)
compte2.retrait(900)
compte2.affiche_solde()
##



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


Re: [Tutor] Simple bank account oriented object

2010-04-05 Thread Marco Rompré
Hi im doin a programmin course at university and in one on my exercise i
have to do that

I had to define a class CompteBancaire(CompteBancaire is bankaccount in
french), that would allow me to create objects Compte1, Compte2,etc.

 The following methods need to be defined
  - depot(somme) would allow me to add cash to my account
balance
  - retrait(somme)would allow me to withdraw some cash from my
account
  - ajouterInterest()  would allow me to add interest
  - affiche() would allow me to display the account
owner and his account balance

the retrait(somme) method is not supposed to let the account balance being
negative.



3.2

Create a sub-class to CompteBancaire and name it  CompteEtudiant. Each
CompteEtudiant (student account) should have a $1000CAD credit line. Write a
builder or constructor for this new class. Surcharge the retrait(somme)
method to make sure that the student can withdraw to their limit.
Test the class

Here's my code for now this is 3.1and 3.2 in the same code

Please help me i think im on the right track but i need some guidance in the
dark. lol

Thank you tutors


#Exercice 3,2 - Gestion d'un compte bancaire pour étudiant avec marge de
crédit disponible de 1000$CDN

class CompteBancaire:
"définition d'un compte bancaire"

def __init__(self,nom,solde,interet):   #Nous allons instancier et
initialiser les objets à la classe
self.nom, self.solde, self.interet = nom,solde,interet

def depot(self,somme=0):#Méthode pour additionner
les dépôts au compte
self.solde=self.solde+somme

def retrait(self,somme=0):  #Méthode pour soustraire les
retraits au compte
if self.nom == 'Sandon':
if self.solde-somme<0:
print "Les fonds sont insuffisants. Essayez un autre montant
pour votre retrait!"
else:
self.solde=self.solde-somme

elif self.nom =='Étudiant': #Vérifie s'il s'agit d'un
compte étudiant
if self.solde - somme < -self.margeCre:  # Vérifie si le
retrait dépasse la marge de crédit maximum
print "Désolé, votre retrait dépasse la marge de crédit
autorisé"
else:   # sinon déuit le montant
retirer de la marge de crédit
self.margeCre = self.solde - somme
self.solde = 0

def calculInteret(self,calculInteret=0): #Méthode qui calcule les
intérêts et le solde résiduel
self.interet=self.solde*calculInteret/100
self.solde=(self.solde*calculInteret/100)+self.solde

def affiche_solde(self):#Méthode qui affiche le
solde et le montant d'intérêt accumulé
print "Le solde du compte bancaire de %s est de %d $CAD"
%(self.nom,self.solde)
print "Vous avez récolté %d $CDN en intérêt"%(self.interet)
#
##
# création de la gestion d'un compte étudiant autorisant une marge de crédit
de (1 000$)

class CompteEtudiant(CompteBancaire):
"définition du compte bancaire pour étudiant dérivé du compte bancaire
standard"
def __init__(self, nom='', solde=0, margeCre=0):
CompteBancaire.__init__(self, nom='Nom', solde=0, interet=0)
self.nom, self.solde, self.margeCre = nom, solde, margeCre

def affiche_solde(self, somme=0):   #Méthode constructeur qui
redéfini la fonction affiche_solde pour le compte étudiant
print "%s--Votre solde bancaire est de %d $CAD"
%(self.nom,self.solde)
print "Le solde de votre marge de crédit est de %d $CAD"
%(self.margeCre)

##
#jeux d'essai avec des valeurs fictives
if __name__=='__main__':#Référence au corps principal du programme.
compte1 = CompteBancaire('Sandon',800,0)#Essai avec un solde de
800$, un retrait de 1200$ et des intérêts de 10%
compte1.depot(0)
compte1.retrait(1200)
compte1.calculInteret(10)
compte1.affiche_solde()
compte2 = CompteEtudiant('Étudiant',800,1000)
compte2.retrait(1100)
compte2.affiche_solde()



On Wed, Mar 31, 2010 at 4:39 PM, Lie Ryan  wrote:

On 04/01/2010 12:35 AM, Marco Rompré wrote:
> > what's wrong in this code??? if I want it to do what i describe in my
> > message.
>
> What happens when you run it? You did not even write that in your
> message. And please reply-all to the list.
>

When I run it,  it gives me this:

>>>
Les fonds sont insuffisants. Essayez un autre montant pour votre retrait!
(Try to witthdraw 1200 with a balance of 880$) This is good!
Le solde du compte bancaire de Sandon est de 880 $CAD (This is fine t

[Tutor] Need some info

2010-04-20 Thread Marco Rompré
Hi! in my programming course at university, I need to create a python model
with 2 concepts in a one towards many relation  each of them  having 2-3
properties.

Also, I need to create an application with screens to add, modify, and
delete the data of the model.

Can someone know where I can find the information that would help me to
successfully complete my assignment

Thank You!!!

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


[Tutor] Would you please help me understand my error

2010-04-23 Thread Marco Rompré
Its supposed to be a object magasin (shop in french) with some golf items in
it


 class Magasin:
"""
Le concept magasin pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", items =[] ):
self.nom = nom
self.items = items

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_items(self, items):
self.items = items

items = property(None, set_items)

def __str__(self):
return self.nom

class Item:
"""
Le concept item pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", prix =""):
self.nom = nom
self.prix = prix

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_prix(self, prix):
self.prix = prix

prix = property(None, set_prix)

def __str__(self):
return self.nom

class Modele:
"""
La definition d'un modele avec les magasins.
"""
def __init__(self, magasins =[]):
self.magasins = magasins

def set_magasins(self, magasins):
self.magasins = magasins

magasins = property(None, set_magasins)

def vide(self):
if self.magasins == []:
return True
else:
return False

def initialiser(self):
magasin01 = Magasin ("Swing de golf")

item01 = Item ("Ensemble de fers Titleist")
item01.set_prix("999.99")

item02 = Item ("Ensemble de fers Callaway")

items = [item01, item02]
magasin01.set_items(items)

def afficher(self):
print("")
print("Magasins")
for magasin in self.magasins:
print("")
print(magasin)
for tache in magasin.items:
print(item)
self.set_magasins([magasin01])



if __name__ == '__main__':
modele = Modele()
#modele.charger()
if modele.vide():
modele.initialiser()
modele.afficher()

My error is:

Magasins

Traceback (most recent call last):
  File "F:\School\University\Session 4\Programmation SIO\Golftmodele.py",
line 102, in 
modele.afficher()
  File "F:\School\University\Session 4\Programmation SIO\Golftmodele.py",
line 93, in afficher
self.set_magasins([magasin01])
NameError: global name 'magasin01' is not defined

Thank you
-- 
Marc-O. Rompré
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Would you please help me understand my error

2010-04-23 Thread Marco Rompré
Bien,

>for starters please get rid of all those set_ methods. They are
> doing nothing, it's not pythonic. Just assign the value straight away.
> e.g.: from """ item01.set_prix("999.99") """  to """ item01.prix =

"999.99" """
>

Our teacher showed us this method and in our exercise we had to copy the
teacher's code and modify the data to fit our concept

But thks I found my error but what did you say about th decimal module
we have to keep in mind that my exercise is for an introductory course
in python I am not good, I am  trying to learn at my best.

Here's my new code( can you please tell me if it is okay)

class Magasin:
"""
Le concept magasin pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", items =[] ):
self.nom = nom
self.items = items

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_items(self, items):
self.items = items

items = property(None, set_items)

def __str__(self):
return self.nom

class Item:
"""
Le concept item pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", prix =""):
self.nom = nom
self.prix = prix

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_prix(self, prix):
self.prix = prix

prix = property(None, set_prix)

def __str__(self):
return self.nom

class Modele:
"""
La definition d'un modele avec les magasins.
"""
def __init__(self, magasins =[]):
self.magasins = magasins

def set_magasins(self, magasins):
self.magasins = magasins

magasins = property(None, set_magasins)


def sauvegarder(self,nom_fichier):
modele_fichier = open(nom_fichier, 'w')
for magasin in self.magasins:
modele_fichier.write("===MAGASIN==="  + "\n")
modele_fichier.write("nom : " + magasin.nom + "\n")
modele_fichier.write("items : " + "\n")
for item in magasin.items:
modele_fichier.write("---ITEM---"  + "\n")
modele_fichier.write("nom : " + item.nom + "\n")
modele_fichier.write("prix : " + item.prix + "\n")
modele_fichier.write("---FIN ITEM---"  + "\n")
modele_fichier.write("===FIN MAGASIN==="  + "\n")
modele_fichier.close()

def charger(self, nom_fichier):
magasins = []
try:
modele_fichier = open(nom_fichier, 'r')
except IOError:
print("Le fichier " + nom_fichier + " n'existe pas.")
else:
fin_fichier = False
while not fin_fichier:
ligne = modele_fichier.readline()
if ligne == "":
self.set_magasins(magasins)
modele_fichier.close()
fin_fichier = True
break
magasin = Magasin()
items = []
fin_magasin = False
while not fin_magasin:
ligne = modele_fichier.readline().strip()
if ligne.startswith("===FIN MAGASIN==="):
magasin.set_items(items)
magasins.append(magasin)
fin_magasin = True
elif ligne.startswith("nom"):
nom = ligne.split(':')[1]
magasin.set_nom(nom.strip())
elif ligne.startswith("---ITEM---"):
item = Item()
fin_item = False
while not fin_item:
ligne = modele_fichier.readline().strip()
if ligne.startswith("nom"):
nom = ligne.split(':')[1]
item.set_nom(nom.strip())
elif ligne.startswith("prix"):
prix = ligne.split(':')[1]
item.set_prix(prix.strip())
elif ligne.startswith("---FIN ITEM---"):
items.append(item)
fin_item = True




def vide(self):
if self.magasins == []:
return True
else:
return False

def initialiser(self, nom_fichier):
magasin01 = Magasin ("Swing de golf")

item01 = Item ("Ensemble de fers Titleist")
item01.set_prix("999.99")

item02 = Item ("Ensemble de fers Callaway")

items = [item01, item02]
magasin01.set_items(items)

self.set_magasins([magasin01])

self.sauvegarder(nom_fichier)

def afficher(self):
print("")
print("Magasins")
for magasin in self.magasins:
print("")
print(magasin)
for item in magasin.items:

[Tutor] Hi everybody stuck on some error need help please thank you!!

2010-04-23 Thread Marco Rompré
Hi everybody, I would appreciate your help on this one
In this program I want to create 2 concepts each with 2 or 3 properties
My first concept is magasin(shop in french) and my shop has 3 attributes:
nom(name in french), items and ville (city in french)
the second one is items and its 2 attributes are nom(name in french) and
prix (price in french)
I want to be able to show a modele with the name of my magasins (stores) and
the city theyre located in, what are the names of the items i have in each
magasin and their prices.

Here's my code:

class Magasin:
"""
Le concept magasin pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", items =[], ville="" ):
self.nom = nom
self.items = items
self.vile = ville

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_items(self, items):
self.items = items

items = property(None, set_items)

def set_ville(self, ville):
self.ville = ville

items = property(None, set_ville)

def __str__(self):
return self.nom

class Item:
"""
Le concept item pour la gestion d'inventaire des items de golf.
"""
def __init__(self, nom ="", prix = 100):
self.nom = nom
self.prix = prix

def set_nom(self, nom):
self.nom = nom

nom = property(None, set_nom)

def set_prix(self, prix):
self.prix = prix

prix = property(None, set_prix)

def __str__(self):
return self.nom

class Modele:
"""
La definition d'un modele avec les magasins.
"""
def __init__(self, nom_fichier, magasins =[]):
self.nom_fichier = nom_fichier
self.magasins = magasins

def set_nom_fichier(self, nom_fichier):
self.nom_fichier = nom_fichier

nom_fichier = property(None, set_nom_fichier)

def set_magasins(self, magasins):
self.magasins = magasins

magasins = property(None, set_magasins)

def sauvegarder(self):
modele_fichier = open(self.nom_fichier, 'w')
for magasin in self.magasins:
modele_fichier.write("===MAGASIN==="  + "\n")
modele_fichier.write("nom : " + magasin.nom + "\n")
modele_fichier.write("items : " + "\n")
for item in magasin.items:
modele_fichier.write("---ITEM---"  + "\n")
modele_fichier.write("nom : " + item.nom + "\n")
modele_fichier.write("prix : " + item.prix + "\n")
modele_fichier.write("---FIN ITEM---"  + "\n")
modele_fichier.write("===FIN MAGASIN==="  + "\n")
modele_fichier.close()

def charger(self):
magasins = []
try:
modele_fichier = open(self.nom_fichier, 'r')
except IOError:
print("Le fichier " + self.nom_fichier + " n'existe pas.")
else:
fin_fichier = False
while not fin_fichier:
ligne = modele_fichier.readline()
if ligne == "":
self.set_magasins(magasins)
modele_fichier.close()
fin_fichier = True
break
magasin = Magasin()
items = []
fin_magasin = False
while not fin_magasin:
ligne = modele_fichier.readline().strip()
if ligne.startswith("===FIN MAGASIN==="):
magasin.set_items(items)
magasins.append(magasin)
fin_magasin = True
elif ligne.startswith("nom"):
nom = ligne.split(':')[1]
magasin.set_nom(nom.strip())
elif ligne.startswith("---ITEM---"):
item = Item()
fin_item = False
while not fin_item:
ligne = modele_fichier.readline().strip()
if ligne.startswith("nom"):
nom = ligne.split(':')[1]
item.set_nom(nom.strip())
elif ligne.startswith("prix"):
prix = ligne.split(':')[1]
item.set_prix(float())
elif ligne.startswith("---FIN ITEM---"):
items.append(item)
fin_item = True

def vide(self):
if self.magasins == []:
return True
else:
return False

def initialiser(self):

magasin01 = Magasin ("Swing de golf")

magasin02 = Magasin ("Golftown")

magasin03 = Magasin ("PointGolf")


item01 = Item ("Ensemble de fers Titleist")
item01.set_prix("1099.99")

item02 = Item ("Ensemble de fers Callaway")
item02.set_prix("1299.99")

item03 

Re: [Tutor] Hi everybody stuck on some error need help please thank you!!

2010-04-23 Thread Marco Rompré
I tried to enter model = Modele (nom_fichier) but it still does not work.
And for the list I don't understand very well, Do you know where I can pay
someone to help with my programming.
Because I feel to annoy tutors with my basic stuff

On Fri, Apr 23, 2010 at 11:22 PM, Steven D'Aprano wrote:

> On Sat, 24 Apr 2010 01:07:11 pm Marco Rompré wrote:
>
> > Here's my code:
> [...]
> > class Modele:
> > """
> > La definition d'un modele avec les magasins.
> > """
> > def __init__(self, nom_fichier, magasins =[]):
> > self.nom_fichier = nom_fichier
> > self.magasins = magasins
> [...]
> > if __name__ == '__main__':
> > modele = Modele()
> > nom_fichier = "magasinmodele.txt"
> > modele.charger(nom_fichier)
> > if modele.vide():
> > modele.initialiser(nom_fichier)
> > modele.afficher()
> >
> > And here's my error :
> >
> > Traceback (most recent call last):
> >   File "F:\School\University\Session 4\Programmation
> > SIO\magasingolfmodele.py", line 187, in 
> > modele = Modele()
> > TypeError: __init__() takes at least 2 arguments (1 given)
>
>
> You define Modele to require a nom_fichier argument, but then you try to
> call it with no nom_fuchier.
>
>
> Also, I see that you do this:
>
> def __init__(self, nom_fichier, magasins =[]):
>
> You probably shouldn't do this -- it doesn't do what you probably think
> it does.
>
> You probably think that what happens is that if you call
> Modele(nom_fichier), the magasins attribute will be set to an empty
> list. But that's not what happens.
>
> Default values in Python are defined when the method is created, not
> when it is run. Watch this example:
>
> >>> class Test:
> ... def __init__(self, x=[]):
> ... self.x = x
> ...
> >>> a = Test()
> >>> a.x
> []
> >>> b = Test()
> >>> b.x
> []
> >>>
> >>> a.x.append("Surprise!")
> >>> b.x
> ['Surprise!']
>
>
> How does this happen? Because every instance shares the same default
> list. When you append to it, all the other instances see the same
> change.
>
> You don't notice this with default values that are strings or numbers,
> because you can't modify them, only replace them:
>
> >>> x = y = 2  # Make two variables that point to the same value.
> >>> x is y  # Make sure they are identical, not just equal.
> True
> >>> x = 3  # Make x point to something else.
> >>> x is y  # And no longer identical.
> False
> >>>
> >>> x = y = []  # Make two variables that point to the same thing.
> >>> x is y
> True
> >>> x.append('something')  # Modify that list in place.
> >>> x is y  # Still identical.
> True
> >>> y
> ['something']
>
>
> If this is the behaviour you want, then you don't need to do anything.
> Otherwise you need to move the creation of the empty list inside the
> method:
>
>def __init__(self, nom_fichier, magasins=None):
>if magasins is None:
> magasins = []
>self.nom_fichier = nom_fichier
>self.magasins = magasins
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


[Tutor] How can I display my float as a string???

2010-04-27 Thread Marco Rompré
Here is my code, I need to display my float value as a string.

item.set_prix str(float(prix))

Thank You
-- 
Marc-O. Rompré
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject)

2010-04-27 Thread Marco Rompré
Oups my posting was too big!!!

On Tue, Apr 27, 2010 at 11:04 PM, Marco Rompré wrote:

> Why is none of my items button works In this, I have two files and in
> my second file I imported all the function of the first one
>
> Here is my codes and my error code  for the two files please help me:
> Traceback (most recent call last):
>
>
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 426, in 
> app = App(racine, "magasinmodele.txt")
>   File "F:\School\University\Session 4\Programmation
> SIO\magasingolfvues.py", line 23, in __init__
> ItemsFrame(contexte, item)
> NameError: global name 'item' is not defined
> >>>
>
>
>  1st fil called magasingolfmodele.py:
>
> # -*- coding: utf-8 -*-
> #
> # magasingolfmodele.py
> #
> # Magasin de golf --< Items de golf
> # Magasin de golf (nom, items, ville)
> # Items de golf(nom, prix)
> #
> # naming standards: http://www.python.org/dev/peps/pep-0008/
> #
>
>
> class Magasin:
> """
> Le concept magasin pour la gestion d'inventaire des items de golf.
> """
> def __init__(self, nom ="", items =[], ville="" ):
> self.nom = nom
> self.items = items
> self.ville = ville
>
> def set_nom(self, nom):
> self.nom = nom
>
> nom = property(None, set_nom)
>
> def set_items(self, items):
> self.items = items
>
> items = property(None, set_items)
>
> def set_ville(self, ville):
> self.ville = ville
>
> ville = property(None, set_ville)
>
> def __str__(self):
> return self.nom
>
> class Item:
> """
> Le concept item pour la gestion d'inventaire des items de golf.
> """
> def __init__(self, nom ="", prix = 100):
> self.nom = nom
> self.prix = prix
>
>
> def set_nom(self, nom):
> self.nom = nom
>
> nom = property(None, set_nom)
>
> def set_prix(self, prix):
> self.prix = prix
>
> prix = property(None, set_prix)
>
> def __str__(self):
> return self.nom
>
>
>
> def initialiser(self):
>
>
> item01 = Item ("Ensemble de fers Titleist")
> item01.set_prix("1099.99")
>
> item02 = Item ("Ensemble de fers Callaway")
> item02.set_prix("1299.99")
>
> item03 = Item ("Ensemble de fers Taylormade Burner Graphite")
> item03.set_prix("2499.99")
>
> item04 = Item ("Ensemble de fers Cobra")
> item04.set_prix("999.99")
>
> item05 = Item ("Ensemble de fers Ping")
> item05.set_prix("1399.99")
>
> item06 = Item ("Ensemble de fers Ben Hogan")
> item06.set_prix("1199.99")
>
> items = [item01, item02, item03, item04, item05, item06]
> magasin01.set_items(items)
>
> items = [item01, item03, item04, item06]
> magasin02.set_items(items)
>
> items = [item01, item02, item03, item05]
> magasin03.set_items(items)
>
> magasins = [magasin01,
> magasin02,
> magasin03]
>
> self.set_magasins(magasins)
>
> self.sauvegarder()
>
> def afficher(self):
> print("")
> print("Magasins")
> for magasin in self.magasins:
> print("")
> print(magasin)
> print("")
> for item in magasin.items:
> print(item)
> for prix in item.prix:
> print(prix)
>
>
> if __name__ == '__main__':
> modele = Modele("magasinmodele.txt")
> modele.charger()
> if modele.vide():
> modele.initialiser()
> modele.afficher()
>
>
> Here's the code of my second file:
>
> # -*- coding: utf-8 -*-
> #
> # magasingolfvues.py
> #
> # naming standards: http://www.python.org/dev/peps/pep-0008/
> #
>
> from Tkinter import *
>
> from magasingolfmodele import *
>
> class App:
> """
> Application illustrant le concept d'un magasin de golf et des items
> qu'il vend.
> """
> def __init__(self, contexte, nom_fichier):
> self.contexte = contexte
> self.modele = Modele(nom_fichier)
> self.modele

Re: [Tutor] Looking for HOWTO's

2005-06-02 Thread Marco Scheidhuber
hi joseph,

Joseph Quigley wrote:
> PS> I wouldn't mind /any/ Python HOWTO or tutorial
google is your friend ;-)

Your first tutorial should be http://python.org/doc/2.4.1/tut/tut.html
or maybe http://honors.montana.edu/~jjc/easytut/easytut/

and a search for "image reader" python gives e.g.
http://sourceforge.net/projects/pdsimagereader/

hth
marco

-- 
marco scheidhuber-
internetmanufaktur jo- Berlin, Germany
   |||meder---fon: ++49-30-417 17 63 34
http://www.meder.de/ --- fax: ++49-30-417 17 63 45
Kollwitzstr. 75  mob: ++49-172- 3 22 07 83
10435 Berlin -
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] SMTP Module Help

2009-01-07 Thread Marco Petersen
I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to 
send an email through my Gmail account but it keeps saying that the 
connection was refused.


This is the code that I used :

import smtplib
msg = 'Test'


server = smtplib.SMTP('smtp.gmail.com')
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login('marco.m.peter...@gmail.com', 'password')
server.sendmail('marco.m.peter...@gmail.com', 
'marcoleepeter...@gmail.com', msg)

server.close()

This error message keeps coming up:


Traceback (most recent call last):
 File "C:/Python25/send_mail.py", line 5, in 
   server = smtplib.SMTP('smtp.gmail.com')
 File "C:\Python25\Lib\smtplib.py", line 244, in __init__
   (code, msg) = self.connect(host, port)
 File "C:\Python25\Lib\smtplib.py", line 310, in connect
   raise socket.error, msg
error: (10061, 'Connection refused')


Can anyone help me with this?

Thanks.

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


[Tutor] 2to3 Help?

2009-01-11 Thread Marco Petersen
I have Python 3.0. I tried to use the 2to3 program included with the 
interpreter to convert some scripts for Python 2.5 to Python 3.0 ones.
When I try to start it form the Python command line, it says it is a 
syntax error.


This was the line of code:

$ 2to3 testscript.py

Any help would be appreciated.

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


[Tutor] Is there a better way?

2012-01-11 Thread Marco Casazza

Hello,

I've been slowly teaching myself python, using it for small projects 
when it seems appropriate. In this case, I was handed a list of email 
addresses for a mailing but some of them had been truncated. There are 
only 21 possible email "suffixes" so I planned to just identify which it 
should be and then replace it. However, when I started writing the code 
I realized that I'd be doing a lot of "repeating". Is there a better way 
to "fix" the suffixes without doing each individually? Here's my working 
code (for 4 colleges):


import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
outlist = []
for line in infile.read().split('\n'):
if line.rstrip().lower().endswith('edu'):
newline = line + '\n'
outlist.append(newline.lower())
elif re.search("@bar", line):
newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@bcc", line):
newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@bmc", line):
newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@leh", line):
newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
outfile.writelines(outlist)

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


Re: [Tutor] Is there a better way?

2012-01-11 Thread Marco Casazza

On 2012-01-11 07:57, Joel Goldstick wrote:

On Wed, Jan 11, 2012 at 7:34 AM, Marco Casazza  wrote:

Hello,

I've been slowly teaching myself python, using it for small projects when it
seems appropriate. In this case, I was handed a list of email addresses for
a mailing but some of them had been truncated. There are only 21 possible
email "suffixes" so I planned to just identify which it should be and then
replace it. However, when I started writing the code I realized that I'd be
doing a lot of "repeating". Is there a better way to "fix" the suffixes
without doing each individually? Here's my working code (for 4 colleges):

import re
with file('c:\python27\mvc\mailing_list.txt', 'r') as infile:
outlist = []
for line in infile.read().split('\n'):
if line.rstrip().lower().endswith('edu'):
newline = line + '\n'
outlist.append(newline.lower())
elif re.search("@bar", line):
newline = re.sub("@bar.*", "@baruch.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@bcc", line):
newline = re.sub("@bcc.*", "@bcc.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@bmc", line):
newline = re.sub("@bmc.*", "@bmcc.cuny.edu", line)+'\n'
outlist.append(newline.lower())
elif re.search("@leh", line):
newline = re.sub("@leh.*", "@lehman.cuny.edu", line)+'\n'
outlist.append(newline.lower())

with file('c:\python27\mvc\output.txt','w') as outfile:
outfile.writelines(outlist)

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

First, look here about reading files:
http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

I like this better:
 f = open('filename', 'r')
 for line in f:
 print line # this will give you one line at a time without
the trailing newline

Second, make a dictionary of with the key being what comes after the @
in your truncated file.  The value will be the complete text you want:
  d = {"bcc" : "bcc.cuny.edu", etc. }

Third, use line.split('@') to split the line into what comes before
and after the @ sign.  It will return a list
 address_parts = line.split('@')

address_parts[0] is what you want to keep as is. I'm guessing that the
3 characters after the @ will be enough to identify what the full
address should look like, so
if address_parts[1][0:3] in d:
   result = '@'.join([address_parts[0], d[address_parts[1][0:3]])

write the result to your out file.

Its early in the morning for me, and this is untested, but it might
give you some ideas.


Hi Joel,

Thanks. I like the dictionary idea... I hadn't thought of that because I 
was trying to fix one "problem" and then realized I had more, and then 
yet more, so it just kept growing--a case of not seeing the forest for 
the trees. And, if I split the address at the amphora I wouldn't need to 
worry about where exactly it was truncated, so no regular expressions to 
gather up the remaining characters after the key.


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


[Tutor] VirutalEnv not working on Ubuntu server 9.10

2012-04-29 Thread Marco Mistroni
HI all
 i have a VPS which is running Ubuntu server 9.10

i have downloaded virtualenv 1.4.2 and installed it in a tmp directory

i have created a environment for using googlemaps..

i am able to download googlemaps package,  but when i activate the
environment , run python  and type  import googlemaps
i receive the following error

ImportError: no module caleld googlemaps


..BUt i have just imported it using pip install. here's output of doing pip
install googlemaps

Downloadign googlemaps-1.0.2
...

Running setup.py install for googlemaps
Successfully installed googlemaps

yet, when i type pytyon  and start to import googlemaps all i receive is an
error that the package does not exist

what am i missing?

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


Re: [Tutor] VirutalEnv not working on Ubuntu server 9.10 / sorted

2012-04-29 Thread Marco Mistroni
Hello
  sorry to bother , found out hte problem. the imported packages work if i
run python from the /bin directory of the virtualenv  environment i have
created

w/kindest regards
 marco

On Sun, Apr 29, 2012 at 3:04 PM, Marco Mistroni  wrote:

> HI all
>  i have a VPS which is running Ubuntu server 9.10
>
> i have downloaded virtualenv 1.4.2 and installed it in a tmp directory
>
> i have created a environment for using googlemaps..
>
> i am able to download googlemaps package,  but when i activate the
> environment , run python  and type  import googlemaps
> i receive the following error
>
> ImportError: no module caleld googlemaps
>
>
> ..BUt i have just imported it using pip install. here's output of doing
> pip install googlemaps
>
> Downloadign googlemaps-1.0.2
> ...
>
> Running setup.py install for googlemaps
> Successfully installed googlemaps
>
> yet, when i type pytyon  and start to import googlemaps all i receive is
> an error that the package does not exist
>
> what am i missing?
>
> w/kindest regards
>  marco
>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] NTLM authentication

2012-08-23 Thread Marco Mistroni
Hi all
 i was wondering if anyone coud provide examples on how to  open an URL
that requires  NTLM authentication

i have tried to use python-ntml but it does not seems to work as i keep on
getting  this error

lib\python2.6\ntlm\ntlm.py", line 219, in parse_NTLM_CHALLENGE_MESSAGE
error: unpack requires a string argument of length 4

could anyone assist pls?

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


[Tutor] NTLM authentication, python 2.6 and windows

2012-08-23 Thread Marco Mistroni
Hi all
 i was wondering if anyone coud provide examples on how to  open an URL
that requires  NTLM authentication
i have tried to use python-ntml but it does not seems to work as i keep on
getting  this errorlib\python2.6\ntlm\ntlm.py", line 219, in
parse_NTLM_CHALLENGE_MESSAGEerror: unpack requires a string argument of
length 4

I am running the client code on python 2.6, on a windows 7 machine, and i
am connecting to an apache tomcat server running on a windows xp machine


could anyone assist pls?

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


[Tutor] Segmentation Fault shenanigans with wx Gui

2012-10-19 Thread Marco Mistroni
Hi all
 i have written a wx GUI which downloads json data from a server, and
populate a listbox.
Every time i populate a listbox, i am receiving Segmentation Faults.
I have tried to retrieve data from the URL via separate thread, and to use
events, but i am still getting a segmentation fault

could anyone assist pls?

here's relevant code. I m running python on Ubuntu 10.04

class WxSharesGUI(wx.Frame):


def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(300, 300))
self.InitUI()

def InitUI(self):
self.load_button = wx.Button(self, wx.ID_ANY, "load ListBox")
self.clear_button = wx.Button(self, wx.ID_ANY, "clear ListBox")
self.load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick)
self.clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick)
self.Bind(EVT_RESULT, self.OnResult)
self.lock = threading.RLock()

# Creating Menu bar
menubar = wx.MenuBar()
newsMenu = wx.Menu()
newsMenu.Append(ID_EDGAR, 'Edgar News', 'Edgar news')
newsMenu.Append(ID_GLOBAL, 'Global Economy', 'Global economy')
newsMenu.Append(ID_ECONOMY, 'Economy Data', 'Economy data')
newsMenu.Append(ID_FX, 'FX', 'Fx data')
futuresItem = newsMenu.Append(ID_FUTURES, 'FUTURES', 'FUTURES')
exitItem = newsMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
menubar.Append(newsMenu, '&News')

mgmtMenu = wx.Menu()
shareMgmtItem = mgmtMenu.Append(ID_UPDATE_SHARE, 'Share Management',
'Share Management')
ptfMgmtItem = mgmtMenu.Append(ID_UPDATE_PORTFOLIO, 'Portfolio
Management', 'Portfolio Mgmt')
resetItem = mgmtMenu.Append(ID_RESET, 'Reset Listbox', 'Portfolio Mgmt')
menubar.Append(mgmtMenu, '&Management')


self.SetMenuBar(menubar)

self.Bind(wx.EVT_MENU, self.OnQuit, exitItem)
self.Bind(wx.EVT_MENU, self.OnFutures, futuresItem)
self.Bind(wx.EVT_MENU, self.OnShareMgmt, shareMgmtItem)
self.Bind(wx.EVT_MENU, self.OnPtfMgmt, ptfMgmtItem)

self.listBox1 = wx.ListBox(self, wx.ID_ANY, choices=[],
style=wx.LB_EXTENDED)
self.listBox1.Append('MAIN')
self.listBox1.Append('INDEXES')
self.listBox1.Append('CURRENCIES')
self.listBox1.Append('HEDGE')
self.listBox1.Append('CDS SPREADS')
self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox,
id=ID_FRAME1LISTBOX1)
self.Bind(wx.EVT_MENU, self.OnResetList, resetItem)

hbox = wx.BoxSizer(wx.HORIZONTAL)

panel = wx.Panel(self, -1)

self.list = AutoWidthListCtrl(panel)
self.list.InsertColumn(0, 'Ticker')#, width=150)
self.list.InsertColumn(1, 'Name')#', width=100)
self.list.InsertColumn(2, 'MovingAvg200')#', width=100)
self.list.InsertColumn(3, 'MovingAvg50')#', width=100)
self.list.InsertColumn(4, 'Price')#, width=80)
self.list.InsertColumn(5, 'Previous')#, width=80)
self.list.InsertColumn(6, 'Change')#, width=80)
self.list.InsertColumn(7, 'TotalValue')#, width=80)
self.list.InsertColumn(8, 'Position')#', width=100)

hbox.Add(self.list, 2, wx.EXPAND)
panel.SetSizer(hbox)


self.SetSize((900, 500))
self.SetTitle('Camel App Python Gui')
self.Centre()

sizer = wx.GridBagSizer(vgap=8, hgap=10)
# pos=(row, column)  span=(rowspan, columnspan)
# wx.ALL puts the specified border on all sides
sizer.Add(self.load_button, pos=(0, 0), flag=wx.ALL, border=5)
# listbox spans 6 rows and 2 columns
sizer.Add(self.clear_button, pos=(0, 25), flag=wx.ALL, border=5)


sizer.Add(self.listBox1, pos=(2, 4), span=(8, 8),
flag=wx.ALL|wx.EXPAND, border=5)

sizer.Add(panel, pos=(10,1),span=(10, 30),
flag=wx.ALL|wx.EXPAND, border=5)
self.SetSizer(sizer)
#self.Fit()

self.Show(True)

def OnQuit(self, e):
self.Close()

def OnResult(self, event):
print 'onResult'
ptf_data = event.data
for item in ptf_data['portfolio']['items']:
index = self.list.InsertStringItem(sys.maxint, item['ticker'])
self.list.SetStringItem(index, 1, item['name'])
self.list.SetStringItem(index, 2, str(item['movingAvg200']))
self.list.SetStringItem(index, 3, str(item['movingAvg50']))
self.list.SetStringItem(index, 4, str(item['price']))
self.list.SetStringItem(index, 5, str(item['previous']))
self.list.SetStringItem(index, 6, str(item['price'] -
item['previous']) )
self.list.SetStringItem(index, 7, str(item['totalValue']))
self.list.SetStringItem(index, 8, str(item['position']))



def load_buttonClick(self,e):
idx = self.listBox1.GetSelections()[0]

ptf = self.listBox1.GetStrings()[idx]

thread.start_new_thread(self.fetch, (ptf,))
self.list.ClearAll()

def fetch(self, ptf):
data= {'action':'portfolio', 'portfolioName':ptf}
ptf_data = jsonLoader.openJsonRequest(data)
print ptf_data['portfolio']['cash']
  

Re: [Tutor] Segmentation Fault shenanigans with wx Gui

2012-10-19 Thread Marco Mistroni
Hello
 i found the problem. It's  calling self.list.ClearAll that causes the
segmentation fault.
removing the call to  ClearAll fixed my problem , but i still want to clear
the list before i  load new data..
could anyone assist?

wkr
 marco

On Fri, Oct 19, 2012 at 11:05 PM, Marco Mistroni wrote:

> Hi all
>  i have written a wx GUI which downloads json data from a server, and
> populate a listbox.
> Every time i populate a listbox, i am receiving Segmentation Faults.
> I have tried to retrieve data from the URL via separate thread, and to use
> events, but i am still getting a segmentation fault
>
> could anyone assist pls?
>
> here's relevant code. I m running python on Ubuntu 10.04
>
> class WxSharesGUI(wx.Frame):
>
>
> def __init__(self, parent, id, title):
> wx.Frame.__init__(self, parent, id, title, size=(300, 300))
> self.InitUI()
>
> def InitUI(self):
> self.load_button = wx.Button(self, wx.ID_ANY, "load ListBox")
> self.clear_button = wx.Button(self, wx.ID_ANY, "clear ListBox")
> self.load_button.Bind(wx.EVT_BUTTON, self.load_buttonClick)
> self.clear_button.Bind(wx.EVT_BUTTON, self.clear_buttonClick)
> self.Bind(EVT_RESULT, self.OnResult)
> self.lock = threading.RLock()
>
> # Creating Menu bar
> menubar = wx.MenuBar()
> newsMenu = wx.Menu()
> newsMenu.Append(ID_EDGAR, 'Edgar News', 'Edgar news')
> newsMenu.Append(ID_GLOBAL, 'Global Economy', 'Global economy')
> newsMenu.Append(ID_ECONOMY, 'Economy Data', 'Economy data')
> newsMenu.Append(ID_FX, 'FX', 'Fx data')
> futuresItem = newsMenu.Append(ID_FUTURES, 'FUTURES', 'FUTURES')
> exitItem = newsMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
> menubar.Append(newsMenu, '&News')
>
> mgmtMenu = wx.Menu()
> shareMgmtItem = mgmtMenu.Append(ID_UPDATE_SHARE, 'Share Management',
> 'Share Management')
> ptfMgmtItem = mgmtMenu.Append(ID_UPDATE_PORTFOLIO, 'Portfolio
> Management', 'Portfolio Mgmt')
> resetItem = mgmtMenu.Append(ID_RESET, 'Reset Listbox', 'Portfolio
> Mgmt')
> menubar.Append(mgmtMenu, '&Management')
>
>
> self.SetMenuBar(menubar)
>
> self.Bind(wx.EVT_MENU, self.OnQuit, exitItem)
> self.Bind(wx.EVT_MENU, self.OnFutures, futuresItem)
> self.Bind(wx.EVT_MENU, self.OnShareMgmt, shareMgmtItem)
> self.Bind(wx.EVT_MENU, self.OnPtfMgmt, ptfMgmtItem)
>
> self.listBox1 = wx.ListBox(self, wx.ID_ANY, choices=[],
> style=wx.LB_EXTENDED)
> self.listBox1.Append('MAIN')
> self.listBox1.Append('INDEXES')
> self.listBox1.Append('CURRENCIES')
> self.listBox1.Append('HEDGE')
> self.listBox1.Append('CDS SPREADS')
> self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox,
> id=ID_FRAME1LISTBOX1)
> self.Bind(wx.EVT_MENU, self.OnResetList, resetItem)
>
> hbox = wx.BoxSizer(wx.HORIZONTAL)
>
> panel = wx.Panel(self, -1)
>
> self.list = AutoWidthListCtrl(panel)
> self.list.InsertColumn(0, 'Ticker')#, width=150)
> self.list.InsertColumn(1, 'Name')#', width=100)
> self.list.InsertColumn(2, 'MovingAvg200')#', width=100)
> self.list.InsertColumn(3, 'MovingAvg50')#', width=100)
> self.list.InsertColumn(4, 'Price')#, width=80)
> self.list.InsertColumn(5, 'Previous')#, width=80)
> self.list.InsertColumn(6, 'Change')#, width=80)
> self.list.InsertColumn(7, 'TotalValue')#, width=80)
> self.list.InsertColumn(8, 'Position')#', width=100)
>
> hbox.Add(self.list, 2, wx.EXPAND)
> panel.SetSizer(hbox)
>
>
> self.SetSize((900, 500))
> self.SetTitle('Camel App Python Gui')
> self.Centre()
>
> sizer = wx.GridBagSizer(vgap=8, hgap=10)
> # pos=(row, column)  span=(rowspan, columnspan)
> # wx.ALL puts the specified border on all sides
> sizer.Add(self.load_button, pos=(0, 0), flag=wx.ALL, border=5)
> # listbox spans 6 rows and 2 columns
> sizer.Add(self.clear_button, pos=(0, 25), flag=wx.ALL, border=5)
>
>
> sizer.Add(self.listBox1, pos=(2, 4), span=(8, 8),
> flag=wx.ALL|wx.EXPAND, border=5)
>
> sizer.Add(panel, pos=(10,1),span=(10, 30),
> flag=wx.ALL|wx.EXPAND, border=5)
> sel

Re: [Tutor] Segmentation Fault shenanigans with wx Gui

2012-10-22 Thread Marco Mistroni
Hello Ramit
 yes solution worked...

thanks and regards
 marco

On Mon, Oct 22, 2012 at 5:58 PM, Prasad, Ramit wrote:

> Marco Mistroni wrote:
>
> > Hello
> >  i found the problem. It's  calling self.list.ClearAll that causes the
> segmentation fault.
> > removing the call to  ClearAll fixed my problem , but i still want to
> clear the list before i  load new
> > data..
> > could anyone assist?
>
> I think the problem is the way you populate the data. The issue
> with ClearAll is a side effect of that. See below for more information.
>
> >
> > wkr
> >  marco
> > On Fri, Oct 19, 2012 at 11:05 PM, Marco Mistroni 
> wrote:
> > Hi all
> >  i have written a wx GUI which downloads json data from a server, and
> populate a listbox.
> > Every time i populate a listbox, i am receiving Segmentation Faults.
> > I have tried to retrieve data from the URL via separate thread, and to
> use events, but i am still getting a
> > segmentation fault
> >
> > could anyone assist pls?
> >
> > here's relevant code. I m running python on Ubuntu 10.04
> >
> [snip]
> >
> > self.list = AutoWidthListCtrl(panel)'
>
> This mailing list is for learning Python. Support and familiarity
> with 3rd party packages is limited. You will probably be better off
> asking the wxpython mailing list. Especially as the AutoWidthListCtrl
> is not a widget that comes with wxpython.
>
> [snip]
> >
> > def OnResult(self, event):
> > print 'onResult'
> > ptf_data = event.data
> > for item in ptf_data['portfolio']['items']:
> > index = self.list.InsertStringItem(sys.maxint, item['ticker'])
>
> I believe this is the source of your problem. You are using the
> incorrect value as the index. If you look at documentation for
> the base class ListCtrl [0][1] you will notice that the first
> argument to InsertStringItem is the insertion index. Instead you are
> using the same value (sys.maxint) for all items you are inserting.
> sys.maxint represents the maximum integer supported by the system
> and is not relevant for what you are trying to do. Instead use an
> incrementing count.
>
>  rows = self.list.GetItemCount()
>  for index, item in enumerate( ptf_data['portfolio']['items'], rows ):
>  self.list.InsertStringItem(index, item['ticker'])
>
>  [0]: http://wiki.wxpython.org/ListControls
> [1]: http://www.wxpython.org/docs/api/wx.ListCtrl-class.html
>
> > self.list.SetStringItem(index, 1, item['name'])
> > self.list.SetStringItem(index, 2, str(item['movingAvg200']))
> > self.list.SetStringItem(index, 3, str(item['movingAvg50']))
> > self.list.SetStringItem(index, 4, str(item['price']))
> > self.list.SetStringItem(index, 5, str(item['previous']))
> > self.list.SetStringItem(index, 6, str(item['price'] -
> item['previous']) )
> > self.list.SetStringItem(index, 7, str(item['totalValue']))
> > self.list.SetStringItem(index, 8, str(item['position']))
> >
>
> Do let us know if the suggestion works or not.
>
> Ramit Prasad
>
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hello! Questions

2016-02-17 Thread Marco Soldavini
I hit the send button too early. anyway

Basically something like

while (stop condition false)
read data
write data into local array or something
wait sample time


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


[Tutor] Hello! Questions

2016-02-17 Thread Marco Soldavini
Hi,
I am almost new to python and I am trying to build a not so easy app (but
very neat and useful) related to industrial automation.

Is this the right place to knock down problems one by one?
Basically my app has several interactions but the most important is reading
values from an embedded machine (better a PLC) via the OPC protocol.

I already tested this with some values of various kind (real, boolean,
strings). Basically each tag is read with a fixed sample time from a stream
opened in OPC and recorded onto an array in python.

Is it better I explain you the main picture? I am not here for spoon
feeding but just tips and suggestion and maybe solution to particular
problems I might find on the track.

Something about OPC is here: https://opcfoundation.org/about/what-is-opc/

The lib I am using is openopc.

My first question is about data types, data structures in general and how
to organize an efficient loop for recording data.

Basically something like

while (stop condition false)
read data
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hello! Questions

2016-02-18 Thread Marco Soldavini
On Wed, Feb 17, 2016 at 11:13 AM, Alan Gauld 
 wrote:


> > My first question is about data types, data structures in general and how
> > to organize an efficient loop for recording data.
>
> > while (stop condition false)
> >read data
> >write data into local array or something
> >wait sample time
>
> That's a good start. What is the question?
> You say you know how to read data fro openopc, so the
> first loop line should be fine.
> Storing into a list involves the append method:
>
> myDataList.append(myData)
>
> and the wait will probably be openopc specific
> but if not you can use the time.sleep() function.
>
>
> hth
> --
> Alan G



Ok here my main loop for gathering data (stripped off some code to make it
easier to read):


*# While loop - scanning and storing OPC values at scan rate **while *(abort
== 0):


*# ESC pressed? **if *msvcrt.kbhit() *and *ord(msvcrt.getch()) == 27:
abort = 1


*break *
*# Server up **if *opc.ping():


*if *opc[*'.run_batch'*] == True *and *rec_started == False:

*# Setting arrays for variables *bool1 = []
ana1 = []
ana2 = []
ana3 = []
ana4 = []
rec_started = True

*if *opc[*'.run_batch'*] == True *and *rec_started == True:

*# scan time *time2 = time.time()
dtime = time2 - time1

*if *dtime > 2 *and *comm_alarm == False:
dt = datetime.datetime.now()
bool1.append((opc.read(*'.watchdog'*)[0],opc.read(
*'.watchdog'*)[1],dt))
ana1.append((opc.read(*'.analog2'*)[0],opc.read(*'.analog2'*
)[1],dt))
time1 = time2


*else*:

*# scan time *time2 = time.time()
dtime = time2 - time1
*if *dtime > 2:
*print **"ERROR: OPC Server is down"*



As you can see I am using append to store data from opc.read command which
returns elements of string array.

Let's say I can have 30-40 variables (so 30-40 append instructions at every
cycle, with same scan rate).

Is this scalable when variables are getting bigger. What if this program
shall run for 2 hours and gather let's say 2000 elements in 40 arrays,
could this be a problem in term of computation?


Second question is I want the arguments in the opc.read command not to be
hard coded but coming from a configuration files.


You see the names of my arrays? bool1, ana1, ana2, etc... Is it possible to
derive number and names of these variables from an external files.

Let's say in this configuration file I can say I have to read 10 arrays or
20 arrays and then my program adjust the while cycle consequently.


Maybe an array of array where the second dimension is coming from the
config file.


Is this clear?


Version of python is 2.7.9 running on Windows 7.


Cheers,

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


Re: [Tutor] Hello! Questions

2016-02-19 Thread Marco Soldavini
Sorry, Here my code in plaintext

#While loop - scanning and storing OPC values at scan rate
while (abort == 0):

    # ESC pressed?
    if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
        abort = 1
        break

    # Server up
    if opc.ping():


        if opc['.run_batch'] == True and rec_started == False:
            # Setting arrays for variables
            bool1 = []
            ana1 = []
            ana2 = []
            ana3 = []
            ana4 = []
            rec_started = True

        if opc['.run_batch'] == True and rec_started == True:
            # scan time
            time2 = time.time()
            dtime = time2 - time1

            if dtime > 2 and comm_alarm == False:
                dt = datetime.datetime.now()
                
bool1.append((opc.read('.watchdog')[0],opc.read('.watchdog')[1],dt))
                
ana1.append((opc.read('.analog2')[0],opc.read('.analog2')[1],dt))
                time1 = time2
                

    else:
        # scan time
        time2 = time.time()
        dtime = time2 - time1
        if dtime > 2:
            print "ERROR: OPC Server is down”



Il giorno 19 febbraio 2016 @ 02:18:05, Alan Gauld (alan.ga...@btinternet.com) 
ha scritto:
> Let's say I can have 30-40 variables (so 30-40 append instructions at every 
> cycle, with same scan rate). 

Its not clear what the scan rate actually is. 
How many scans per second? 


yes scan per second. For example a new fetch every 2 second, so a new append to 
array every 5 second



> shall run for 2 hours and gather let's say 2000 elements in 40 arrays, 
> could this be a problem in term of computation? 

Yes it could, but it depends on what size the data is. 
You need to do some basic math to calculate it out. 

40 * 2000 = 80k items. If they are integers then its 
4 bytes per item so 320Kbytes. Not too bad. If they 
are 100 character strings then its into MB but on a 
modern PC still not too bad. But if it's intended to 
run in an embedded controller with only 1M of RAM 
it might be a big issue. 


Pc for sure, I think with 8GB RAM. I’ll do some detailed calculations about 
that.

> Second question is I want the arguments in the opc.read command not to be 
> hard coded but coming from a configuration files. 

OK. You might want to think about what that file 
format would look like. 


I’d like to have an xml file or csv file to parse (another topic I wanna learn) 
and in this file I have a table defining my variables with a name and another 
field for description


> You see the names of my arrays? bool1, ana1, ana2, etc... Is it possible to 
> derive number and names of these variables from an external files. 

It is but its usually a bad idea. 
Better is to use a dictionary with your "variables" 
as keys and your arrays as values. So your append 
looks like 

data = dict() 
keyName = readFromFile() 
value = readFromFile() 

data[keyName].append(value) 
Ok so I will look more into dictionaries, it is like hash tables?





> Let's say in this configuration file I can say I have to read 10 arrays or 
> 20 arrays and then my program adjust the while cycle consequently. 

Yes that's doable. 

> Maybe an array of array where the second dimension is coming from the 
> config file. 

I'd use the dictionary approach rather than arrays of arrays. 
(Which are probably lists of lists in Python.) 


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


Re: [Tutor] Hello! Questions

2016-02-19 Thread Marco Soldavini
On Fri, Feb 19, 2016 at 3:32 PM, Peter Otten <__pete...@web.de> wrote:

>
>
> Also, after reading http://openopc.sourceforge.net/api.html I wonder if it
> wouldn't be better to go with the timestamp provided by the server
>
>   bool1.append(opc.read(".watchdog"))
>

yes but my next step is to load some of this data up to SQL and the
timestamp provided by the opc was difficult to manage into a TIME field. I
manage to insert the appended data instead with the timestamp generated
with my code.

I'll work more on that to see if it is possible to get the original
timestamp. I don't require high precision just something around the second
is ok.


>
> With a slight modification of Alan's suggestion you could write to a list
> of
> dicts instead of a dict of lists like so:
>
> # outside the loop
> WANTED = [".watchdog", ".analog1", ".analog2]
> data = []
>
> # in the loop:
>  data.append({r[0]:r[1:] for r in opc.read(WANTED)})
>
>
>
Thanks for the helpful hints. I have a ton of questions yet to come!

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


[Tutor] ImportError: No module named...

2016-04-17 Thread Marco Soldavini
I am running this configuration

Win7 64 bit
Python 2.7.9
PyCharm Community Edition 4.5.4
Reportlab-2.8.win32-py2.7

I am try to running this simple example code

from reportlab.pdfgen import canvas
from reportlab.platypus import Image

im = Image ("logo.jpg")
c = canvas.Canvas("hello.pdf")
c.drawString(100,750,"Welcome to Reportlab!")
c.save()

But I get the following error code on line 1

ImportError: No module named pdfgen


I've checked my install and I have reportlab under
C:\Python27\Lib\site-packages\reportlab

I don't understand why this was working last time and now it doesn't anymore.
It could be an install problem?

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


Re: [Tutor] ImportError: No module named...

2016-04-18 Thread Marco Soldavini
Yeah, I spotted the mistake. There was a file left in the folder named
reportlab.pyc which I could not see from the pycharm interface.

Thanks!

On Mon, Apr 18, 2016 at 1:47 AM, Danny Yoo  wrote:
>
>> But I get the following error code on line 1
>>
>> ImportError: No module named pdfgen
>>
>
> Is reportlab.pdfgen a standard part of that package's installation?
>
> You might want to check for possible conflicts with other things called
> reportlab.  Do you have any files in the current directory that are called
> "reportlab"?
>
> You might also try the following:
>
> ###
> import reportlab
> print(reportlab.__file__)
> ###
>
> which hopefully should point to the expected path.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] XML and ElementTree

2016-04-25 Thread Marco Soldavini
I've a few questions about parsing XML. I wrote some code that works
but I want to know which are the most intelligent data structures to
parse data to

Consider that my XML file is something like the following:




1
XXX

   
   
   
   
   
   







So root element can have station child element from 1 to n
Each station element have unique child elements apart from groups
which may have more group child element each with a few tags

Now I want to parse this xml file and get the tag values into
variables in python
I could have 1 station element or 2 or 3
I could append all data in a long list, but is this good?
Could it be better to build a dictionary for each station element and
then build a list of dictionary
Which method you suggest to find data and use it after parsing it?

If later in the program I want to access a variable value I want to do
it with the xml tag name and not with an index like Settings[10] for
example but something like Settings['tag']

But what if I have more than one structure like station which has the same keys?

Following is part of my code for now.
Thanks!
marco


try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET


# Settings XML File Parsing

tree = ET.parse('settingstest.xml')
root = tree.getroot()

stations = len(root)
print "Found ",stations, " stations configured in settings file"

Settings = []
for station in root:
   StationId = station.find('StationId')
   Settings.append(StationId)
   .
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Tkinter and threading

2016-06-02 Thread Marco Soldavini
Hello,
probably this is a very naive question, but I've read some stuff on
Tkinter and its infinite loop.

Then about how can i bind actions to elements, for example buttons.

What if I want to run another loop beside the graphical interface in
the same python script?

For example a state machine with a var state which can have some
discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
and a text element on the gui that reports that state.

So a button cause a transition > the python loop (not the gui loop)
detects the transition and changes the state var value > the gui
refresh its value on screen.

I wrote some code to try it without threading but it does not give the
expected result as it seems the button update status action is already
triggered. I am missing some basic point here

from Tkinter import *

state = "STOPPED"

root = Tk()

myContainer1 = Frame(root)
myContainer1.pack()
label1=Label(myContainer1, text=state, font = "Helvetica 16 bold italic")
label1.pack()

def change(new_state):
label1.config(text=new_state)

button1 = Button(myContainer1, text="START")
button1.bind("", change("START"))
button1.pack()
button2 = Button(myContainer1)
button2["text"]= "STOP"
button2.pack()
root.mainloop()


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


Re: [Tutor] Tkinter and threading

2016-06-02 Thread Marco Soldavini
Thanks for you answers!

On Thu, Jun 2, 2016 at 6:39 PM, Peter Otten <__pete...@web.de> wrote:

>> For example a state machine with a var state which can have some
>> discrete string values (like RUNNING, STOPPED, PAUSED, ABORTED, IDLE)
>> and a text element on the gui that reports that state.
>>
>> So a button cause a transition > the python loop (not the gui loop)
>> detects the transition and changes the state var value > the gui
>> refresh its value on screen.
>>
>> I wrote some code to try it without threading but it does not give the
>> expected result as it seems the button update status action is already
>> triggered. I am missing some basic point here
>
> Indeed your problem has nothing to do with threads.
>>


Yes i know it could be done without threads, but for study reason i
want to separate the logic from representation (the HMI). That's how
usually program industrial machines. HMI serves only to display and
change variables, not to execute logic.

I want to build a mockup of a machine I saw at work, with statuses and alarms.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Web scraping using selenium and navigating nested dictionaries / lists.

2019-01-27 Thread Marco Mistroni
Hi my 2 cents. Have a look at scrapy for scraping.selenium is v good  tool
to learn but is mainly to automate uat of guis
Scrapy will scrape for you and u can automate it via cron. It's same stuff
I am doing ATM
Hth

On Sun, Jan 27, 2019, 8:34 AM  All,
>
>
>
> Goal of new project.
>
> I want to scrape all my books from Audible.com that I have purchased.
> Eventually I want to export this as a CSV file or maybe Json. I have not
> got
> that far yet. The reasoning behind this is to  learn selenium  for my work
> and get the list of books I have purchased. Killing two birds with one
> stone
> here. The work focus is to see if selenium   can automate some of the
> testing I have to do and collect useful information from the web page for
> my
> reports. This part of the goal is in the future. As I need to build my
> python skills up.
>
>
>
> Thus far, I have been successful in logging into Audible and showing the
> library of books. I am able to store the table of books and want to use
> BeautifulSoup to extract the relevant information. Information I will want
> from the table is:
>
> *   Author
> *   Title
> *   Date purchased
> *   Length
> *   Is the book in a series (there is a link for this)
> *   Link to the page storing the publish details.
> *   Download link
>
> Hopefully this has given you enough information on what I am trying to
> achieve at this stage. AS I learn more about what I am doing, I am adding
> possible extra's tasks. Such as verifying if I have the book already
> download via itunes.
>
>
>
> Learning goals:
>
> Using the BeautifulSoup  structure that I have extracted from the page
> source for the table. I want to navigate the tree structure. BeautifulSoup
> provides children, siblings and parents methods. This is where I get stuck
> with programming logic. BeautifulSoup does provide find_all method plus
> selectors which I do not want to use for this exercise. As I want to learn
> how to walk a tree starting at the root and visiting each node of the tree.
> Then I can look at the attributes for the tag as I go. I believe I have to
> set up a recursive loop or function call. Not sure on how to do this.
> Pseudo
> code:
>
>
>
> Build table structure
>
> Start at the root node.
>
> Check to see if there is any children.
>
> Pass first child to function.
>
> Print attributes for tag at this level
>
> In function, check for any sibling nodes.
>
> If exist, call function again
>
> If no siblings, then start at first sibling and get its child.
>
>
>
> This is where I get struck. Each sibling can have children and they can
> have
> siblings. So how do I ensure I visit each node in the tree?
>
> Any tips or tricks for this would be grateful. As I could use this in other
> situations.
>
>
>
> Sean
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get Selenium to wait for page load

2019-01-31 Thread Marco Mistroni
Hi
You won't find much help here as this is a python moist
Have a look at WebDriverWait from selenium.webdriver.support.ui

It allows you to wait for certain conditions
Hth

On Thu, Jan 31, 2019, 11:09 AM  Hi all,
>
>
>
> I have found an excellent article on identifying stale elements. The issue
> is when I try and use their example code. I get a failure where for_wait is
> not defined.
>
>
> http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-
> after-a-click.html
> 
>
>
>
> Traceback (most recent call last):
> File "", line 5, in 
> NameError: name 'wait_for' is not defined
> >>>
>
>
>
> When I look through the examples. I only find one reference for the above
> function. But it doesn't look correct and I am confused. The author
> indicates the definition of the function is half way up the page. As I
> cannot see, this reference doesn't help. So can someone help and provide
> the
> definition for this method/function?
>
>
>
> The code which generated the error:
>
>
>
> rows = []
>
> pageNav = browser.find_element_by_id("center-5")
>
> curr_page = pageNav.find_element_by_css_selector('span
> .pageNumberElement').text
>
> prev_page = ""
>
> while prev_page in curr_page:
>
> #wait_for(link_has_gone_stale):
>
> prev_page = curr_page
>
> rows.extend(tableNavigation (pageNav))
>
> if wait_for(link_has_gone_stale):
>
> pageNav = browser.find_element_by_id("center-5")
>
> curr_page = pageNav.find_element_by_css_selector('span
> .pageNumberElement').text
>
> if prev_page == curr_page:
>
> print ("Page no has not changed:",curr_page)
>
> else:
>
> prev_page = curr_page
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor