Gribouillis 1,391 Programming Explorer Team Colleague

At the end of the wiki page on rotation matrix, there is a link to the Rodrigues rotation formula. This could be what you're looking for.

Gribouillis 1,391 Programming Explorer Team Colleague

The import statement is the mechanism that allows python programs to use libraries. Using libraries is a key feature in any programming language. It allows our programs to benefit from all the work that has been done before by others.

Suppose you're a clever mathematician and you write a python function to factorize integers, then you will write your own module named for example clever_mod and this module will contain a function factorize(). If you publish your module on pypi for example, anybody can download it an use your function by writing

from clever_mod import factorize
result = factorize(9237982379866234)

As of today, there are 97775 python modules in pypi, and an unknown number of available modules that are not on pypi.

sys is a standard library module in python, which means that it is one of the few dozens modules that automatically come with every python install. sys.argv is the list that contains the arguments that your script received from the command line when its execution was launched.

@Dani "Learn python the hard way" is a well known python tutorial. The idea is to get your hands dirty by actually typing every character of the tutorial's programs and examples in order to learn python faster. It sounds like a reasonable idea.

Gribouillis 1,391 Programming Explorer Team Colleague

There is also an implementation at Rosetta code. It is very short, but I haven't used C# for a long time, so I don't know if it is good.

ddanbe commented: Thanks for the tip. :) +15
Gribouillis 1,391 Programming Explorer Team Colleague

Of course it is possible, third party modules need to be installed with a tool such as pip, then they can be imported. For example if we want to use module unidecode that we find in the python package index, we can open a terminal (or cmd console) and type (on my system, pip for python 3 is named pip3)

pip3 install unidecode

Then in python, we can use (tested with python 3)

>>> import unidecode
>>> unidecode.unidecode("Déjà")
'Deja'
Gribouillis 1,391 Programming Explorer Team Colleague

Usually you don't do it, you read and parse the input file by various means, for example

>>> import io
>>> stdin = io.StringIO("""34 78""")                                                                       
>>> line = stdin.readline()
>>> line
'34 78'
>>> x, y = (int(s) for s in line.split()[:2])
>>> x, y
(34, 78)

You could perhaps get a better answer by explaining in which context you want to do this.

Gribouillis 1,391 Programming Explorer Team Colleague

I'd recommend using python setup.py develop first, which will install a symbolic link allowing python to import and use myapp without really installing the package. If you're using a virtualenv, make sure the command uses your virtualenv's python interpreter.

Gribouillis 1,391 Programming Explorer Team Colleague

@Dave_15 I don't quite agree with you. First your post contains no obvious solution for this specific issue. Second I don't have a political agenda telling me to get more people to use python 3. Concerning unicode characters, many python 2 issues simply vanish by using python 3 because unicode is correctly handled in the language's very design. So why waste time solving issues that exist only because one uses an obsolete version of python ?

Gribouillis 1,391 Programming Explorer Team Colleague

Thank you for your support. I'm a python programming enthusiast and I like to share this knowledge!

You could get the IP by regex, for exemple

match = re.search(r'->\s*([0-9]+(?:\.[0-9]+){3})', entry)
if match:
    ip = match.group(1)
tdsan commented: I think this is great, I made one slight modification to the code "(r'->\s", I removed the -> and it seemed to work great through this log file +0
Gribouillis 1,391 Programming Explorer Team Colleague

1- If you want to group when the sequence is unordered, you must sort the input before using groupby()
2- The elif needs the same indention as the corresponding if. Also note that the
cnt results come after all the entries in the group have been exhausted. If you need more information from these entries, you need to store them temporarily. If I understand your question well, you want only the last part of the ip. You could use this code

def entry_to_second(entry):
    return entry.split('.', 1)[0]
newip = []
c = Counter()
logfile = sorted(logfile, key=entry_to_second) # <--- sort the logfile by the second
for key, group in groupby(logfile, key=entry_to_second):
    for entry in group:
        c.update(re.findall(r'[0-9]+(?:\.[0-9]+){3}', entry))
    for ip, cnt in c.items():
        if cnt > 10:
            newip.append(item)
        elif cnt > 100:             # <-- align elif with if. Indentation is critical in python
            a = ip.rsplit(':', 1)[-1]   # <-- last part of ip (the :21 IF there is a :)
            print(a)
    c.clear()
newblist = blacklist + newip
Gribouillis 1,391 Programming Explorer Team Colleague

Well, groupby() works by computing a key for each item and by
grouping together items having the same key. I could as well have written

def get_key_of_line(line):
    return line.split('.', 1)[0]

for key, group in groupby(logfile, key=get_key_of_line):
    ...

Here we suppose that every line starts with a pattern such as
12/30-04:09:41.foo-bar-baz. The grouping key will be 12/30-04:09:41 .
It can be obtained by splitting the line on the first dot. We could
also have obtained it with a regex

def get_key_of_line(line):
    return re.match(r'^[^.]*', line).group(0)

Note that if some lines don't start with a timestamp, these functions
will return the whole line if there is no dot, or the part of the line
before the first dot as the grouping key. You may need to adapt the
function to ensure that identical keys are only returned for consecutive
lines that need to be grouped.

Gribouillis 1,391 Programming Explorer Team Colleague

You could use itertools.groupby and collections.Counter. Something along the lines of

newip = []
c = Counter()
for key, group in groupby(logfile, key=lambda e: e.split('.',1)[0]):
    for entry in group:
        c.update(re.findall(r'[0-9]+(?:\.[0-9]+){3}', entry))
    newip.extend(ip for ip, cnt in c.items() if cnt > 10)
    c.clear()
newblist = blacklist + newip

The groupby() groups consecutive entries that happen in the same second, then the number of occurrences of each ip in this group is calculated.

Gribouillis 1,391 Programming Explorer Team Colleague

You should be using the python interpreter and the pip command from your venv bin/ directory. What's in your venv's bin directory ?

Gribouillis 1,391 Programming Explorer Team Colleague

This is strange, there should be a python interpreter in the virtualenv's bin/ directory. Didn't you create the virtualenv with a python interpreter such as in

virtualenv --python=python2.7 mydir

?

Gribouillis 1,391 Programming Explorer Team Colleague

Try which pip and which python. Both should be in your virtual env's bin directory. django-admin.py should be in the same directory. You can also use locate django-admin.py to find all the files with that name in your file system.

Gribouillis 1,391 Programming Explorer Team Colleague

Hm, no, I can not turn it off once I'm logged in. I'll keep my referer headers on :)

rproffitt commented: Got it. I'll let you test this. Thanks for asking since I learned a thing or two. +0
Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

Various python packages handling dicom images can be found in the Python Package Index https://pypi.python.org/pypi?%3Aaction=search&term=dicom . I don't know them, so I suggest you test them and evaluate them :)

I would start with pydicom for example.

Gribouillis 1,391 Programming Explorer Team Colleague

On my computer, when I write

f = 3.56

in a python program, the following bits are stored in memory

0 10000000000 1100011110101110000101000111101011100001010001111011

This is the IEEE 754 representation of the floating point number 3.56 according to my machine's precision. The corresponding real value is not exactly 3.56, it is

Fraction(8016407336719483, 2251799813685248)

This is equal to

Fraction(356, 100) + Fraction(3, 56294995342131200)

The error is approximately 5.3290705182e-17

Also have a look at https://docs.python.org/3/tutorial/floatingpoint.html

rproffitt commented: That's accurate. +11
cereal commented: well written! +14
Gribouillis 1,391 Programming Explorer Team Colleague

Wikipedia has a <whole page> about G.W.Bush's popularity. As a citizen, I don't like the idea of following the herd and make my opinions about a leader just because most people think the same. This is the mechanism of smear campaign. Of course many things can probably be criticised in his policy such as starting a war in Iraq with thousands of dead people, but on the other hand, I'm not sure ordinary citizens are in a good position to judge. The world is full of conflicts and threats, and everybody knows that if the americans stay at home, the russians or the chinese will take their place.
In a way I think it is too easy to denigrate a leader for people who do nothing but watch the world events on TV.

Gribouillis 1,391 Programming Explorer Team Colleague

In kubuntu 14.04 you can do it with the System Configuration app. See the attached snapshots (sorry it's in french). I can add as many keyboard layouts as needed. I don't know if this will work in more recent versions of kubuntu

Gribouillis 1,391 Programming Explorer Team Colleague

If you want to translate more than one sentence, you can use a loop

if __name__ == "__main__":
    while True:
        x = main()
        print(x)
Gribouillis 1,391 Programming Explorer Team Colleague

I think these compatibility issues will exist forever. The solution
is to stop using python 2.x code. The main sources of backward incompatibility are

  • The print statement without ()
  • The literal strings which are byte strings in 2.x and unicode strings in 3.x
  • The new names of standard library modules.
  • Some details of integer arithmetics

Most of these incompatibilities can be solved by using the 2to3 tool to translate
old python 2 code into python 3.

The reasons for these incompatibilities lie both in python's initial design, with
its own flaws and its C-like culture from the early 90s and in the evolution of
programming and the internet, for example in the first decade of 2000, many
programs adapted to unicode.

ddanbe commented: Surely helps. :) +15
Gribouillis 1,391 Programming Explorer Team Colleague

Try print(pd) to see where this pandas comes from.

Venkata subbara commented: ncountering same error as AttributeError: module 'pandas' has no attribute 'read_file' +0
Gribouillis 1,391 Programming Explorer Team Colleague

@JamesCherrill In your example my 'key' algorithm groups the 3s and the 5s in a one-liner because the keys x//3 for the values (1, 3, 3, 5 ,5, 5, 5) are (0, 1, 1, 1, 1, 1, 1). In python it gives

>>> import itertools as itt
>>> from functools import partial
>>> data = [1, 3, 3, 5, 5, 5, 5]
>>>
>>> def the_key(tol, val):
...     return val // tol
...
>>> print([the_key(3, x) for x in data] )
[0, 1, 1, 1, 1, 1, 1]
>>> print([list(g) for k, g in itt.groupby(data, partial(the_key, 3))])
[[1], [3, 3, 5, 5, 5, 5]]

The awesome part is that this works also with 2D data instead of 1D

Gribouillis 1,391 Programming Explorer Team Colleague

There is a good example at the bottom of this page http://www.python-course.eu/tkinter_checkboxes.php . Take the time to read about the use of tkinter Variable classes.

slate commented: Good answer. Op is not reading the answers anyway. +8
Gribouillis 1,391 Programming Explorer Team Colleague

Rosetta Code has a solution in 27 programming languages https://rosettacode.org/wiki/Gaussian_elimination I didn't test them ...

Also, it may work only for square matrices.

Gribouillis 1,391 Programming Explorer Team Colleague

You could replace line 7 with

while start == 'Start':

and remove the for loop in start, which is not good: loop takes the values 'S', 't', 'a', 'r', 't', then the loop exits. This is probably not what you want.

Gribouillis 1,391 Programming Explorer Team Colleague

Majestic0100 is probably working on another project now as this thread was started 8 years ago!

Gribouillis 1,391 Programming Explorer Team Colleague

There are probably several ways to accomplish this, for example

def method(self, step, a, b):
    if step == 'start':
        do_something(a, b)
        root.after(2000, self.method, 'again',  a, b)
    elif step == 'again':
        something_else(a, b)
        root.after(3000, self.method, 'theend', a, b)
    elif step == 'theend':
        print('This is the end')
Crazyscript77 commented: Thats such a good idea, Im gonna give this a shot right now, thanks so much for your help! +0
Gribouillis 1,391 Programming Explorer Team Colleague

You probably want to call after() with a method argument

class App:
    def test(self):
        print('hello')
        root.after(10000, self.endoftest)

    def endoftest(self):
        print('world')
Crazyscript77 commented: Ill definitely keep this in the toolbag, thanks again! +0
Gribouillis 1,391 Programming Explorer Team Colleague

It is very difficult to run an interactive session with the subprocess module. Some of your statements look suspicious, such as prog.stdout.read() instead of prog.stdout.readline() to read a single line, prog.stdout.seek(0) (prog.stdout is not a regular file). If you write lines to prog.stdin, the lines should end with a newline character, also it would probably be a good idea to call prog.stdin.flush() in order to ensure that the line is not buffered somewhere instead of being sent to the program.

Anyway, IMHO, it would be much better to find a way to call the commands in a non interactive way. You could use the /c option in CMD.exe, or perhaps call netsh command without wrapping it in a CMD command. You can perhaps write a batch file that does a part of the job and you could call this batch file with the subprocess module.

Gribouillis 1,391 Programming Explorer Team Colleague

If you're in windows, try the version from Christoph Gohlke's site Click Here !

Gribouillis 1,391 Programming Explorer Team Colleague

You could also start by reading this Howto from the python documentation Click Here

Gribouillis 1,391 Programming Explorer Team Colleague

I don't think studying my code snippets is good way to learn python. Most of them deal with specialized tips and tricks. More seriously, you could visit the hitchiker's guide to python (among thousands of other sites) to start with.

Using a debugger is not so crucial in python as it is in C++ for example, because there are very few mysterious bugs. Most errors are very easily detected by reading the traceback or printing a few variables.

I don't like python IDEs in general. I work more efficiently with a very good text editor (Kate in linux, but there is a windows version too) which has some tools to work with
python and with projects too. But it is not an IDE.

A very nice way to work, but again the tool I'm using is linux-specific is to have a program that watches changes in my files while I'm editing, and automatically runs the code every time I save it in the editor. It gives an immediate feedback about what I'm doing. The program runs in a terminal next to the editor window and it replaces an IDE. I know there are windows tools to do such things but I don't know them.

AssertNull commented: Good approach. I shall follow it. +5
Gribouillis 1,391 Programming Explorer Team Colleague

Among the various reasons why some people stick with python 2 is the fact that many linux distributions still come with python 2 as their default python interpreter, because many of their system scripts are written in python 2. For example, I'm using kubuntu 14.04, so April 2014, and my default python is 2.7.6.

As a newbie, you would waste a lot of time learning python 2 instead of python 3, so don't do it. On the other hand, python 3 is not very different from python 2. Apart from the print with parenthesis which you mentioned (print was a special statement in python 2 and became a regular function in python 3), the main change is the proper and transparent handling of unicode strings. In python 2, a string such as 'hello world' is a byte string, while in python 3 it is a unicode string. So if you work with python 2, there is a risk that you waste time struggling with conversions between bytes and unicode, and encoding issues. These issues are not very difficult to solve - for a python expert - . The other significant change is the renaming of some library modules. For example Tkinter becomes tkinter.

You could try the 2to3 tool which comes with your python installation, which is an automated script purporting to translate python 2 scripts into python 3 scripts. Here is a video Click Here of a guy using this tool to translate a program.

rproffitt commented: 2to3 times a better answer as well! +10
Gribouillis 1,391 Programming Explorer Team Colleague

If you can attach answer_token.txt to a post, I could try the code.

Gribouillis 1,391 Programming Explorer Team Colleague

Also I don't use a mac. If you're using a mac terminal with ssh to your server, it seems to met that the mac terminal should allow you to scroll.

Gribouillis 1,391 Programming Explorer Team Colleague

Nothing is wrong. Only you must call the method if you want it to be executed. So write p.Sums().

Gribouillis 1,391 Programming Explorer Team Colleague

We don't know who Mr Rioch D'lyma is, nor which book or code you're talking about. Can you please post some links to explain all this ?

Wallace Jnr commented: The Problem being talked about is implementation of the pseudocode with respect to Gaussian Elimination with Scaled Partial Pivoting. +0
Gribouillis 1,391 Programming Explorer Team Colleague

No, the formula is this one Click Here. It is not an equality, it is an equivalent when n is large.

quatrosem commented: that is it! thanks... question answered! +0
Gribouillis 1,391 Programming Explorer Team Colleague

The print() at line 6 needs a end="" argument. Also you could replace all the end="t" with end="", and also " {}" with "{:>5}" which is better because every number will fit in a fixed length zone of 5 characters.

Gribouillis 1,391 Programming Explorer Team Colleague

I've found a play_again() function <here>. It can be adapted to your game by returning a boolean. Also the procedure to initialize the maze and the player must be called again, so I write a reinit() function to do that. Here is the result. It could be a good starting point.

import os
import pygame
import random

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
brown = (205,133,63)
blue = (135,206,250)

FPS = 60
#the dimension of the game
display_width = 680
display_height = 440

# Class for the player
class Player(object):

    def __init__(self):
        self.rect = pygame.Rect(40, 40, 30, 30)

    def move(self, dx, dy):

        # Move each axis separately. Note that this checks for collisions both times.
        if dx != 0:
            self.move_single_axis(dx, 0)
        if dy != 0:
            self.move_single_axis(0, dy)

    def move_single_axis(self, dx, dy):

        # Move the rect
        self.rect.x += dx
        self.rect.y += dy

        # If you collide with a wall, move out based on velocity
        for wall in walls:
            if self.rect.colliderect(wall.rect):
                if dx > 0: # Moving right, Hit the left side of the wall
                    self.rect.right = wall.rect.left
                if dx < 0: # Moving left, Hit the right side of the wall
                    self.rect.left = wall.rect.right
                if dy > 0: # Moving down, Hit the top side of the wall
                    self.rect.bottom = wall.rect.top
                if dy < 0: # Moving up, Hit the bottom side of the wall
                    self.rect.top = wall.rect.bottom

# Class to hold a wall rect
class Wall(object):

    def __init__(self, pos):
        walls.append(self)
        self.rect = …
Gribouillis 1,391 Programming Explorer Team Colleague

If you only want to add an interface argument to your script, use the argparse module like this

import argparse
import time
import os
import sys

def get_bytes(t, iface):
    with open('/sys/class/net/' + iface + '/statistics/' + t + '_bytes', 'r') as f:
        data = f.read();
    return int(data)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="estimates internet interface speed")
    parser.add_argument('iface', metavar='INTERFACE', help='network interface such as eth0 or wlan0')
    args = parser.parse_args()
    (tx_prev, rx_prev) = (0, 0)
    while(True):
        try:
            tx = get_bytes('tx', args.iface)
            rx = get_bytes('rx', args.iface)
        except IOError:
            print("Cannot read the number of bytes received or transmitted through interface {}".format(args.iface))
            break
        if tx_prev > 0:
            tx_speed = tx - tx_prev
            print('TX: ', tx_speed, 'bps')
        if rx_prev > 0:
            rx_speed = rx - rx_prev
            print('RX: ', rx_speed, 'bps')
        time.sleep(1)
        tx_prev = tx
        rx_prev = rx
Gribouillis 1,391 Programming Explorer Team Colleague

Here is the graph with all states allowed. Note that an undirected graph can be drawn, because every move is reversible.

Gribouillis 1,391 Programming Explorer Team Colleague

I drew the following graph, which shows that there are only two routes of equal length. The starting point is the green dot fdwc (farmer, duck, wolf, corn) and the final point is the red dot, labelled 0. The arrows are possible transitions. I removed the yellow states from the graph because they are not acceptable states. For example fw (farmer wolf) is not acceptable because the other bank of the river would contain duck and corn and no farmer. Some of those yellow states could be reached in principle, but the corresponding edges were removed.

Gribouillis 1,391 Programming Explorer Team Colleague

I posted a solution in python for this problem Click Here. The algorithm could perhaps give you some ideas to compare with your code.

Gribouillis 1,391 Programming Explorer Team Colleague

Is there no join() method in c# ?

Gribouillis 1,391 Programming Explorer Team Colleague

@AssertNull running

astyle --style=allman --align-pointer=middle --max-code-length=79 farmer.cpp

does a pretty good job on formatting Builder_1's code

Gribouillis 1,391 Programming Explorer Team Colleague

There is a great module named <psutil> which can tell you all this

import psutil

for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict()
    except psutil.NoSuchProcess:
        pass
    else:
        print(pinfo)
        break

To save the data into tabular format, you could use a simple library such as <tablib>.

Gribouillis 1,391 Programming Explorer Team Colleague

This seems to work, I'm looking for a sequence of characters which are not a newline, or a newline followed by a non alphanumeric character.

import re

content = """
Data:      01 18 01 23 45 67 89 AB  CD EF FE DC BA 98 76 54
           32 10 01 23 45 67 89 AB  CD EF 02 18 67 89 AB CD
           EF FE DC BA 98 76 54 32  10 01 23 45 67 89 AB CD
           EF FE DC BA 03 10 33 33  33 33 33 33 33 33 44 44
           44 44 44 44 44 44 04 10  44 44 44 44 44 44 44 44
           33 33 33 33 33 33 33 33  05 10 55 55 55 55 55 55
           55 55 66 66 66 66 66 66  66 66 FF 10 66 66 66 66
           66 66 66 66 55 55 55 55  55 55 55 55 FF FF
Le:

Data:      31 32 33 34 FF FF FF FF
Le:

Data:
Le:        16
"""

for match in re.finditer(r'Data:((?:[^\n]|\n[^\w])*)', content):
    print(repr(match.group(1)))