Gribouillis 1,391 Programming Explorer Team Colleague

There is a += in HiHe's code. Do you understand it ?

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps label.config(text='value')

Gribouillis 1,391 Programming Explorer Team Colleague

I think execute() expects a tuple such as (word,) instead of (word) which is the same as word without parentheses.

Gribouillis 1,391 Programming Explorer Team Colleague

Open the documentation page of the sqlite3 module, then search all occurrences of INSERT INTO in this page. Your answer is there!

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, you can change your code like this

def get_item1(line):
    return ((line[0], line[1]), line[2])

def get_key2(line):
    return (line[3], line[4])

k1 = dict(get_item1(line) for line in list1)

count2 = Counter(k for k in (get_key2(line) for line in list2) if k in k1)
k2 = set(k for k, v in count2.items() if v >= 3)

result = []
for line in list2:
    key = get_key2(line)
    if key in k2:
        x = list(line[:-1])
        x.append(k1[key] if line[-1] == 'n/a' else line[-1])
        result.append(x)
Gribouillis 1,391 Programming Explorer Team Colleague

I need to add to the final "result" the third value of list1 where the two lists match.

You must describe this more precisely. From what I understand you want to alter every line in result with a value extracted from the matching line in list1. It is possible of course, but what will you do if list1 contains more than 1 matching line ?

Gribouillis 1,391 Programming Explorer Team Colleague

If you only want simple things such as buttons, entries, choices etc, I discovered guidata recently which is extremely easy to use. It is based on Qt in python but you don't need to learn Qt.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes it looks like an experimental module by a famous ruby guru. Is it still developped ?

Gribouillis 1,391 Programming Explorer Team Colleague

Assuming that you already have lists of "lines" which are tuples or lists, I suggest something along the line of

from collections import Counter

get_key(line):
    return (line[3], line[4])

# compute the set of all keys in list 1
k1 = set(get_key(line) for line in list1)

count2 = Counter(k for k in (get_key(line) for line in list2) if k in k1)
k2 = set(k for k, v in count2.items() if v >= 3)

result = [line for line in list2 if get_key(line) in k2]
Gribouillis 1,391 Programming Explorer Team Colleague

I don't understand, please post code with complete dictionaries and describe your expected output.

Gribouillis 1,391 Programming Explorer Team Colleague

What are your dictionaries? Python's built-in dictionaries cannot have several occurrences of the same key.

Gribouillis 1,391 Programming Explorer Team Colleague

However, if I'm asked to do an exercise, I cannot quite get every step down to what I should be doing.

It is because what you should be doing is not determined solely by the problem to solve or the peculiarities of the language. The largest part is determined by the tools at your disposal. It means the hundreds of functions in the standard library and third-party libraries. You need to learn that such or such function or class is the tool to use to solve such or such problem. Only time and experience can teach you that. You learn to know the tools by using them often.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a modified version which works (with python3) up to the point where the newWindow() method is called. You must add the code for the popup window and subsequent behavior

#-*-coding: utf8-*-
from tkinter import *
import tkinter

class GUI:

    def __init__(self):
        self.root= Tk()
        self.labelVariable = StringVar()
        self.root.title('Projet informatique')
        self.initialize()
        self.root.mainloop()

    def initialize(self):
        self.main = Frame(self.root)
        self.main.pack() 

        label = Label(self.main, textvariable=self.labelVariable, font=('courier',10,'bold'), anchor="w", fg="red", bg="white")
        label.grid(column=0,row=1,columnspan=2,sticky='EW')
        self.labelVariable.set(u"Modélisation de populations atteintes d'un virus")

        v=tkinter.Listbox(self.main)
        v.insert("end","Modèle SIR")
        v.insert("end", "Modèle de Witowski")
        v.insert("end", "Modèle de Munz")
        v.insert("end", "Modèle avec infection latente")
        v.insert("end", "Modèle avec traitement")
        v.bind("<Double-Button-1>", self.Double)
        v.grid(row=2,column=0)

        self.root.grid_columnconfigure(0,weight=1)

    def Double(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        self.newWindow(value)

if __name__ == "__main__":
    app = GUI()
    app.title('Projet informatique')
    #on boucle sans fin en attente d'évenements
    app.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

Why not this ?

>>> import numpy as np
>>> a = np.array([1,2,1,3,4,5])
>>> 0.64 + 0.12 * a
array([ 0.76,  0.88,  0.76,  1.  ,  1.12,  1.24])
Slavi commented: elegant :D +6
Gribouillis 1,391 Programming Explorer Team Colleague

As a bonus, you can try my sqlite snippet on your database to display its structure from the command line.

Gribouillis 1,391 Programming Explorer Team Colleague

I opened the database with sqliteman and the table was indeed empty. What happened is that you forgot a statement

conn.commit()

in dbinsert.py before closing the connection. Your inserts occurred in memory but they were never written on disk.

Gribouillis 1,391 Programming Explorer Team Colleague

You can install sqliteman to browse the database. Type

sudo apt-get install sqliteman

in ubuntu or other debian distros. Then open your database file with sqliteman and examine the contents of the database. You can also run sql statements in the gui.

Gribouillis 1,391 Programming Explorer Team Colleague

For simple interfaces such as displaying or capturing data, a super easy solution is guidata.

Gribouillis 1,391 Programming Explorer Team Colleague

You could perhaps create an image in a canvas widget, then draw other widgets above the canvas.

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest to use the boot-repair disk as Slavi did in this thread. In principle, it should work.

It seems strange to me that you don't have a linux swap partition.

Gribouillis 1,391 Programming Explorer Team Colleague

Why don't you use the other thread's solution ? I wrote all the code to create the file if does not exist and also to be able to run the code from another directory etc. If you use a function such as load_favorite() instead of pickle.load( open("films.db", "rb")) it will work.

Gribouillis 1,391 Programming Explorer Team Colleague

Again, your error message is for a modified code.
I think you're forgetting that the pack() method returns None, which means that you must write a separate statement to pack the label if you want to keep a pointer to it. For example, here is a working code snippet

#!/usr/bin/env python
# -*-coding: utf8-*-


def callback():
    lbl.configure(text = 'button clicked!')


import Tkinter

window = Tkinter.Tk()
window.geometry('300x300')
window.configure(background = 'PeachPuff3')
lbl = Tkinter.Label(window, text = 'Nothing yet!')
lbl.pack()
btn = Tkinter.Button(window, text = 'add', command = callback)
btn.pack()
print(lbl, btn)
window.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

In python 2 in kubuntu, I can import it directly

import ttk

In python 3 it is

from tkinter import ttk

ttk.py should be in the folder lib-tk in your python2 library. Try to run

locate ttk

in a terminal to see where it is.

Gribouillis 1,391 Programming Explorer Team Colleague

There is no line Label['text'] = 'Good morning' in the code you posted before. Also this error message is very explicit. You are using a variable named Label which has not been defined. Also this variable name is a very bad choice in a tkinter context where Label is a tkinter class.

Gribouillis 1,391 Programming Explorer Team Colleague

Python says why it doesn't work

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'Tkinter'

Nothing is more important than the error message! Don't forget to add it to your posts.

The reason is that between python 2 and python 3, some modules in the standard library were renamed. In particular, uppercase characters were removed from their names and Tkinter became tkinter.

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, here is the code section with comments. I hope it helps

#!/usr/bin/env python3
# -*-coding: utf8-*-
import os
import pickle

DBFILENAME = 'films.db'

# The next line initializes a variable named 'loaded' to the value False
# This variable tells us if the database of favorite movies has
# already been loaded.
loaded = False

favorite_movies = [] 

def pathtofile(filename=DBFILENAME):
    # The __file__ variable contains a string giving
    # the location of the current program in the file
    # system. The following line computes the absolute
    # path of the directory containing this program
    # (print it to see its value)
    folder = os.path.dirname(os.path.abspath(__file__))

    # the next line returns the absolute path
    # to the location of the dbfile that we want
    # to use. Computing this carefully allows
    # us to robustly call this program from
    # any folder.
    return os.path.join(folder, filename)

def load_favorite():
    # this global declaration (at the beginning of
    # the function's body) tells python that we are
    # going to give new values to these global variables
    # If we don't write this, python thinks that these
    # are local variables, and writing statements such as
    # loaded = True
    # would have no effect on the outer variable 'loaded'
    global favorite_movies, loaded

    # if the fav list has already been loaded, we don't
    # do anything and exit the function
    if loaded:
        return

    filepath = pathtofile()
    if not os.path.isfile(filepath): # <- file does not exist
        # the db file does not exist. …
Gribouillis 1,391 Programming Explorer Team Colleague

Ok, here is a way. Try to understand every detail

#!/usr/bin/env python3
# -*-coding: utf8-*-
import os
import pickle

DBFILENAME = 'films.db'
loaded = False
favorite_movies = [] 

def pathtofile(filename=DBFILENAME):
    """Return absolute path to the db file"""
    # use db file in the same folder as
    # our program (this could be different)
    folder = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(folder, filename)

def load_favorite():
    global favorite_movies, loaded
    if loaded:
        return
    filepath = pathtofile()
    if not os.path.isfile(filepath): # <- file does not exist
        with open(filepath, 'wb') as fout:
            pickle.dump([], fout) # <- dump an empty fav movies list in file

    # The 'with' construct ensures that the file is
    # properly closed after the with block
    with open(filepath, 'rb') as fin:
        favorite_movies = pickle.load(fin)
    loaded = True

def dump_favorite():
    filepath = pathtofile()
    with open(filepath, 'wb') as fout:
        pickle.dump(favorite_movies, fout)

def append():
    import sys
    movie_name = str(sys.stdin.readline())
    load_favorite()
    favorite_movies.append(movie_name)
    dump_favorite()
    print (favorite_movies)

def sort():
    load_favorite()
    favorite_movies.sort()
    print (favorite_movies)

def view():
    load_favorite()
    print (favorite_movies)

if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
    help='name of function to execute',
    metavar='FUNCNAME',
    choices=['view' , 'sort' , 'append'])
    args = parser.parse_args()
    function = globals()[args.funcname]
    function()
Gribouillis 1,391 Programming Explorer Team Colleague

Without the exact code, it is impossible to debug. For example in my code, there is no pickle.load( open("films.db", "rb")).

Gribouillis 1,391 Programming Explorer Team Colleague

In fact it does not matter. However, a standard program pattern is

# shebang line (#! ...)
# coding

"""program docstring
"""

# imports ...
import os
import pickle

# some global constants
MYCONSTANT = 733

# functions and class definitions

def spam():
    ...

class Eggs():
    ...

# module level code
statement
statement

# script level code
if __name__ == "__main__":
    statement
    statement
    statement

With this design, my code could go in the module level code at the end, or in a function's body returning the fav movies list, which could be called from the module level code section.

Of course, python allows you to write the code anywhere.

Gribouillis 1,391 Programming Explorer Team Colleague

You can create a pickle file containing an empty list of favorite movies

#!/usr/bin/env python3
# -*-coding: utf8-*-

import os
import pickle

# use db file in the same folder as
# our program (this could be different)
filename = 'films.db'
folder = os.path.dirname(os.path.abspath(__file__))
filepath = os.path.join(folder, filename)


if not os.path.isfile(filepath): # <- file does not exist
    with open(filepath, 'wb') as fout:
        pickle.dump([], fout) # <- dump an empty fav movies list in file

# The 'with' construct ensures that the file is
# properly closed after the with block
with open(filepath, 'rb') as fin:
        favorite_movies = pickle.load(fin)
Gribouillis 1,391 Programming Explorer Team Colleague

If you add lists of integers together, you will always obtain a list of integers. If you want a list of sublist, you must append sublists to pack:

pack.append(sublist)

This adds only one element, this element is a sublist.

Gribouillis 1,391 Programming Explorer Team Colleague

The result (array([2]),) is a tuple containing a single item which is an np array. The item 0 of this tuple is the first item, ie the array. This array's item 0 is its first element, the integer 2.

Also this is interesting:

>>> import numpy as np
>>> a=np.array([[1,2,1],[3,4,2],[6,5,3],[7,8,4]])
>>> (a[:,0] == 6)
array([False, False,  True, False], dtype=bool)
>>> (a[:,1] == 5)
array([False, False,  True, False], dtype=bool)
>>> ((a[:,0] == 6) & (a[:,1] == 5))
array([False, False,  True, False], dtype=bool)
>>> ((a[:,0] == 6) & (a[:,1] == 5)).nonzero()
(array([2]),)

try >>> help(np.nonzero) for more documentation.

Gribouillis 1,391 Programming Explorer Team Colleague

Sure

index = np.where((a[:,0] == 6) & (a[:,1] == 5))[0]
X = index[0]
Gribouillis 1,391 Programming Explorer Team Colleague

You can write

if np.where((a[:,0] == 6) & (a[:,1] == 5))[0]:
    print('yes')
else:
    print('no')

Can you explain what you want to do in a more precise way ?

Gribouillis 1,391 Programming Explorer Team Colleague

Well, as 7 is in the first column and 5 is in the second column, the result is hardly suprising

>>> a[:,0]
array([1, 3, 6, 7])
>>> a[:,1]
array([2, 4, 5, 8])
>>> 7 in a[:,0] and 5 in a[:,1]
True

EDIT: this seems to be working, extracting an array of row indices

>>> np.where((a[:,0] == 6) & (a[:,1] == 5))
(array([2]),)
Gribouillis 1,391 Programming Explorer Team Colleague

@snippsat I like the concept, although being based on top of sqlalchemy may have a performance cost for dataset.

The greatest thing in this may be the datafreeze command that it contains and the concept of yaml freezefile which make it possible to describe a reusable extraction of data from a given database.

With a little more work, freezefiles could be used to export pickle files instead of json or csv, making them trivial to load from python.

Gribouillis 1,391 Programming Explorer Team Colleague

Being able to save data to disk and retrieve it is equivalent to being able to convert this data to string and then back to data. Indeed, you can always define

def save(data, filename):
    with open(filename, 'w') as fh:
        fh.write(string_from_data(data))

def retrieve(filename):
    with open(filename) as fh:
        return data_from_string(fh.read())

It means that you only need to define string_from_data() and data_from_string(). This is called serializing and de-serializing data. There are many ways to do it.

For example, supposing that your data is a list of names and that the names don't contain a newline character, one can define

def string_from_data(data):
    return '\n'.join(data)

def data_from_string(s):
    return s.split('\n')

Now with these definitions, you can write in program:

import os
FILENAME = 'mylist.txt'

if os.path.isfile(FILENAME):
    mylist = retrieve(FILENAME)
else:
    mylist = []

# ... work with mylist

save(mylist, FILENAME)
Gribouillis 1,391 Programming Explorer Team Colleague

Use argparse ! It is by far the best way to do this

#!/usr/bin/env python3
# -*-coding: utf8-*-

def sayhi():
    print('hi everybody!')

def goodbye():
    print('see you soon!')

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
        help='name of function to execute',
        metavar='FUNCNAME',
        choices=['goodbye', 'sayhi']) # <-- LOOK HERE
    args = parser.parse_args()
    function = globals()[args.funcname]
    function()
Gribouillis 1,391 Programming Explorer Team Colleague

Then the script must take an argument which is the function name. The best thing to do is to use the argparse module to parse the command line, something like

#!/usr/bin/env python3
# -*-coding: utf8-*-

def sayhi():
    print('hi everybody!')


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
        help='name of function to execute',
        metavar='FUNCNAME',
        choices=['sayhi'])
    args = parser.parse_args()
    function = globals()[args.funcname]
    function()
Gribouillis 1,391 Programming Explorer Team Colleague

Can you post your script? It depends on what you want to do. For example, here is a function which prints hello world

#!/usr/bin/env python
# -*-coding: utf8-*-
# This is file hello.py
# Line 1 above tells the linux shell that this
# program must be executed with python. Replace
# python with python3 if needed.
# Line 2 above tells python that this file is
# encoded in utf8

# our function definition

def thefunc():
    print('hello world')

if __name__ == '__main__':
    # this block contains the code that will be executed
    # when hello.py is executed on the command line
    # It calls our function thefunc()
    thefunc()

Now save this file under the name hello.py, then in a terminal run the 2 commands

chmod +x hello.py
./hello.py
Gribouillis 1,391 Programming Explorer Team Colleague

The else part must go with the for. It is only executed if the for loop was not interrupted by a break statement

for i in range (2, 25):
    if 25 % i == 0:
        break
else:
    print (25, " is a prime number.")

See the doc https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

Gribouillis 1,391 Programming Explorer Team Colleague

You can do it in a one-liner

total = sum(float(x) for x in '1.32, 5.32, 4.4, 3.78'.split(','))
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

If the dictionary file was created on windows, it may have windows-like end of lines. Try to open the dictionary file with mode 'rU' (universal newlines).

Gribouillis 1,391 Programming Explorer Team Colleague

On my system, PySide is in the folder /usr/lib/python2.7/dist-packages

Check that this directory is in the python path

>>> import sys
>>> '/usr/lib/python2.7/dist-packages' in sys.path
True

If it is not in the python path, set the environment variable PYTHONPATH.

You can also find PySide in a terminal with

sudo apt-get install mlocate
sudo updatedb
locate PySide
Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps a sudo apt-get install python-pyside (or python3-pyside).

Gribouillis 1,391 Programming Explorer Team Colleague

You need to add

value = float([y for x, y in valueTable if x == 'Price/Book (mrq):'][0])
print(value)

You could perhaps find the table first with a findAll('table', ...).

Gribouillis 1,391 Programming Explorer Team Colleague

We see the failing regex, but we don't know how it fails. Can you post a fully failing python example with a (short) concrete respData ?

Gribouillis 1,391 Programming Explorer Team Colleague

In Kubuntu, aptitude says that the new python Pil is a fork of Pillow.

Gribouillis 1,391 Programming Explorer Team Colleague

On my system it is

sudo apt-get install python-matplotlib python3-matplotlib python-pil python3-pil

It is easier to find packages with aptitude

sudo apt-get install aptitude
aptitude search pil