Gribouillis 1,391 Programming Explorer Team Colleague

What is your version of python ?

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

You can give your neighbor an electronic cigarette. Many heavy smokers (including me) stopped with the e-cigarette. Give him e-liquid with 11mg nicotine to start with.

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

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

You are wrapping the str class. It means that you want a string, but you don't want the string methods (such as addition or index(), etc). Instead, you want your own methods.

Did you consider subclassing str like this

class Sentence(str):
    __slots__ = ()

    def __new__(cls, *args):
        s = ''.join(str(a) for a in args)
        return str.__new__(cls, s)

    def is_char(self):
        return len(self) == 1 and 97 <= ord(self) < 123

    # etc

You can add more methods, and you have more friendly instances, which can use the usual str methods.

Gribouillis 1,391 Programming Explorer Team Colleague

Add a print statement to start a new line

for score1 in list1:
    for i in range(0,score1):
        print "*",
    print
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

Oh well if you only want to run a command from python you can do

import subprocess
subprocess.call('rsync -rav pi@192.168.2.27:python ~/', shell=True)
Gribouillis 1,391 Programming Explorer Team Colleague

Yes, this is the server program. You must run the client program on the other machine. Of course, the client program must use the server's IP address.

Gribouillis 1,391 Programming Explorer Team Colleague

An extremely simple way to send data from one computer to another is to use an xml_rpc server. Try to run the example code in the python documentation for the xml-rpc protocol. An example server on one machine, the example client on the other machine.

Gribouillis 1,391 Programming Explorer Team Colleague

A configuration file is usually a reasonably sized file, and you can load its content in memory as a python string or a python list of lines. You could cut this string and insert your new content as in this example:

>>> s = "foo a e ueiue uie uie define hosts{ eu ett ul uieue"
>>> idx = s.index('define hosts{')
>>> head, tail = s[:idx], s[idx:]
>>> head
'foo a e ueiue uie uie '
>>> tail
'define hosts{ eu ett ul uieue'
>>> middle = 'foo bar baz qux \n'
>>> head + middle + tail
'foo a e ueiue uie uie foo bar baz qux \ndefine hosts{ eu ett ul uieue'
Gribouillis 1,391 Programming Explorer Team Colleague

Well, as I told you, I never used these tools. The iat man page says

iat - converts many CD-ROM image formats to iso9660.

but your mobile phone is not a CD-ROM, which could explain the error message

This image is not CD IMAGE

There is another tool named bchunk which you could give a try.

Gribouillis 1,391 Programming Explorer Team Colleague

Use

iat my_image.bin > my_new_image.img
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a version using generators.

#!/usr/bin/env python3

"""This script simulates a monkey on a typewriter trying to come up
with one sentence of Shakespeare.

Only the lowercase alpha characters are used and the sentence
is "methinks it is like a weasel"
"""

import random
import string

TEST_STRING = "methinks it is like a weasel"

def ape_sentences():
    """Generate an infinite sequence of random sentences"""
    alphabet = string.ascii_lowercase + " "
    a = len(alphabet)
    n = len(TEST_STRING)
    while True:
        yield ''.join(alphabet[random.randrange(a)] for i in range(n))

def evaluate(sentence):
    """Evaluates the proportion of characters in
    sentence which match characters in the test sentence"""
    r = sum(x == y for (x, y) in zip(sentence, TEST_STRING))
    return r / len(TEST_STRING)

def best_sentences():
    """Generate an infinite sequence of the best sentences
    written by the ape so far.
    """
    best_pair = (0, '')
    for s in ape_sentences():
        best_pair = max(best_pair, (evaluate(s), s))
        yield best_pair

def display(itercnt, sentence, score):
    """Print a number of iterations so far, the best sentence
    and the score of the best sencence.
    """
    print("{:<7} {} {:.4%}".format(str(itercnt), repr(sentence), score))

def main():
    """Simulate the sequence of ape's trials.
    """
    for i, (score, s) in enumerate(best_sentences(), 1):
        if s == TEST_STRING:
            display(i, s, score)
            print('SUCCESS!')
            break
        if i % 1000 == 0:
            display(i, s, score)

if __name__ == "__main__":
    main()
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

It's OK. Only remember that using python standards help you share your code with other python programmers !

Gribouillis 1,391 Programming Explorer Team Colleague

I'd like to read your code Tcll, but I don't have much time. I don't think it is a good idea to use a less pythonic statement in order to save 4e-8 seconds. Remember that

Premature optimization is the root of all evil (Knuth)

Also, meditate the zen of python by typing

>>> import this

For example if vert is a class of geometrical vertices, nobody understands that the expression vert([1.0, 1.0, 1.0]) means that you are storing the vertice somewhere in memory or on file.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes you can do that by subclassing type. Here is a simplified example

>>> class struct(type):
...  def __new__(meta, size, fields):
...   name = 'foo'
...   bases = (object,)
...   D = dict(fields = fields, size = size)
...   return type.__new__(meta, name, bases, D)
...  def __init__(meta, size, fields):
...   pass
... 
>>> vert = struct(12, 'x y')
>>> vert.__class__
<class '__main__.struct'>
>>> data = vert()
>>> data.__class__
<class '__main__.foo'>
>>> data.__class__ == vert
True

However, your code would be better if it was more pythonic. For example isinstance(data, vert) is already better than using __class__. Also reading or writing to file through the __call__ method obscures your code. load() and dump() are pythonic.

Finally, a namedtuple-like implementation of your structs would probably be a good idea as named tuples are simple structures that everybody understands.

Gribouillis 1,391 Programming Explorer Team Colleague

You are trying to do something resembling the collections.namedtuple system. struct() will be a function which returns a class, as namedtuple() returns a new subclass of tuple.

Namedtuple's arguments are the name of the class and the fields name. In struct, you also have a type for each field and a size. I suppose that the size is the sum of the sizes of the item types, so it could be computed automatically. I suggest the following API

def struct(name, fields, types):
    """Return a new type.
    Could be a subtype of namedtuple(name, fields)
    Add class members:
        _field_types: a dictionary field name --> type
        _size: computed once at class creation
    """

# for example

vert = struct('vert', 'x y z', (bf32, bf32, bf32))

# load from and dump to file with a pickle-like syntax:

v = vert.load(file=ifh)

w = vert([1.0, 1.0, 1.0])

w.dump(file=ofh)

load() would be a class method and dump() an instance method.

Gribouillis 1,391 Programming Explorer Team Colleague

At first sight, it seems that you are trying to do some unpythonic design. I'd like to have the code of class struct. Is it an ordinary user defined class or something else ? Also I don't understand this

data = x() # read data from imported file

If x is a class, the statement data = x() means that you are instantiating class x. This is very different from reading data from a file. Also, if you have a good design, you should be able to avoid testing the __class__ member of your instances.

In principle, a class instance can be a class. In fact every class in python is an instance of a metaclass (every python object is an instance), but it is unlikely that you really need this in your program.

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

This is perhaps a more efficient way to generate the same kind of random image

>>> from PIL import Image
>>> import os
>>> size = (600, 600)
>>> im = Image.new('RGB', size)
>>> def ran():
...  return os.urandom(600*600)
... 
>>> pixels = zip(ran(), ran(), ran())
>>> im.putdata(list(pixels))
>>> im.show()

Of course, it does not look like something.

On my computer, im.show() opens the image with a GUI named imagemagick display where there are commands to apply various algorithms to the image. Consider installing imagemagick if you don't have it.

Gribouillis 1,391 Programming Explorer Team Colleague

hm, sourceforge is back.

Slavi commented: it worked =) +5
Gribouillis 1,391 Programming Explorer Team Colleague

If I were you, I would try the boot-repair disk. It always repaired my broken boots in one click. Unfortunately, sourceforge is currently down, and I'm not sure you can download the disk.

Edit: if you have a live ubuntu disk, you can run boot-repair as explained here.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't agree with that. I think it is very convenient to have a main function. As soon as the code in if __name__... has more than a few lines of code, it seems logical to encapsulate it in a function or a class. For example this code may have private variables which don't need to become global variables. As this code thickens, additional functions may become necessary. Also this is coherent with other programming languages. Every C programmer will feel at home with a main() function.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes, it is excellent style.

Gribouillis 1,391 Programming Explorer Team Colleague

Welcome to Daniweb.

Gribouillis 1,391 Programming Explorer Team Colleague

It is very difficult to understand how the expected output is connected to the input. Can you explain this ? Also why did you post this in four different forums (python, java, C, C++)? What do you want exactly ?

Gribouillis 1,391 Programming Explorer Team Colleague

I don't know Runestone Interactive. About languages, my personal opinion is that you are wasting your time learning perl at the same time as python. Both languages can be used for the same tasks and you will end up not using perl because it is older and harder to use than python. There are many languages to learn. You could learn php to start web development.

Gribouillis 1,391 Programming Explorer Team Colleague

We can help, but we cannot do your homework for you. Find the ciphered version of the word 'hello', then try to compute it with the dictionary.

Gribouillis 1,391 Programming Explorer Team Colleague

A regex to match more than 1 space character is

r' {2,}'

To match a dot followed by a letter without consuming the letter, you can use

r'\.(?=[a-zA-Z])'

Always use raw strings(r'...') with regexes, in order to preserve \ characters.

Gribouillis 1,391 Programming Explorer Team Colleague

Marrakech, in october. It was like summer with 35°C (95°F).

Gribouillis 1,391 Programming Explorer Team Colleague

Using itertools.repeat()

from itertools import repeat

def generate_n_chars(n, c):
    return ''.join(repeat(c, n))

print(generate_n_chars(10, 'z'))
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a recursive solution

def generate_n_chars(n, c):
    if n == 0:
        return ''
    n, r = divmod(n, 2)
    s = generate_n_chars(n, c)
    return s + s + c if r else s + s
Gribouillis 1,391 Programming Explorer Team Colleague

Another solution, using the any() builtin function

def is_member(x, a):
    return any(item == x for item in a)
Gribouillis 1,391 Programming Explorer Team Colleague

You must add ix = -1 before the for loop, or enumerate from 1:

ix = 0
for ix, c in enumerate(s, 1): pass
length = ix
Gribouillis 1,391 Programming Explorer Team Colleague

For a string, the following function works

def length(s):
    return 1 + s.rfind(s[-1]) if s else 0

It fails for a list because the list type has no method rfind(). The following works for a list

def length(alist):
    x = object()
    alist.append(x)
    result = alist.index(x)
    del alist[-1]
    return result
Gribouillis 1,391 Programming Explorer Team Colleague

This page Click Here contains many formulas. I suggest to start with Ramanujan's formula.

Gribouillis 1,391 Programming Explorer Team Colleague

I think you could add a launcher to the explorer's context menu by following this tutorial.

Gribouillis 1,391 Programming Explorer Team Colleague

You must indent line 50 to 89 (they belong to the while loop) and you must probably change raspberry[1] at line 79 with raspberryPosition[1].

Gribouillis 1,391 Programming Explorer Team Colleague

Everybody has his/her favorite language. What we lack is an objective criterion to define the best language. It's an ill posed problem. You can

  1. google what is the best programming language.
  2. Think about something else.

Python is a very good general purpose language, from a technical point of vue.

Gribouillis 1,391 Programming Explorer Team Colleague

You say that it won't work, but what is the output ?

Gribouillis 1,391 Programming Explorer Team Colleague

Python says 5.16294852309750916500022794327 e287193 and 6.74114012549907340226906510470 e315652. For example

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from scipy.misc import factorial
>>> x = factorial(65536, exact=True)
>>> s = str(x)
>>> s[-1]
'0'
>>> s[:30]
'516294852309750916500022794327'
>>> len(s)
287194
>>> 
>>> x = 65536 ** 65536
>>> s = str(x)
>>> s[-1]
'6'
>>> s[:30]
'674114012549907340226906510470'
>>> len(s)
315653
Gribouillis 1,391 Programming Explorer Team Colleague

Wouldn't that mean storing the master password somewhere in the file system and compromise security ?

Gribouillis 1,391 Programming Explorer Team Colleague

I have a running version for scilab here. I didn't check that the numerical result is good however

clear;
function func = foo(z, x)
    func = ((0.6369).*sin(z.*sin(x)).*sin(x))
endfunction

function simpson = simpson(f, a, b, n)
h  = (b-a)/n;
i   = 0;
fks = 0.0;
while (i<=n)
    xk = a+i*h;
    if i==or(0, n) then
        fk = f(xk);
    elseif (i-fix(i./2).*2)== 1 then
        // https://help.scilab.org/docs/5.5.0/en_US/m2sci_rem.html
        fk = 4.*f(xk);
    else
        fk = 2.*f(xk);
    end
    fks = fks + fk;
    i = i + 1;
end
simpson = (h./3).*fks;
endfunction

function func = baz(x)
    func = foo(1, x)
endfunction

simpson(baz, 0, 1.57, 10)
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest that you call the following function as soon as you get a cursor object:

from collections import namedtuple
from operator import attrgetter
import itertools

def load_programs(cur):
    """Return a dictionary channel -> list of program records"""
    tp = namedtuple('record', 'channel title start_date stop_date')
    cur.execute("""SELECT channel, title, start_date, stop_date FROM programs""")
    L = [tp(row[0].encode('ascii'),row[1].encode('ascii'), row[2], row[3])
            for row in cur.fetchall()]
    L = sorted(L, key=attrgetter('channel'))
    result = dict()
    for channel, group in itertools.groupby(L, key=attrgetter('channel')):
        result[channel] = list(group)
    return result

This will get you a dictionary object mapping each channel to the list of programs for this channel. Then you do what you want with this dictionary. For example try this

from pprint import pprint
...
programdict = load_programs(cur)
pprint(programdict)
Gribouillis 1,391 Programming Explorer Team Colleague

I want to print for each title outside of the loop.

This is meaningless. It does not matter if the titles are printed inside or outside of the loop (which loop ? why ?) as long as the program prints the correct output. Change your priorities: first the program must work as expected, then the secondary details.

Gribouillis 1,391 Programming Explorer Team Colleague

There is no syntax error for my python. However, remove lines 3 to 8 if you want, they're not used.

Are you sure that the shebang works ?