Gribouillis 1,391 Programming Explorer Team Colleague

epsilon has no special meaning in python. It is a valid identifier which can be used as a variable name as in the above code. In numerical analysis, epsilon is typically used to denote a positive quantity close to zero.

Gribouillis 1,391 Programming Explorer Team Colleague

In linux, you can use subprocess.call(['xdg-open','NAMEOFFILE']).

Gribouillis 1,391 Programming Explorer Team Colleague

These anonymous could very well be a western intelligence agency.

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

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

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

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

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

Gribouillis 1,391 Programming Explorer Team Colleague

You can use a breadth-first traversal to find the webapps folders first, then walk these folders

import collections as col
import itertools as itt
import os

def breadth_first(root, subnodes_func, max_depth=None):
    """Yield pairs (depth, node) in the breadth-first traversal of a tree

        Args:
            root: root node of the tree
            subnodes_func: function of one node argument returning
                a sequence of subnodes
            max_depth: maximum depth of generated nodes (defaults to None)
    """
    fifo = col.deque([(0, root)])
    limited = (max_depth is not None)
    while fifo:
        depth, node = fifo.popleft()
        yield depth, node
        if limited and depth >= max_depth:
            continue
        depth += 1
        for subnode in subnodes_func(node):
            fifo.append((depth, subnode))

def subdirs(dir):
    """Generates subfolders of a given folder"""
    try:
        r, d, f = next(os.walk(dir))
        for x in d:
            yield os.path.join(r, x)
    except StopIteration:
        return

def gen_webapps_dirs(root, max_depth=None):
    """Generate folders named 'webapps' while traversing root folder breadth-first"""
    for d, dir in breadth_first(root, subdirs, max_depth=max_depth):
        if os.path.basename(dir) == 'webapps':
            yield dir

if __name__ == '__main__':
    file = open("hosts.txt","r")

    for servername in file:
        path = '\\\\'+servername.strip()+'\\d$\\tomcat\\Servers\\'
        for webapps in gen_webapps_dirs(path, max_depth=2):
            print(webapps)

`

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

That's many t's and k's.

Gribouillis 1,391 Programming Explorer Team Colleague

In python 2, use

import ttk

why don't you read the answers ?

Gribouillis 1,391 Programming Explorer Team Colleague

The random module may be helpful.

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

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

Ok, so here is a new standard lib candidate

import re

def overcount(S, sub, start=0, end=None):
    """overcount(S, sub[, start[, end]]) -> int

    Return the number of overlapping occurences
    of substring sub in string S[start:end].
    """
    p = r'(?={})'.format(re.escape(sub))
    t = () if end is None else (end,)
    return len(re.compile(p).findall(S, start, *t))

if __name__ == '__main__':
    print(overcount("assesses assesses", "sses", 0, 9)) # 2
snippsat commented: Nice +12
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

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

You can also burn a DVD with the appropriate version of kubuntu. Go here http://www.kubuntu.org/getkubuntu and choose Kubuntu 14.04 (long term support). If your PC is 64 bits choose the 64 bits version.

Make sure the computer is connected to your modem by a cable,
Then reboot the computer on this DVD. During the install process, the most important step is the partitioning. I suggest a manual partitioning:

1) delete existing partitions (say goodbye to win7 and your data)
2) It can be useful to have a small partition for the mount point /boot near the beginning of the disk (for example 1 GB formatted in ext4)
3) You need a partition for the mount point / (for example 100 GB, formatted in ext4)
4) You need a swap partition (for example 4 times the RAM, say 16 GB if you have 4 GB of ram, type is linuxswap) You can have more, but I don't know if it is useful.
5) It is a good idea to have a separate partition for the mount point /home (as many GB as you want, say the rest of your disk, formatted in ext4)

For the rest of the procedure, answer the installer's questions.

EDIT: when the installation is complete, go to a terminal and type the commands

sudo apt-get update
sudo apt-get upgrade

this will download and install the latest software upgrades for your system.

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

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

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
Gribouillis 1,391 Programming Explorer Team Colleague

I uploaded a module named symboldict to the python package index (pypi). This snippet shows how to use it to create a dictionary of symbols from various modules. This dictionary can be used as a common language shared by several modules. It can be used to load python libraries in a lazy way. It also brings the power of python dictionaries to manipulate collections of functions.

Gribouillis 1,391 Programming Explorer Team Colleague

You can try something along the line of

ss = re.sub(r'^\d+ ?', '', s, re.MULTILINE)
Gribouillis 1,391 Programming Explorer Team Colleague

Merry xmas and Happy New year guyzzzz :)))

Slavi commented: copycat! =) +0
Gribouillis 1,391 Programming Explorer Team Colleague

There may be indention issues in your code. What is the self at lines 28 and 36 for example? Also avoid to have two different variables program_buttons and programs_button in the same file.

Gribouillis 1,391 Programming Explorer Team Colleague

Merry Christmas! The look is very similar to DrPython's, which was also designed for teaching purposes (I think it was a python version of a DrScheme (now DrRacket) related to how to think like a computer scientist). He could perhaps start with DrPython's GUI.

Edit: hm, DrPython is in wxpython. They need a tkinter version of the same GUI.

Gribouillis 1,391 Programming Explorer Team Colleague

In python, one can execute a program using the subprocess module. For example, you can use this snippet to get program output, error messages and exit status.

With this, you can easily build a program third.py which executes the two initial binaries. Then you could use py2exe to get a third.exe.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you mean

if position_x == 375:
    print position_x

?

Gribouillis 1,391 Programming Explorer Team Colleague

It is not a python issue, it is an rsync issue. Solve the problem outside of python, then use the solution in python. There are ways to use rsync without being prompted for password, but I don't know rsync well enough. You should google for it, and perhaps ask in the linux forum.

Gribouillis 1,391 Programming Explorer Team Colleague

The line

#!/usr/bin/python -tt

is not a python thing. It is a unix mechanism named shebang. If the file is made executable in unix, the first line of the file is parsed and if it contains the shebang structure, the OS knows that it must execute the program on the shebang line. For example executing this file in unix will start the process

/usr/bin/python -tt thisscript.py

A python file such as myscript.py has two different uses:

  1. it can be executed as a script by a command python myscript.py
  2. it can be used as a module by another script with a statement import myscript

When the file is executed, a special variable __name__ is defined. In the first case, this variable has the value '__main__' and in the second case its value is the current module's name 'myscript' in our case.

Hence the intended meaning of

if __name__ == '__main__':
    do_stuff()

is

if we_are_executed_as_a_script_and_not_as_a_module():
    do_stuff()

It is not required for all modules, but it is often useful. A main() function is not required in python. You can write arbitrary code in this block, you could even have several such blocks.

Gribouillis 1,391 Programming Explorer Team Colleague

I never tried this, but the iat tool is a converter to iso9660 (see here for example), then here is a discussion about iso and img...

Gribouillis 1,391 Programming Explorer Team Colleague

hm, sourceforge is back.

Slavi commented: it worked =) +5