Gribouillis 1,391 Programming Explorer Team Colleague

I agree with vegaseat, try

import tkinter
print(tkinter)
Gribouillis 1,391 Programming Explorer Team Colleague

There is a moment is every woman's life, when she wants to do something forbidden.

Easy, the opposite is: Some women never want to do anything forbidden.

Another solution was

if int(menu) not in (1, 2):
aVar++ commented: I didn't know you could do that even when I knew python well. Thank you :). +4
Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps replace host with host.get() in lambda .

Gribouillis 1,391 Programming Explorer Team Colleague

Very good. I would have written shutil.move(files, client_folder). Another solution is to create a sequence of files to move first

def to_move(folder):
    """generate the files to move"""
    wd = os.getcwd()
    os.chdir(folder)
    try:
        for name in glob.glob('*.*'):
            if 'client_name' in str(name).lower():
                yield os.path.join(folder, name)
    finally:
        os.chdir(wd)

src_dir = r'd:\Desktop'
L = list(to_move(src_dir))
Gribouillis 1,391 Programming Explorer Team Colleague

I disapprove inflammatory debates in daniweb. I had one once with a knowledgeable programmer and some time later, he ceased to connect. I think he had too strong convictions and he wanted everybody to agree.

Gribouillis 1,391 Programming Explorer Team Colleague

This can actually be used to mimick the action of the ls command with colorful output. The following code lists the user's home directory with colors:

from termcolor import colored # pip install termcolor
import sys
if sys.platform == 'win32':
    from colorama import init # pip install colorama
    init()
import os
import stat

def color_code(filename):
    try:
        mode = os.lstat(filename).st_mode
    except OSError:
        return
    if stat.S_ISDIR(mode):
        return 'blue'
    elif stat.S_ISLNK(mode):
        return 'cyan'
    elif stat.S_ISFIFO(mode) or stat.S_ISBLK(mode):
        return 'yellow'
    elif mode & (stat.S_IXUSR):
        return 'green'
    elif filename.endswith((".tar", ".zip", ".deb", ".rpm", ".gz")):
        return 'red'
    elif filename.endswith((".jpg", ".gif", ".png", ".tiff", ".mp3", ".ogg", ".wav")):
        return 'magenta'

def listdir_color(directory):
    L = sorted(os.listdir(directory), key = lambda s: s.lower())
    for i, name in enumerate(L):
        fn = os.path.join(directory, name)
        col = color_code(fn)
        if col is not None:
            L[i] = colored(name, col)
    return L

if __name__ == '__main__':
    L = listdir_color(os.path.expanduser('~'))
    print_multicolumn(L, 4)

It even works in the ipython notebook !

Also notice that (partial) pure python implementations of ls already exist. See the pycoreutils package :)

Gribouillis 1,391 Programming Explorer Team Colleague

This snippet is reserved for users of the KDE linux desktop. It adds a service menu to kde applications such as dolphin and konqueror, to launch an ipython dashboard in a directory in one click.

More specifically, save the text of this snippet as a file ~/.kde/share/kde4/services/ServiceMenus/opennotebook.desktop (create the directory if necessary). Make sure ipython is installed. You may prefer an install via sudo pip install ipython over your distribution's ipython-notebook package (I experienced issues with ipython older than 1.1.0).

Then open dolphin and right-click a directory. In the Actions submenu, there should be an entry Start Notebook. Upon clicking this entry, a konsole tab opens which runs an ipython notebook. A web page appears in the default web browser which is the ipython dashboard for notebooks stored in this directory. We are ready to use python comfortably in 2 clicks !

I use this service menu every day, and it is very handy. I hope you'll enjoy it.

Gribouillis 1,391 Programming Explorer Team Colleague

This snippet prints a python list of strings in multicolumn format (similarly to linux ls command). It uses module prettytable, available in pypi.

Gribouillis 1,391 Programming Explorer Team Colleague

The obvious error is that the file argument in storbinary() must be an open file object instead of a string. Try

with open(sourcepath, 'rb') as ifh:
    ftps.storbinary(outbound, ifh, 8192)
Gribouillis 1,391 Programming Explorer Team Colleague

Dont like that there is no source code comment pointing out where to get it and that there is no info if it supports py3. Cant use it, downvote therefore.

I did not write this with python 3 in mind. For windows you can download pythonmagick binaries for python 3 in Christoph Gohlke's site.

I was not able to install pythonmagick for python 3 in linux mint (as of November 24th 2013). You can use other python wrappers around ImageMagick however. For example I tried a ctypes wrapper magickpy, installed using pip3 (package python3-pip in linux mint). Here is the code

import magickpy as Magick

in_name = 'scilab02.png'
out_name = 'scilab02_small.png'

img = Magick.Image.read(in_name)
w, h = img.width, img.height
new_width = 800
factor = new_width/float(w)
new_height = int(h * factor)
info = Magick.ExceptionInfo()
filter = Magick.FilterTypes.BesselFilter
blur = 1.0
img2 = img.makeResize(new_width, new_height, filter, blur, info)
img2.write(out_name)

Aso check this page for other wrappers.

Gribouillis 1,391 Programming Explorer Team Colleague

The 4 letters words are nodes in a graph where adjacent nodes differ by one letter from the current node. Starting from the startword, you can do a depth first walk of the graph until you reach the endword. I posted a clue for depth first traversal here (replace urls with 4 letter words).

Gribouillis 1,391 Programming Explorer Team Colleague

A new module python-future is available to help build code cross compatible between python 2 and 3, and for code conversion. Check it !

Gribouillis 1,391 Programming Explorer Team Colleague

You can use the Command class in this code snippet. You would write

com = Command("./vershion.sh").run()
if com.failed:
    print(com.error)
else:
    print(com.output)
Gribouillis 1,391 Programming Explorer Team Colleague

Importing a hierarchy of firefox bookmarks in konqueror can be tricky, as konqueror's bookmarks editor doesn't read firefox's sqlite databases where the bookmarks are stored.

Konqueror bookmarks are normally stored in a file ~/.kde/share/apps/konqueror/bookmarks.xml , which is actually a dialect of xml named xbel.

I found very little documentation about this transition, and my first attempt was to export firefox' bookmarks in html format, then import the html bookmarks from konqueror. Unfortunately, it failed to import the subfolders in the tree of bookmarks. It seems to me that this forum is a good place to post a working solution.

The solution is to install the Opera web browser, which can import bookmarks from firefox' places.sqlite file. Once the bookmarks are in Opera, they can be exported in an opera bookmarks format file (extension .adr). Then Konqueror's bookmarks editor is able to import those opera files. HaHa!

All my subfolders were correctly imported into Konqueror.

cereal commented: thanks for sharing! +11
Gribouillis 1,391 Programming Explorer Team Colleague

Sending your code to the python interpreter yields

  File "<ipython-input-1-18413f1ea40a>", line 3
    w=[l[0],l[1],l[2],l[3],l[4])
                               ^
SyntaxError: invalid syntax

Please correct the syntax first and post code that python accepts to run.

Gribouillis 1,391 Programming Explorer Team Colleague

You can also use the key parameter in function min():

import itertools as it

point_list = [
    (1, 2),
    (3, 5),
    (4, 6),
    (1.5, 7),
]

def distance(pair):
    p, q = pair
    return ((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) ** 0.5

print(min(it.combinations(point_list, 2), key = distance))

""" my output -->
((3, 5), (4, 6))
"""
Gribouillis 1,391 Programming Explorer Team Colleague

You cannot use s[0] on en empty string, as s[0] returns the first char in the string: write the empty strings tests first.

Gribouillis 1,391 Programming Explorer Team Colleague

Please avoid SMS language in the forum ...

The best thing to do is to post your attempts to decipher your text with python in this thread. We may be able to help you but nobody will write the code for you.

Gribouillis 1,391 Programming Explorer Team Colleague

One problem is that you start each year with c = 1 on the first day. Since your criterion for sundays is c%6 == 0. It means that every year starts with a tuesday.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is an example with 2 worker threads. It uses Condition objects to synchronize threads. It is relatively easy to understand if you remember that only one thread may own a given condition at a given time, which means for example that a worker blocks on with G.wcond if another thread is in a with G.wcond section, unless the other thread is running a G.wcond.wait() statement.

from threading import Thread, Condition
import time

class G:
    wcond = Condition()
    pcond = Condition()
    can_work = False
    can_process = True

class Worker(Thread):
    def run(self):
        while True:
            with G.wcond:
                while not G.can_work: # we wait for permission to work
                    G.wcond.wait()
                self.do_work()
                G.can_work = False
                with G.pcond: # we give permission to process
                    G.can_process = True
                    G.pcond.notify()

    def do_work(self):
        for i in range(3):
            print("working ...", self.name)
            time.sleep(0.2)


class Processor(Thread):
    def run(self):
        while True:
            with G.pcond:
                while not G.can_process: # we wait for permission to process
                    G.pcond.wait()
                self.do_process()
                G.can_process = False
                with G.wcond: # we give permission to work
                    G.can_work = True
                    G.wcond.notify()


    def do_process(self):
        for i in range(2):
            print("processing ...")
            time.sleep(0.2)

w, w2, p = Worker(), Worker(), Processor()
w.start()
w2.start()
p.start()

"""my output -->
processing ...
processing ...
('working ...', 'Thread-4')
('working ...', 'Thread-4')
('working ...', 'Thread-4')
processing ...
processing ...
('working ...', 'Thread-5')
('working ...', 'Thread-5')
('working ...', 'Thread-5')
processing ...
processing ...
('working ...', 'Thread-4')
('working ...', 'Thread-4')
etc
"""

With regard to your code, notice that

  1. The Thread's run() method must contain the thread's action, instead of its __init__() method.
  2. …
Gribouillis 1,391 Programming Explorer Team Colleague

i guess i can use eval(str)

No! Use json.loads()

Gribouillis 1,391 Programming Explorer Team Colleague

I would pass json format

command '{"India":["New Delhi", "Bangalore"], "Canada": ["Toronto","Vancouver"]}'

and in python code

import json
self.items = json.loads(items)

This avoids any eval issue, and eases cross programs calls.

Gribouillis 1,391 Programming Explorer Team Colleague

A simple way to resize an image programmatically, using the PythonMagick module. This module is a python port of the the magick++ library.

Gribouillis 1,391 Programming Explorer Team Colleague

I have no idea what to do.

In this case, compute the GPA by hand, without your computer, and write down carefully every detail of your procedure. This should give you the algorithm.

Gribouillis 1,391 Programming Explorer Team Colleague

The errors come from bad bookkeeping of the index i

def lapping(x1, x2):
    x1, x2 = str(x1), str(x2) # in case integers are passed to lapping()
    not_lapped= True #used to test if there was no lapping
    i = -1
    for sets in Big_Set[:-1]: # don't use the last set
        i += 1
        if x1 in sets:
            y = sets.index(x1) # the first position where x1 is
            if x2 == Big_Set[i+1][y]:
                print("%s and %s laps in sets: " %(x1, x2))
                print("set%d: %s" %(i+1,str(sets)))
                print("and")
                print("set%d: %s" %(i+2,str(Big_Set[i+1])))
                not_lapped= False
    if not_lapped:
        print("%s and %s do not match the lapping criteria\n" %(x1,x2))
Gribouillis 1,391 Programming Explorer Team Colleague

The most flexible solution is that the calling code stores the pointer to the window

def start():
    window = MainWindow()
    window.show()
    return window

# in calling code
import above_module
window = above_module.start()

The other solution is that the pointer is stored in above_module. For example

window = None

def start():
    global window
    window = MainWindow()
    window.show()

One drawback of this approach is that window is not automatically garbage collected, and if you want several instances, you'll have to use a container.

Gribouillis 1,391 Programming Explorer Team Colleague

Congratulations, this is good python code. Its naming style however is unusual for python code. You may want to read pep 8, a style guide written for the developpers of the python language trunk. If you follow this style everybody will think you are a very experienced pythonista.

Also string.Template is seldom used. Most programmers would choose the method str.format() for this.

The 5/pi limit explains easily. The polygon perimeter is 10 in your example (n * s). This is the perimeter of a circle with radius 5/pi.

ddanbe commented: Helpful +14
Gribouillis 1,391 Programming Explorer Team Colleague

os.walk('.') means that you are traversing the current working directory with os.walk (as returned by os.getcwd()). If you run the code while in the X0.0 directory, os.walk will never see the X0.05 directory.

The current working directory does not change during the walk. To create psub in a subfolder, you must write

psub = os.path.join(root, 'psub')
with open(psub, 'a') as writer:
    ...

You can also unindent line 5 as the contents of 'top.txt' is stored in the string data.

Gribouillis 1,391 Programming Explorer Team Colleague

Have look at the os.walk() function.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a complete (simplified) running example. Try it in the directory with the .out files

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

# split the code into several functions to lighten it

def main():
    with open('results.txt', 'a') as writer:
        for file in os.listdir('.'):
            if not file.endswith('.out'):
                continue
            with open(file, 'r') as reader:
                handle_reader(reader, writer)

def handle_reader(reader, writer):
    print('reading file:', reader.name, file = writer)
    opt_cnt = 0
    for line in reader:
        s=line.strip()               
        if s=='**** Optimisation achieved ****':
            opt_cnt += 1 # <-- count those lines
            print('optimisation line number', opt_cnt, end ='\n', file = writer)
        else:
            pass

if __name__ == '__main__':
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

There are different ways. 1: declare outline global inside the function

outline = True # when the program starts

def toggle(*args): # args ignored
    global outline # at the top of the function
    if outline == True:
        outline = False
    if outline == False:
        outline = True

2: use a class to hold global variables (avoid global statement)

class glo:
    outline = True # when the program starts

def toggle(*args):
    glo.outline = not glo.outline

3: use a module to hold global variables (especially useful is your program uses more than one file)

# in file glo.py
outline = True

# in your main program
import glo

def toggle(*args):
    glo.outline = not glo.outline

3: Create a class to hold global variables and function and use a single instance

class MyApp:
    def __init__(self):
        self.outline = True

    def toggle(self, *args):
        self.outline = not self.outline

if __name__ == '__main__':
    my_app = MyApp()
    # ...
    Button(..., command = my_app.toggle)
    #...
    foo.mainloop()

4: etc

Gribouillis 1,391 Programming Explorer Team Colleague

Here are some examples of the format() method

Python 3.3.1 (default, Apr 17 2013, 22:32:14) 
[GCC 4.7.3] on linux
>>> "Give me {0} and {2}, said the {1} man".format("bacon", "other", "eggs")
'Give me bacon and eggs, said the other man'
>>> "Give me {0} and {2} eggs, said the {1} man".format("bacon", "other", 5)
'Give me bacon and 5 eggs, said the other man'
>>> "Give me {0} and {2:.2f} eggs, said the {1} man".format("bacon", "other", 5)
'Give me bacon and 5.00 eggs, said the other man'
>>> "Give me {} and {}, said the {} man".format("bacon", "eggs", "other")
'Give me bacon and eggs, said the other man'
>>> "Give me {} and {:.2f} eggs, said the {} man".format("bacon", 5, "other")
'Give me bacon and 5.00 eggs, said the other man'
Gribouillis 1,391 Programming Explorer Team Colleague

It's a very good idea to use parenthesis in your print statements as if you were using a function. It teaches you python 3 at the same time. If you add the line

from __future__ import print_function

as the first statement of your module, it will turn print into a true function. Then you can use

print('#', '-' * num, sep='')

or

print('#', end = '') # don't print a newline
print('-' * num)
Gribouillis 1,391 Programming Explorer Team Colleague

galons_used and gallons_used are 2 different variables. Typo.

Gribouillis 1,391 Programming Explorer Team Colleague

This line uses the string format() method to build a regular expression. For example

>>> import re
>>> wanted = ('cat', 'dog', 'parrot')
>>> regex = '^(?:{0})'.format('|'.join(re.escape(s) for s in wanted))
>>> regex
'^(?:cat|dog|parrot)'

This regex is able to tell if a string starts with any of the words cat, dog and parrot. Read this for a tutorial on regular expressions and this for the format() method.

Gribouillis 1,391 Programming Explorer Team Colleague

What does not n & 1 do?

& is the integer bitwise and operator. When n is an integer, n & 1 is the value of its first bit in base 2. Therefore, n & 1 has value 0 if n is even and 1 if n is odd. not n & 1 has the same meaning as n is even (which is less cryptic but is not python). Another way to say it is n % 2 == 0, but vegaseat thinks he gains some speed.

Gribouillis 1,391 Programming Explorer Team Colleague

Why did you declare i = "" ? Python cannot add a str to an int.

Gribouillis 1,391 Programming Explorer Team Colleague

These books may help you.

ddanbe commented: Nice tip. +14
Gribouillis 1,391 Programming Explorer Team Colleague

Use the subprocess module instead, as described in the documentation.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a small parser. It can be improved by stronger input validation

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

START, END, DATA, EMPTY = range(4)

class ParseError(Exception):
    pass

class Parser(object):
    def __init__(self):
        pass

    def error(self, lineno):
        raise ParseError("Invalid Syntax at line %s" %  str(lineno))

    def parse(self, lines):
        L = [dict()]
        for i, line in enumerate(lines, 1):
            t = self.classify(line, i)
            type, key, data = t
            if type == START:
                L[-1][key] = D = {}
                L.append(D)
            elif type == END:
                del L[-1]
            elif type == DATA:
                L[-1][key] = data
        return L[0]

    def classify(self, line, lineno):
        line = line.strip()
        if not line:
            return (EMPTY, '', '')
        if not(len(line) >= 3 and line[0] == '[' and line[-1] == ']'):
            self.error(lineno)
        if line[1] == '/':
            return (END, line[2:-1], '')
        else:
            i = line.find(']')
            if i == len(line) - 1:
                return (START, line[1:-1], '')
            else:
                return (DATA, line[1:i], line[i+1:-(i+2)])

if __name__ == '__main__':
    example_data = """
[options]
    [user]
        [name]John Doe[/name]
        [age]Age[/age]
    [/user]
    [packages]
        [pkg]
            [version]1.2[/version]
            [summary]Something[/summary]
            [author]John Doe[/author]
        [/pkg]
    [/packages]
[/options]
    """
    from StringIO import StringIO
    from pprint import pprint
    p = Parser()
    f = StringIO(example_data)
    result = p.parse(f)
    pprint(result)

"""my output -->
 {'options': {'packages': {'pkg': {'author': 'John Doe',
                                  'summary': 'Something',
                                  'version': '1.2'}},
             'user': {'age': 'Age', 'name': 'John Doe'}}}
"""
TrustyTony commented: Neat! +12
Gribouillis 1,391 Programming Explorer Team Colleague

Replace [user] by "user":{ and [/user] by },. In the same way, replace [name] with "name":" and [/name] with ",. Do this with all the tags, then call eval()

Gribouillis 1,391 Programming Explorer Team Colleague

First, every value in python is either True or False in a "boolean context".
A boolean context occurs in "if", "while" or other statements

if myvalue:   # <-- boolean context.
    print("value was true")
else:
    print("value was false")

The expression

bool(myvalue)

is either True or False and this tells us whether myvalue is considered true
or false. For example

print( bool(5), bool(2), bool(None), bool(0) )

will print True, True, False, False.

Now

A or B

has value A if bool(A) is True, and value B otherwise.

A and B

has value A if bool(A) is False and value B otherwise.

Gribouillis 1,391 Programming Explorer Team Colleague

Not sure how to handle the comma that is used in some countries as a decimal point.

We could have a concept of "dialect" like the csv module, with fields like "thousand_sep", "decimal_pt".
In the business_fr dialect, thousand_sep would be a space and decimal_pt a comma.

Gribouillis 1,391 Programming Explorer Team Colleague

Hm. I have an old regex in my files which handles also the exponential part

import re

_fregex = re.compile(r"^[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")

def is_floating(f):
    return bool(_fregex.match(f.strip()))


if __name__ == '__main__':
    for f in ('123','-123.45', '+3.14', '+3.', '+.3', '$99.95', '.', '2.4.3',
                '++2.4.3','2.4+'):
        print('%s => %s' % (f, is_floating(f)))

"""
123 => True
-123.45 => True
+3.14 => True
+3. => True
+.3 => True
$99.95 => False
. => False
2.4.3 => False
++2.4.3 => False
2.4+ => False
"""
Gribouillis 1,391 Programming Explorer Team Colleague

This thread may help you, especially the linux solution with the socket pair.

Gribouillis 1,391 Programming Explorer Team Colleague

For the off topic question, read this help .

To make short take any of efficiency, code size, memory effort, programming effort, then

c++ > java > python

Python is easier because it uses duck typing. Java is easier than C++ because of memory management and types management.

c# is very similar to java. Perl has ugly and unmaintainable code.

Gribouillis 1,391 Programming Explorer Team Colleague

This can be understood mainly by examining the history of these languages. C++ was an object oriented development of C at the time where OOP was the new paradigm. Perl started as a system scripting language which was more structured than shell languages. It was then heavily used when internet was based on cgi scripts and there was no other alternative. Php succeeded because it made it possible to include dynamic code in html pages.

Python is different. It started as a general purpose language derived from a small university language called ABC. Its success comes from experience: people realized that using python led to drastic cuts in their programming effort!

frankenfrank commented: useful historical comparison +0
Gribouillis 1,391 Programming Explorer Team Colleague

Write your own parser !

#!/usr/bin/env python
import sys

def handle_args(args):
    s = False
    for a in args:
        if a == '-s':
            if s:
                break
            else:
                s = True
        else:
            yield (s, a)
            s = False
    if s:
        raise RuntimeError('missing argument for -s')

for item in handle_args(sys.argv[1:]):
    print(item)

'''my output --->
(False, 'firstargument')
(False, 'secondargument')
(True, 'thirdargument')
(True, 'fourth')
(False, 'fifth')
(True, 'sixth')
'''
Gribouillis 1,391 Programming Explorer Team Colleague

You can use datetime

>>> import datetime as dt
>>> 
>>> start = dt.datetime.now()
>>> start
datetime.datetime(2013, 7, 16, 0, 21, 17, 748591)
>>> # drink some cofee
... 
>>> death_date = dt.datetime.now()
>>> elapsed = death_date - start
>>> elapsed
datetime.timedelta(0, 81, 872052)
>>> elapsed.total_seconds()
81.872052
Gribouillis 1,391 Programming Explorer Team Colleague

If the searched text is in a single line, you can read the file line by line:

import itertools as itt

def wrong_line(line):
    return 'card 1:' not in line

with open('filename.txt') as ifh:
    result = list(itt.islice(itt.dropwhile(wrong_line, ifh), 1, 3))

# result should be the list ['    ball\n', '    red\n']