<commit_before>import ntpath
from test.test_support import verbose, TestFailed
import os

errors = 0

def tester(fn, wantResult):
    global errors
    fn = fn.replace("\\", "\\\\")
    gotResult = eval(fn)
    if wantResult != gotResult:
        print "error!"
        print "evaluated: " + str(fn)
        print "should be: " + str(wantResult)
        print " returned: " + str(gotResult)
        print ""
        errors = errors + 1

tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
tester('ntpath.splitext(".ext")', ('.ext', ''))
tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
tester('ntpath.splitext("")', ('', ''))
tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))

tester('ntpath.splitdrive("c:\\foo\\bar")',
       ('c:', '\\foo\\bar'))
tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")',
       ('\\\\conky\\mountpoint', '\\foo\\bar'))
tester('ntpath.splitdrive("c:/foo/bar")',
       ('c:', '/foo/bar'))
tester('ntpath.splitunc("//conky/mountpoint/foo/bar")',
       ('//conky/mountpoint', '/foo/bar'))

tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
       ('\\\\conky\\mountpoint\\foo', 'bar'))

tester('ntpath.split("c:\\")', ('c:\\', ''))
tester('ntpath.split("\\\\conky\\mountpoint\\")',
       ('\\\\conky\\mountpoint', ''))

tester('ntpath.split("c:/")', ('c:/', ''))
tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', ''))

tester('ntpath.isabs("c:\\")', 1)
tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1)
tester('ntpath.isabs("\\foo")', 1)
tester('ntpath.isabs("\\foo\\bar")', 1)

tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
       "/home/swen")
tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
       "\\home\\swen\\")
tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
       "/home/swen/spam")

tester('ntpath.join("")', '')
tester('ntpath.join("", "", "")', '')
tester('ntpath.join("a")', 'a')
tester('ntpath.join("/a")', '/a')
tester('ntpath.join("\\a")', '\\a')
tester('ntpath.join("a:")', 'a:')
tester('ntpath.join("a:", "b")', 'a:b')
tester('ntpath.join("a:", "/b")', 'a:/b')
tester('ntpath.join("a:", "\\b")', 'a:\\b')
tester('ntpath.join("a", "/b")', '/b')
tester('ntpath.join("a", "\\b")', '\\b')
tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
tester('ntpath.join("a", "b", "\\c")', '\\c')
tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep')
tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b')
tester("ntpath.join('c:', '/a')", 'c:/a')
tester("ntpath.join('c:/', '/a')", 'c:/a')
tester("ntpath.join('c:/a', '/b')", '/b')
tester("ntpath.join('c:', 'd:/')", 'd:/')
tester("ntpath.join('c:/', 'd:/')", 'd:/')
tester("ntpath.join('c:/', 'd:/a/b')", 'd:/a/b')

tester("ntpath.join('')", '')
tester("ntpath.join('', '', '', '', '')", '')
tester("ntpath.join('a')", 'a')
tester("ntpath.join('', 'a')", 'a')
tester("ntpath.join('', '', '', '', 'a')", 'a')
tester("ntpath.join('a', '')", 'a\\')
tester("ntpath.join('a', '', '', '', '')", 'a\\')
tester("ntpath.join('a\\', '')", 'a\\')
tester("ntpath.join('a\\', '', '', '', '')", 'a\\')

tester("ntpath.normpath('A//////././//.//B')", r'A\B')
tester("ntpath.normpath('A/./B')", r'A\B')
tester("ntpath.normpath('A/foo/../B')", r'A\B')
tester("ntpath.normpath('C:A//B')", r'C:A\B')
tester("ntpath.normpath('D:A/./B')", r'D:A\B')
tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B')

tester("ntpath.normpath('C:///A//B')", r'C:\A\B')
tester("ntpath.normpath('D:///A/./B')", r'D:\A\B')
tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B')

tester("ntpath.normpath('..')", r'..')
tester("ntpath.normpath('.')", r'.')
tester("ntpath.normpath('')", r'.')
tester("ntpath.normpath('/')", '\\')
tester("ntpath.normpath('c:/')", 'c:\\')
tester("ntpath.normpath('/../.././..')", '\\')
tester("ntpath.normpath('c:/../../..')", 'c:\\')
tester("ntpath.normpath('../.././..')", r'..\..\..')
tester("ntpath.normpath('K:../.././..')", r'K:..\..\..')
tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')

oldenv = os.environ.copy()
try:
    os.environ.clear()
    os.environ["foo"] = "bar"
    os.environ["{foo"] = "baz1"
    os.environ["{foo}"] = "baz2"
    tester('ntpath.expandvars("foo")', "foo")
    tester('ntpath.expandvars("$foo bar")', "bar bar")
    tester('ntpath.expandvars("${foo}bar")', "barbar")
    tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
    tester('ntpath.expandvars("$bar bar")', "$bar bar")
    tester('ntpath.expandvars("$?bar")', "$?bar")
    tester('ntpath.expandvars("${foo}bar")', "barbar")
    tester('ntpath.expandvars("$foo}bar")', "bar}bar")
    tester('ntpath.expandvars("${foo")', "${foo")
    tester('ntpath.expandvars("${{foo}}")', "baz1}")
    tester('ntpath.expandvars("$foo$foo")', "barbar")
    tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
    tester('ntpath.expandvars("%foo% bar")', "bar bar")
    tester('ntpath.expandvars("%foo%bar")', "barbar")
    tester('ntpath.expandvars("%foo%%foo%")', "barbar")
    tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
    tester('ntpath.expandvars("%?bar%")', "%?bar%")
    tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
    tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
finally:
    os.environ.clear()
    os.environ.update(oldenv)

# ntpath.abspath() can only be used on a system with the "nt" module
# (reasonably), so we protect this test with "import nt".  This allows
# the rest of the tests for the ntpath module to be run to completion
# on any platform, since most of the module is intended to be usable
# from any platform.
try:
    import nt
except ImportError:
    pass
else:
    tester('ntpath.abspath("C:\\")', "C:\\")

currentdir = os.path.split(os.getcwd())[-1]
tester('ntpath.relpath("a")', 'a')
tester('ntpath.relpath(os.path.abspath("a"))', 'a')
tester('ntpath.relpath("a/b")', 'a\\b')
tester('ntpath.relpath("../a/b")', '..\\a\\b')
tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
tester('ntpath.relpath("a", "a")', '.')

if errors:
    raise TestFailed(str(errors) + " errors.")
elif verbose:
    print "No errors.  Thank your lucky stars."
<commit_msg>Changed test so it no longer runs as a side effect of importing.<commit_after>import ntpath
import os
from test.test_support import verbose, TestFailed
import test.test_support as test_support
import unittest

def tester(fn, wantResult):
    fn = fn.replace("\\", "\\\\")
    gotResult = eval(fn)
    if wantResult != gotResult:
        raise TestFailed, "%s should return: %s but returned: %s" \
              %(str(fn), str(wantResult), str(gotResult))

class TestNtpath(unittest.TestCase):
    def test_splitext(self):
        tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
        tester('ntpath.splitext("/foo/foo.ext")', ('/foo/foo', '.ext'))
        tester('ntpath.splitext(".ext")', ('.ext', ''))
        tester('ntpath.splitext("\\foo.ext\\foo")', ('\\foo.ext\\foo', ''))
        tester('ntpath.splitext("foo.ext\\")', ('foo.ext\\', ''))
        tester('ntpath.splitext("")', ('', ''))
        tester('ntpath.splitext("foo.bar.ext")', ('foo.bar', '.ext'))
        tester('ntpath.splitext("xx/foo.bar.ext")', ('xx/foo.bar', '.ext'))
        tester('ntpath.splitext("xx\\foo.bar.ext")', ('xx\\foo.bar', '.ext'))
        tester('ntpath.splitext("c:a/b\\c.d")', ('c:a/b\\c', '.d'))

    def test_splitdrive(self):
        tester('ntpath.splitdrive("c:\\foo\\bar")',
               ('c:', '\\foo\\bar'))
        tester('ntpath.splitdrive("c:/foo/bar")',
               ('c:', '/foo/bar'))

    def test_splitunc(self):
        tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")',
               ('\\\\conky\\mountpoint', '\\foo\\bar'))
        tester('ntpath.splitunc("//conky/mountpoint/foo/bar")',
               ('//conky/mountpoint', '/foo/bar'))

    def test_split(self):
        tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
        tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
               ('\\\\conky\\mountpoint\\foo', 'bar'))

        tester('ntpath.split("c:\\")', ('c:\\', ''))
        tester('ntpath.split("\\\\conky\\mountpoint\\")',
               ('\\\\conky\\mountpoint', ''))

        tester('ntpath.split("c:/")', ('c:/', ''))
        tester('ntpath.split("//conky/mountpoint/")', ('//conky/mountpoint', ''))

    def test_isabs(self):
        tester('ntpath.isabs("c:\\")', 1)
        tester('ntpath.isabs("\\\\conky\\mountpoint\\")', 1)
        tester('ntpath.isabs("\\foo")', 1)
        tester('ntpath.isabs("\\foo\\bar")', 1)

    def test_commonprefix(self):
        tester('ntpath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
               "/home/swen")
        tester('ntpath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
               "\\home\\swen\\")
        tester('ntpath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
               "/home/swen/spam")

    def test_join(self):
        tester('ntpath.join("")', '')
        tester('ntpath.join("", "", "")', '')
        tester('ntpath.join("a")', 'a')
        tester('ntpath.join("/a")', '/a')
        tester('ntpath.join("\\a")', '\\a')
        tester('ntpath.join("a:")', 'a:')
        tester('ntpath.join("a:", "b")', 'a:b')
        tester('ntpath.join("a:", "/b")', 'a:/b')
        tester('ntpath.join("a:", "\\b")', 'a:\\b')
        tester('ntpath.join("a", "/b")', '/b')
        tester('ntpath.join("a", "\\b")', '\\b')
        tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
        tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
        tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
        tester('ntpath.join("a", "b", "\\c")', '\\c')
        tester('ntpath.join("d:\\", "\\pleep")', 'd:\\pleep')
        tester('ntpath.join("d:\\", "a", "b")', 'd:\\a\\b')
        tester("ntpath.join('c:', '/a')", 'c:/a')
        tester("ntpath.join('c:/', '/a')", 'c:/a')
        tester("ntpath.join('c:/a', '/b')", '/b')
        tester("ntpath.join('c:', 'd:/')", 'd:/')
        tester("ntpath.join('c:/', 'd:/')", 'd:/')
        tester("ntpath.join('c:/', 'd:/a/b')", 'd:/a/b')

        tester("ntpath.join('')", '')
        tester("ntpath.join('', '', '', '', '')", '')
        tester("ntpath.join('a')", 'a')
        tester("ntpath.join('', 'a')", 'a')
        tester("ntpath.join('', '', '', '', 'a')", 'a')
        tester("ntpath.join('a', '')", 'a\\')
        tester("ntpath.join('a', '', '', '', '')", 'a\\')
        tester("ntpath.join('a\\', '')", 'a\\')
        tester("ntpath.join('a\\', '', '', '', '')", 'a\\')

    def test_normpath(self):
        tester("ntpath.normpath('A//////././//.//B')", r'A\B')
        tester("ntpath.normpath('A/./B')", r'A\B')
        tester("ntpath.normpath('A/foo/../B')", r'A\B')
        tester("ntpath.normpath('C:A//B')", r'C:A\B')
        tester("ntpath.normpath('D:A/./B')", r'D:A\B')
        tester("ntpath.normpath('e:A/foo/../B')", r'e:A\B')

        tester("ntpath.normpath('C:///A//B')", r'C:\A\B')
        tester("ntpath.normpath('D:///A/./B')", r'D:\A\B')
        tester("ntpath.normpath('e:///A/foo/../B')", r'e:\A\B')

        tester("ntpath.normpath('..')", r'..')
        tester("ntpath.normpath('.')", r'.')
        tester("ntpath.normpath('')", r'.')
        tester("ntpath.normpath('/')", '\\')
        tester("ntpath.normpath('c:/')", 'c:\\')
        tester("ntpath.normpath('/../.././..')", '\\')
        tester("ntpath.normpath('c:/../../..')", 'c:\\')
        tester("ntpath.normpath('../.././..')", r'..\..\..')
        tester("ntpath.normpath('K:../.././..')", r'K:..\..\..')
        tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
        tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')

    def test_expandvars(self):
        oldenv = os.environ.copy()
        try:
            os.environ.clear()
            os.environ["foo"] = "bar"
            os.environ["{foo"] = "baz1"
            os.environ["{foo}"] = "baz2"
            tester('ntpath.expandvars("foo")', "foo")
            tester('ntpath.expandvars("$foo bar")', "bar bar")
            tester('ntpath.expandvars("${foo}bar")', "barbar")
            tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
            tester('ntpath.expandvars("$bar bar")', "$bar bar")
            tester('ntpath.expandvars("$?bar")', "$?bar")
            tester('ntpath.expandvars("${foo}bar")', "barbar")
            tester('ntpath.expandvars("$foo}bar")', "bar}bar")
            tester('ntpath.expandvars("${foo")', "${foo")
            tester('ntpath.expandvars("${{foo}}")', "baz1}")
            tester('ntpath.expandvars("$foo$foo")', "barbar")
            tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
            tester('ntpath.expandvars("%foo% bar")', "bar bar")
            tester('ntpath.expandvars("%foo%bar")', "barbar")
            tester('ntpath.expandvars("%foo%%foo%")', "barbar")
            tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
            tester('ntpath.expandvars("%?bar%")', "%?bar%")
            tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
            tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
        finally:
            os.environ.clear()
            os.environ.update(oldenv)

    def test_abspath(self):
        # ntpath.abspath() can only be used on a system with the "nt" module
        # (reasonably), so we protect this test with "import nt".  This allows
        # the rest of the tests for the ntpath module to be run to completion
        # on any platform, since most of the module is intended to be usable
        # from any platform.
        try:
            import nt
        except ImportError:
            pass
        else:
            tester('ntpath.abspath("C:\\")', "C:\\")

    def test_relpath(self):
        currentdir = os.path.split(os.getcwd())[-1]
        tester('ntpath.relpath("a")', 'a')
        tester('ntpath.relpath(os.path.abspath("a"))', 'a')
        tester('ntpath.relpath("a/b")', 'a\\b')
        tester('ntpath.relpath("../a/b")', '..\\a\\b')
        tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
        tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
        tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
        tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
        tester('ntpath.relpath("a", "a")', '.')

def test_main():
    test_support.run_unittest(TestNtpath)

if __name__ == "__main__":
    unittest.main()
<|endoftext|>


<commit_before>import time
from fork import *

def fib(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

@cpu_bound_fork
def fib_fork(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

@contagious
@cpu_bound_fork
def contagious_fib_fork(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

def test_cpu_bound(n):
    print('##### test_cpu_bound #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fib(i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_contagious_decorator(n):
    print('##### test_cpu_bound_contagious_decorator #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += contagious_fib_fork(i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_contagious_directly(n):
    print('##### test_cpu_bound_contagious_directly #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fork_contagious(fib, i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_noncontagious(n):
    print('##### test_cpu_bound_noncontagious #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fork_noncontagious(contagious_fib_fork, i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

test_cpu_bound(n=30)
test_cpu_bound_contagious_decorator(n=30)
test_cpu_bound_contagious_directly(n=30)
test_cpu_bound_noncontagious(n=30)
<commit_msg>added io-bound tests for contagious futures<commit_after>import time
from fork import *

@cpu_bound
def fib(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

@cpu_bound_fork
def fib_fork(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

@contagious
@cpu_bound_fork
def contagious_fib_fork(n):
    return 1 if n <= 1 else fib(n-1) + fib(n-2)

@io_bound
def webservice():
    time.sleep(0.02)
    return 'result'

@io_bound_fork
def webservice_fork():
    time.sleep(0.02)
    return 'result'

@contagious
@io_bound_fork
def contagious_webservice_fork():
    time.sleep(0.02)
    return 'result'

def test_cpu_bound(n):
    print('##### test_cpu_bound #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fib(i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_contagious_decorator(n):
    print('##### test_cpu_bound_contagious_decorator #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += contagious_fib_fork(i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_contagious_directly(n):
    print('##### test_cpu_bound_contagious_directly #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fork_contagious(fib, i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_cpu_bound_noncontagious(n):
    print('##### test_cpu_bound_noncontagious #####')
    start = time.time()
    seq_result = 0
    for i in range(n):
        seq_result += fib(i)
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = 0
    for i in range(n):
        par_result += fork_noncontagious(contagious_fib_fork, i)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_io_bound(n):
    print('##### test_io_bound #####')
    start = time.time()
    seq_result = ''
    for i in range(n):
        seq_result += webservice()
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = ''
    for i in range(n):
        par_result += webservice_fork()
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_io_bound_contagious_decorator(n):
    print('##### test_io_bound_contagious_decorator #####')
    start = time.time()
    seq_result = ''
    for i in range(n):
        seq_result += webservice()
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = ''
    for i in range(n):
        par_result += contagious_webservice_fork()
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_io_bound_contagious_directly(n):
    print('##### test_io_bound_contagious_directly #####')
    start = time.time()
    seq_result = ''
    for i in range(n):
        seq_result += webservice()
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = ''
    for i in range(n):
        par_result += fork_contagious(webservice)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

def test_io_bound_noncontagious(n):
    print('##### test_io_bound_noncontagious #####')
    start = time.time()
    seq_result = ''
    for i in range(n):
        seq_result += webservice()
    str(seq_result)
    end = time.time()
    print('sequential:', end-start)

    start = time.time()
    par_result = ''
    for i in range(n):
        par_result += fork_noncontagious(contagious_webservice_fork)
    str(par_result)
    end = time.time()
    print('parallel:  ', end-start)

    if seq_result == seq_result:
        print('results are equal')
    else:
        print('results are unequal')
        print('sequential:', seq_result)
        print('parallel:  ', seq_result)

test_cpu_bound(n=30)
test_cpu_bound_contagious_decorator(n=30)
test_cpu_bound_contagious_directly(n=30)
test_cpu_bound_noncontagious(n=30)
test_io_bound(n=30)
test_io_bound_contagious_decorator(n=30)
test_io_bound_contagious_directly(n=30)
test_io_bound_noncontagious(n=30)
<|endoftext|>


<commit_before>"""
Name Server and helper functions.

Pyro - Python Remote Objects.  Copyright by Irmen de Jong (irmen@razorvine.net).
"""

from __future__ import with_statement
import re, logging, socket, sys
from Pyro4 import constants, core, socketutil
from Pyro4.threadutil import RLock, Thread
from Pyro4.errors import PyroError, NamingError
import Pyro4

__all__=["locateNS", "resolve", "startNS"]

if sys.version_info>=(3, 0):
    basestring=str

log=logging.getLogger("Pyro.naming")

class NameServer(object):
    """Pyro name server. Provides a simple flat name space to map logical object names to Pyro URIs."""

    def __init__(self):
        self.namespace={}
        self.lock=RLock()

    def lookup(self, name):
        """Lookup the given name, returns an URI if found"""
        try:
            return core.URI(self.namespace[name])
        except KeyError:
            raise NamingError("unknown name: "+name)

    def register(self, name, uri, safe=False):
        """Register a name with an URI. If safe is true, name cannot be registered twice.
        The uri can be a string or an URI object."""
        if isinstance(uri, core.URI):
            uri=uri.asString()
        elif not isinstance(uri, basestring):
            raise TypeError("only URIs or strings can be registered")
        else:
            core.URI(uri)  # check if uri is valid
        if not isinstance(name, basestring):
            raise TypeError("name must be a str")
        if safe and name in self.namespace:
            raise NamingError("name already registered: "+name)
        with self.lock:
            self.namespace[name]=uri

    def remove(self, name=None, prefix=None, regex=None):
        """Remove a registration. returns the number of items removed."""
        if name and name in self.namespace and name!=constants.NAMESERVER_NAME:
            with self.lock:
                del self.namespace[name]
            return 1
        if prefix:
            with self.lock:
                items=list(self.list(prefix=prefix).keys())
                if constants.NAMESERVER_NAME in items:
                    items.remove(constants.NAMESERVER_NAME)
                for item in items:
                    del self.namespace[item]
                return len(items)
        if regex:
            with self.lock:
                items=list(self.list(regex=regex).keys())
                if constants.NAMESERVER_NAME in items:
                    items.remove(constants.NAMESERVER_NAME)
                for item in items:
                    del self.namespace[item]
                return len(items)
        return 0

    def list(self, prefix=None, regex=None):
        """Retrieve the registered items as a dictionary name-to-URI. The URIs
        in the resulting dict are strings, not URI objects.
        You can filter by prefix or by regex."""
        with self.lock:
            if prefix:
                result={}
                for name in self.namespace:
                    if name.startswith(prefix):
                        result[name]=self.namespace[name]
                return result
            elif regex:
                result={}
                try:
                    regex=re.compile(regex+"$")  # add end of string marker
                except re.error:
                    x=sys.exc_info()[1]
                    raise NamingError("invalid regex: "+str(x))
                else:
                    for name in self.namespace:
                        if regex.match(name):
                            result[name]=self.namespace[name]
                    return result
            else:
                # just return (a copy of) everything
                return self.namespace.copy()

    def ping(self):
        """A simple test method to check if the name server is running correctly."""
        pass

class NameServerDaemon(core.Daemon):
    """Daemon that contains the Name Server."""
    def __init__(self, host=None, port=None, unixsocket=None):
        if Pyro4.config.DOTTEDNAMES:
            raise PyroError("Name server won't start with DOTTEDNAMES enabled because of security reasons")
        if host is None:
            host=Pyro4.config.HOST
        if port is None:
            port=Pyro4.config.NS_PORT
        super(NameServerDaemon, self).__init__(host, port, unixsocket)
        self.nameserver=NameServer()
        self.register(self.nameserver, constants.NAMESERVER_NAME)
        self.nameserver.register(constants.NAMESERVER_NAME, self.uriFor(self.nameserver))
        log.info("nameserver daemon created")

    def close(self):
        super(NameServerDaemon, self).close()
        self.nameserver=None

    def __enter__(self):
        if not self.nameserver:
            raise PyroError("cannot reuse this object")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.nameserver=None
        return super(NameServerDaemon, self).__exit__(exc_type, exc_value, traceback)

class BroadcastServer(object):
    if sys.version_info>=(3, 0):
        REQUEST_NSURI=bytes("GET_NSURI", "ASCII")
    else:
        REQUEST_NSURI="GET_NSURI"

    def __init__(self, nsUri, bchost=None, bcport=None):
        self.nsUri=nsUri
        if bcport is None:
            bcport=Pyro4.config.NS_BCPORT
        if bchost is None:
            bchost=Pyro4.config.NS_BCHOST
        if ":" in nsUri.host:  # ipv6
            bchost = bchost or "::"
            self.sock=Pyro4.socketutil.createBroadcastSocket((bchost, bcport, 0, 0), reuseaddr=Pyro4.config.SOCK_REUSE, timeout=2.0)
        else:
            self.sock=Pyro4.socketutil.createBroadcastSocket((bchost, bcport), reuseaddr=Pyro4.config.SOCK_REUSE, timeout=2.0)
        self._sockaddr=self.sock.getsockname()
        bchost=bchost or self._sockaddr[0]
        bcport=bcport or self._sockaddr[1]
        if ":" in bchost:  # ipv6
            self.locationStr="[%s]:%d" % (bchost, bcport)
        else:
            self.locationStr="%s:%d" % (bchost, bcport)
        log.info("ns broadcast server created on %s", self.locationStr)
        self.running=True

    def close(self):
        log.debug("ns broadcast server closing")
        self.running=False
        self.sock.close()

    def getPort(self):
        return self.sock.getsockname()[1]

    def fileno(self):
        return self.sock.fileno()

    def runInThread(self):
        """Run the broadcast server loop in its own thread. This is mainly for Jython,
        which has problems with multiplexing it using select() with the Name server itself."""
        thread=Thread(target=self.__requestLoop)
        thread.setDaemon(True)
        thread.start()
        log.debug("broadcast server loop running in own thread")

    def __requestLoop(self):
        while self.running:
            self.processRequest()
        log.debug("broadcast server loop terminating")

    def processRequest(self):
        try:
            data, addr=self.sock.recvfrom(100)
            if data==self.REQUEST_NSURI:
                responsedata=core.URI(self.nsUri)
                if responsedata.host=="0.0.0.0":
                    # replace INADDR_ANY address by the interface IP adress that connects to the requesting client
                    try:
                        interface_ip=socketutil.getInterfaceAddress(addr[0])
                        responsedata.host=interface_ip
                    except socket.error:
                        pass
                log.debug("responding to broadcast request from %s: interface %s", addr[0], responsedata.host)
                responsedata=str(responsedata)
                if sys.version_info>=(3, 0):
                    responsedata=bytes(responsedata, "iso-8859-1")
                self.sock.sendto(responsedata, 0, addr)
        except socket.error:
            pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

def startNSloop(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None, unixsocket=None):
    """utility function that starts a new Name server and enters its requestloop."""
    daemon=NameServerDaemon(host, port, unixsocket)
    nsUri=daemon.uriFor(daemon.nameserver)
    bcserver=None
    if unixsocket:
        hostip="Unix domain socket"
    else:
        hostip=daemon.sock.getsockname()[0]
        if hostip.startswith("127."):
            print("Not starting broadcast server for localhost.")
            log.info("Not starting NS broadcast server because NS is bound to localhost")
            enableBroadcast=False
        if enableBroadcast:
            bcserver=BroadcastServer(nsUri, bchost, bcport)
            print("Broadcast server running on %s" % bcserver.locationStr)
            bcserver.runInThread()
    print("NS running on %s (%s)" % (daemon.locationStr, hostip))
    print("URI = %s" % nsUri)
    try:
        daemon.requestLoop()
    finally:
        daemon.close()
        if bcserver is not None:
            bcserver.close()
    print("NS shut down.")

def startNS(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None, unixsocket=None):
    """utility fuction to quickly get a Name server daemon to be used in your own event loops.
    Returns (nameserverUri, nameserverDaemon, broadcastServer)."""
    daemon=NameServerDaemon(host, port, unixsocket)
    bcserver=None
    nsUri=daemon.uriFor(daemon.nameserver)
    if not unixsocket:
        hostip=daemon.sock.getsockname()[0]
        if hostip.startswith("127."):
            # not starting broadcast server for localhost.
            enableBroadcast=False
        if enableBroadcast:
            bcserver=BroadcastServer(nsUri, bchost, bcport)
    return nsUri, daemon, bcserver

def locateNS(host=None, port=None):
    """Get a proxy for a name server somewhere in the network."""
    def broadcastloop(bindaddr, sendaddr):
        sock=Pyro4.socketutil.createBroadcastSocket(bindaddr, reuseaddr=Pyro4.config.SOCK_REUSE, timeout=0.7)
        for _ in range(2):
            try:
                sock.sendto(BroadcastServer.REQUEST_NSURI, 0, sendaddr)
                data, _=sock.recvfrom(100)
                sock.close()
                if sys.version_info>=(3,0):
                    data=data.decode("iso-8859-1")
                log.debug("located NS: %s", data)
                return core.Proxy(data)
            except socket.timeout:
                continue
        sock.close()
        return None

    if host is None:
        # first try localhost if we have a good chance of finding it there
        if Pyro4.config.NS_HOST in ("localhost", "::1") or Pyro4.config.NS_HOST.startswith("127."):
            host = Pyro4.config.NS_HOST
            if ":" in host:   # ipv6
                host="[%s]" % host
            uristring="PYRO:%s@%s:%d" % (constants.NAMESERVER_NAME, host, port or Pyro4.config.NS_PORT)
            log.debug("locating the NS: %s", uristring)
            proxy=core.Proxy(uristring)
            try:
                proxy.ping()
                log.debug("located NS")
                return proxy
            except PyroError:
                pass
        # broadcast lookup
        if not port:
            port=Pyro4.config.NS_BCPORT
        log.debug("IPv6 broadcast locate")
        result = broadcastloop(("::", 0, 0, 0), ("ff02::1", port, 0, 0))
        if result is not None:
            return result
        log.debug("ipv6 broadcast locate failed")
        log.debug("ipv4 broadcast locate")
        result = broadcastloop(("0.0.0.0", 0), ("<broadcast>", port))
        if result is not None:
            return result
        log.debug("ipv4 broadcast locate failed, try direct connection on NS_HOST")
        # broadcast failed, try PYRO directly on specific host
        host=Pyro4.config.NS_HOST
        port=Pyro4.config.NS_PORT
    # pyro direct lookup
    if not port:
        port=Pyro4.config.NS_PORT
    if ":" in host:
        host = "[%s]" % host
    if core.URI.isUnixsockLocation(host):
        uristring="PYRO:%s@%s" % (constants.NAMESERVER_NAME, host)
    else:
        uristring="PYRO:%s@%s:%d" % (constants.NAMESERVER_NAME, host, port)
    uri=core.URI(uristring)
    log.debug("locating the NS: %s", uri)
    proxy=core.Proxy(uri)
    try:
        proxy.ping()
        log.debug("located NS")
        return proxy
    except PyroError:
        raise Pyro4.errors.NamingError("Failed to locate the nameserver")

def resolve(uri):
    """Resolve a 'magic' uri (PYRONAME) into the direct PYRO uri."""
    if isinstance(uri, basestring):
        uri=core.URI(uri)
    elif not isinstance(uri, core.URI):
        raise TypeError("can only resolve Pyro URIs")
    if uri.protocol=="PYRO":
        return uri
    log.debug("resolving %s", uri)
    if uri.protocol=="PYRONAME":
        nameserver=locateNS(uri.host, uri.port)
        uri=nameserver.lookup(uri.object)
        nameserver._pyroRelease()
        return uri
    else:
        raise PyroError("invalid uri protocol")

def main(args):
    from optparse import OptionParser
    parser=OptionParser()
    parser.add_option("-n", "--host", dest="host", help="hostname to bind server on")
    parser.add_option("-p", "--port", dest="port", type="int", help="port to bind server on (0=random)")
    parser.add_option("-u","--unixsocket", help="Unix domain socket name to bind server on")
    parser.add_option("", "--bchost", dest="bchost", help="hostname to bind broadcast server on (default is \"\")")
    parser.add_option("", "--bcport", dest="bcport", type="int",
                      help="port to bind broadcast server on (0=random)")
    parser.add_option("-x", "--nobc", dest="enablebc", action="store_false", default=True,
                      help="don't start a broadcast server")
    options, args = parser.parse_args(args)
    startNSloop(options.host, options.port, enableBroadcast=options.enablebc,
            bchost=options.bchost, bcport=options.bcport, unixsocket=options.unixsocket)

if __name__=="__main__":
    main(sys.argv[1:])
<commit_msg>don't crash on socket error when doing broadcast lookup, fixes for instance crash with errno EHOSTUNREACH<commit_after>"""
Name Server and helper functions.

Pyro - Python Remote Objects.  Copyright by Irmen de Jong (irmen@razorvine.net).
"""

from __future__ import with_statement
import re, logging, socket, sys
from Pyro4 import constants, core, socketutil
from Pyro4.threadutil import RLock, Thread
from Pyro4.errors import PyroError, NamingError
import Pyro4

__all__=["locateNS", "resolve", "startNS"]

if sys.version_info>=(3, 0):
    basestring=str

log=logging.getLogger("Pyro.naming")

class NameServer(object):
    """Pyro name server. Provides a simple flat name space to map logical object names to Pyro URIs."""

    def __init__(self):
        self.namespace={}
        self.lock=RLock()

    def lookup(self, name):
        """Lookup the given name, returns an URI if found"""
        try:
            return core.URI(self.namespace[name])
        except KeyError:
            raise NamingError("unknown name: "+name)

    def register(self, name, uri, safe=False):
        """Register a name with an URI. If safe is true, name cannot be registered twice.
        The uri can be a string or an URI object."""
        if isinstance(uri, core.URI):
            uri=uri.asString()
        elif not isinstance(uri, basestring):
            raise TypeError("only URIs or strings can be registered")
        else:
            core.URI(uri)  # check if uri is valid
        if not isinstance(name, basestring):
            raise TypeError("name must be a str")
        if safe and name in self.namespace:
            raise NamingError("name already registered: "+name)
        with self.lock:
            self.namespace[name]=uri

    def remove(self, name=None, prefix=None, regex=None):
        """Remove a registration. returns the number of items removed."""
        if name and name in self.namespace and name!=constants.NAMESERVER_NAME:
            with self.lock:
                del self.namespace[name]
            return 1
        if prefix:
            with self.lock:
                items=list(self.list(prefix=prefix).keys())
                if constants.NAMESERVER_NAME in items:
                    items.remove(constants.NAMESERVER_NAME)
                for item in items:
                    del self.namespace[item]
                return len(items)
        if regex:
            with self.lock:
                items=list(self.list(regex=regex).keys())
                if constants.NAMESERVER_NAME in items:
                    items.remove(constants.NAMESERVER_NAME)
                for item in items:
                    del self.namespace[item]
                return len(items)
        return 0

    def list(self, prefix=None, regex=None):
        """Retrieve the registered items as a dictionary name-to-URI. The URIs
        in the resulting dict are strings, not URI objects.
        You can filter by prefix or by regex."""
        with self.lock:
            if prefix:
                result={}
                for name in self.namespace:
                    if name.startswith(prefix):
                        result[name]=self.namespace[name]
                return result
            elif regex:
                result={}
                try:
                    regex=re.compile(regex+"$")  # add end of string marker
                except re.error:
                    x=sys.exc_info()[1]
                    raise NamingError("invalid regex: "+str(x))
                else:
                    for name in self.namespace:
                        if regex.match(name):
                            result[name]=self.namespace[name]
                    return result
            else:
                # just return (a copy of) everything
                return self.namespace.copy()

    def ping(self):
        """A simple test method to check if the name server is running correctly."""
        pass

class NameServerDaemon(core.Daemon):
    """Daemon that contains the Name Server."""
    def __init__(self, host=None, port=None, unixsocket=None):
        if Pyro4.config.DOTTEDNAMES:
            raise PyroError("Name server won't start with DOTTEDNAMES enabled because of security reasons")
        if host is None:
            host=Pyro4.config.HOST
        if port is None:
            port=Pyro4.config.NS_PORT
        super(NameServerDaemon, self).__init__(host, port, unixsocket)
        self.nameserver=NameServer()
        self.register(self.nameserver, constants.NAMESERVER_NAME)
        self.nameserver.register(constants.NAMESERVER_NAME, self.uriFor(self.nameserver))
        log.info("nameserver daemon created")

    def close(self):
        super(NameServerDaemon, self).close()
        self.nameserver=None

    def __enter__(self):
        if not self.nameserver:
            raise PyroError("cannot reuse this object")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.nameserver=None
        return super(NameServerDaemon, self).__exit__(exc_type, exc_value, traceback)

class BroadcastServer(object):
    if sys.version_info>=(3, 0):
        REQUEST_NSURI=bytes("GET_NSURI", "ASCII")
    else:
        REQUEST_NSURI="GET_NSURI"

    def __init__(self, nsUri, bchost=None, bcport=None):
        self.nsUri=nsUri
        if bcport is None:
            bcport=Pyro4.config.NS_BCPORT
        if bchost is None:
            bchost=Pyro4.config.NS_BCHOST
        if ":" in nsUri.host:  # ipv6
            bchost = bchost or "::"
            self.sock=Pyro4.socketutil.createBroadcastSocket((bchost, bcport, 0, 0), reuseaddr=Pyro4.config.SOCK_REUSE, timeout=2.0)
        else:
            self.sock=Pyro4.socketutil.createBroadcastSocket((bchost, bcport), reuseaddr=Pyro4.config.SOCK_REUSE, timeout=2.0)
        self._sockaddr=self.sock.getsockname()
        bchost=bchost or self._sockaddr[0]
        bcport=bcport or self._sockaddr[1]
        if ":" in bchost:  # ipv6
            self.locationStr="[%s]:%d" % (bchost, bcport)
        else:
            self.locationStr="%s:%d" % (bchost, bcport)
        log.info("ns broadcast server created on %s", self.locationStr)
        self.running=True

    def close(self):
        log.debug("ns broadcast server closing")
        self.running=False
        self.sock.close()

    def getPort(self):
        return self.sock.getsockname()[1]

    def fileno(self):
        return self.sock.fileno()

    def runInThread(self):
        """Run the broadcast server loop in its own thread. This is mainly for Jython,
        which has problems with multiplexing it using select() with the Name server itself."""
        thread=Thread(target=self.__requestLoop)
        thread.setDaemon(True)
        thread.start()
        log.debug("broadcast server loop running in own thread")

    def __requestLoop(self):
        while self.running:
            self.processRequest()
        log.debug("broadcast server loop terminating")

    def processRequest(self):
        try:
            data, addr=self.sock.recvfrom(100)
            if data==self.REQUEST_NSURI:
                responsedata=core.URI(self.nsUri)
                if responsedata.host=="0.0.0.0":
                    # replace INADDR_ANY address by the interface IP adress that connects to the requesting client
                    try:
                        interface_ip=socketutil.getInterfaceAddress(addr[0])
                        responsedata.host=interface_ip
                    except socket.error:
                        pass
                log.debug("responding to broadcast request from %s: interface %s", addr[0], responsedata.host)
                responsedata=str(responsedata)
                if sys.version_info>=(3, 0):
                    responsedata=bytes(responsedata, "iso-8859-1")
                self.sock.sendto(responsedata, 0, addr)
        except socket.error:
            pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

def startNSloop(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None, unixsocket=None):
    """utility function that starts a new Name server and enters its requestloop."""
    daemon=NameServerDaemon(host, port, unixsocket)
    nsUri=daemon.uriFor(daemon.nameserver)
    bcserver=None
    if unixsocket:
        hostip="Unix domain socket"
    else:
        hostip=daemon.sock.getsockname()[0]
        if hostip.startswith("127."):
            print("Not starting broadcast server for localhost.")
            log.info("Not starting NS broadcast server because NS is bound to localhost")
            enableBroadcast=False
        if enableBroadcast:
            bcserver=BroadcastServer(nsUri, bchost, bcport)
            print("Broadcast server running on %s" % bcserver.locationStr)
            bcserver.runInThread()
    print("NS running on %s (%s)" % (daemon.locationStr, hostip))
    print("URI = %s" % nsUri)
    try:
        daemon.requestLoop()
    finally:
        daemon.close()
        if bcserver is not None:
            bcserver.close()
    print("NS shut down.")

def startNS(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None, unixsocket=None):
    """utility fuction to quickly get a Name server daemon to be used in your own event loops.
    Returns (nameserverUri, nameserverDaemon, broadcastServer)."""
    daemon=NameServerDaemon(host, port, unixsocket)
    bcserver=None
    nsUri=daemon.uriFor(daemon.nameserver)
    if not unixsocket:
        hostip=daemon.sock.getsockname()[0]
        if hostip.startswith("127."):
            # not starting broadcast server for localhost.
            enableBroadcast=False
        if enableBroadcast:
            bcserver=BroadcastServer(nsUri, bchost, bcport)
    return nsUri, daemon, bcserver

def locateNS(host=None, port=None):
    """Get a proxy for a name server somewhere in the network."""
    def broadcastloop(bindaddr, sendaddr):
        sock=Pyro4.socketutil.createBroadcastSocket(bindaddr, reuseaddr=Pyro4.config.SOCK_REUSE, timeout=0.7)
        for _ in range(2):
            try:
                sock.sendto(BroadcastServer.REQUEST_NSURI, 0, sendaddr)
                data, _=sock.recvfrom(100)
                sock.close()
                if sys.version_info>=(3,0):
                    data=data.decode("iso-8859-1")
                log.debug("located NS: %s", data)
                return core.Proxy(data)
            except socket.timeout:
                continue
            except socket.error:
                continue
        sock.close()
        return None

    if host is None:
        # first try localhost if we have a good chance of finding it there
        if Pyro4.config.NS_HOST in ("localhost", "::1") or Pyro4.config.NS_HOST.startswith("127."):
            host = Pyro4.config.NS_HOST
            if ":" in host:   # ipv6
                host="[%s]" % host
            uristring="PYRO:%s@%s:%d" % (constants.NAMESERVER_NAME, host, port or Pyro4.config.NS_PORT)
            log.debug("locating the NS: %s", uristring)
            proxy=core.Proxy(uristring)
            try:
                proxy.ping()
                log.debug("located NS")
                return proxy
            except PyroError:
                pass
        # broadcast lookup
        if not port:
            port=Pyro4.config.NS_BCPORT
        log.debug("IPv6 broadcast locate")
        result = broadcastloop(("::", 0, 0, 0), ("ff02::1", port, 0, 0))
        if result is not None:
            return result
        log.debug("ipv6 broadcast locate failed")
        log.debug("ipv4 broadcast locate")
        result = broadcastloop(("0.0.0.0", 0), ("<broadcast>", port))
        if result is not None:
            return result
        log.debug("ipv4 broadcast locate failed, try direct connection on NS_HOST")
        # broadcast failed, try PYRO directly on specific host
        host=Pyro4.config.NS_HOST
        port=Pyro4.config.NS_PORT
    # pyro direct lookup
    if not port:
        port=Pyro4.config.NS_PORT
    if ":" in host:
        host = "[%s]" % host
    if core.URI.isUnixsockLocation(host):
        uristring="PYRO:%s@%s" % (constants.NAMESERVER_NAME, host)
    else:
        uristring="PYRO:%s@%s:%d" % (constants.NAMESERVER_NAME, host, port)
    uri=core.URI(uristring)
    log.debug("locating the NS: %s", uri)
    proxy=core.Proxy(uri)
    try:
        proxy.ping()
        log.debug("located NS")
        return proxy
    except PyroError:
        raise Pyro4.errors.NamingError("Failed to locate the nameserver")

def resolve(uri):
    """Resolve a 'magic' uri (PYRONAME) into the direct PYRO uri."""
    if isinstance(uri, basestring):
        uri=core.URI(uri)
    elif not isinstance(uri, core.URI):
        raise TypeError("can only resolve Pyro URIs")
    if uri.protocol=="PYRO":
        return uri
    log.debug("resolving %s", uri)
    if uri.protocol=="PYRONAME":
        nameserver=locateNS(uri.host, uri.port)
        uri=nameserver.lookup(uri.object)
        nameserver._pyroRelease()
        return uri
    else:
        raise PyroError("invalid uri protocol")

def main(args):
    from optparse import OptionParser
    parser=OptionParser()
    parser.add_option("-n", "--host", dest="host", help="hostname to bind server on")
    parser.add_option("-p", "--port", dest="port", type="int", help="port to bind server on (0=random)")
    parser.add_option("-u","--unixsocket", help="Unix domain socket name to bind server on")
    parser.add_option("", "--bchost", dest="bchost", help="hostname to bind broadcast server on (default is \"\")")
    parser.add_option("", "--bcport", dest="bcport", type="int",
                      help="port to bind broadcast server on (0=random)")
    parser.add_option("-x", "--nobc", dest="enablebc", action="store_false", default=True,
                      help="don't start a broadcast server")
    options, args = parser.parse_args(args)
    startNSloop(options.host, options.port, enableBroadcast=options.enablebc,
            bchost=options.bchost, bcport=options.bcport, unixsocket=options.unixsocket)

if __name__=="__main__":
    main(sys.argv[1:])
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pytest
import socket
from server import response_ok, parse_request

def test_response_ok():
    response = response_ok(b"this is from the client")
    assert b"200" in response

@pytest.fixture()
def client_code():
    ADDR = ('127.0.0.1', 8000)
    client_conn = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP
    )

    client_conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    client_conn.connect(ADDR)
    return client_conn

def test_functional(client_code):
    msg = b"GET /index.html HTTP/1.1\r\nHost:"

    try:
        client_code.sendall(msg)
        output = ""
        while True:
            part = client_code.recv(1024)
            assert part
            output = output + part
            if len(part) < 1024:
                client_code.shutdown(socket.SHUT_WR)
                client_code.close()
                break
    except Exception as e:
        print e
    assert b'200' in output

def test_bad_request_functional(client_code):
    msg = "do you hear me at all?"

    try:
        client_code.sendall(msg)
        output = b""
        while True:
            part = client_code.recv(1024)
            assert part
            output = output + part
            if len(part) < 1024:
                client_code.shutdown(socket.SHUT_WR)
                client_code.close()
                break
    except Exception as e:
        print e
    assert b"400" in output

def test_bad_parse():
    bad_request = b"some_bad_request"
    with pytest.raises(ValueError):
        parse_request(bad_request)

def test_parse_request():
    bad_request = b"GET /index.html HTTP/1.1\r\nHost:"
    response = parse_request(bad_request)
    assert b"/index.html" in response

'''def test_send_msg(client_code):
    client_code.sendall(b"GET Hello World")
    output = ""
    while True:
        part = client_code.recv(16)
        output = output + part
        if len(part) < 16:
            client_code.shutdown(socket.SHUT_WR)
            client_code.close()
            break
    assert b"World" in output
    assert b"200" in output'''
<commit_msg>delete old stuff<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pytest
import socket
from server import response_ok, parse_request

def test_response_ok():
    response = response_ok(b"this is from the client")
    assert b"200" in response

@pytest.fixture()
def client_code():
    ADDR = ('127.0.0.1', 8000)
    client_conn = socket.socket(
        socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP
    )

    client_conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    client_conn.connect(ADDR)
    return client_conn

def test_functional(client_code):
    msg = b"GET /index.html HTTP/1.1\r\nHost:"

    try:
        client_code.sendall(msg)
        output = ""
        while True:
            part = client_code.recv(1024)
            assert part
            output = output + part
            if len(part) < 1024:
                client_code.shutdown(socket.SHUT_WR)
                client_code.close()
                break
    except Exception as e:
        print e
    assert b'200' in output

def test_bad_request_functional(client_code):
    msg = "do you hear me at all?"

    try:
        client_code.sendall(msg)
        output = b""
        while True:
            part = client_code.recv(1024)
            assert part
            output = output + part
            if len(part) < 1024:
                client_code.shutdown(socket.SHUT_WR)
                client_code.close()
                break
    except Exception as e:
        print e
    assert b"400" in output

def test_bad_parse():
    bad_request = b"some_bad_request"
    with pytest.raises(ValueError):
        parse_request(bad_request)

def test_parse_request():
    bad_request = b"GET /index.html HTTP/1.1\r\nHost:"
    response = parse_request(bad_request)
    assert b"/index.html" in response
<|endoftext|>


<commit_before>import csv
from datetime import datetime
from StringIO import StringIO

from django.contrib import messages
from django.shortcuts import redirect, render
from django.views.generic.base import TemplateView
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from volunteering.models import (Assignment, Duty, Volunteer, Family,
                                 Event, Sendable)

def importer(request):
    if request.method == 'POST':
        data_file = StringIO(request.POST['csv'])
        data_csv = csv.DictReader(data_file, dialect=csv.excel_tab)

        created_count = 0
        updated_count = 0
        for record in data_csv:
            created = _update_or_create_volunteer(record)
            if created:
                created_count += 1
            else:
                updated_count += 1
        messages.success(request, '%s volunteers created and %s updated.' %
                         (created_count, updated_count))
        return redirect('/admin/volunteering/volunteer/')
    else:
        return render(request, 'volunteering/import.html')

def _update_or_create_volunteer(record):
    family, _ = Family.objects.get_or_create(external_id=record['FAMILY ID'])
    params = {
        'title': record['TITLE'],
        'first_name': record['FIRSTNAMES'],
        'surname': record['SURNAME'],
        'dear_name': record['DEARNAMES'],
        'external_id': record['MEMBER ID'],
        'family': family,
        'email_address': record['EMAIL'],
        'home_phone': record['HOME'],
        'mobile_phone': record['MOBILE'],
    }
    volunteer, created = Volunteer.objects.update_or_create(
        params, external_id=record['MEMBER ID'])
    # attribute_names = [a.strip() for a in record['ATTRIBUTES'].split(",")]
    # volunteer.attributes.clear()
    # for attribute_name in attribute_names:
    #     attribute = Attribute.objects.get(name=attribute_name)
    #     volunteer.attributes.add(attribute)

    # volunteer.save()
    return created

class SummaryView(TemplateView):

    template_name = 'volunteering/summary.html'

    def get_context_data(self, **kwargs):
        context = super(SummaryView, self).get_context_data(**kwargs)
        volunteer = Volunteer.objects.get(slug=kwargs['volunteer_slug'])

        self.set_volunteer_last_view(volunteer)

        context['volunteer'] = volunteer
        context['assigned'] = Duty.objects.upcoming_assigned_to(volunteer)
        context['assignable'] = Duty.objects.assignable_to(volunteer). \
            order_by('event', 'start_time').distinct()

        return context

    def set_volunteer_last_view(self, volunteer):
        volunteer.last_summary_view = timezone.now()
        volunteer.save()

class AssignmentView(TemplateView):

    template_name = 'volunteering/assignment.html'

    def get_context_data(self, **kwargs):
        context = super(AssignmentView, self).get_context_data(**kwargs)

        volunteer = Volunteer.objects.get(slug=kwargs['volunteer_slug'])
        duty = Duty.objects.get(id=kwargs['duty_id'])

        context['volunteer'] = volunteer
        context['duty'] = duty
        context['is_claimed'] = volunteer.has_claimed(duty)
        return context

    def post(self, request, *args, **kwargs):
        volunteer_slug = kwargs['volunteer_slug']
        duty_id = kwargs['duty_id']

        volunteer = Volunteer.objects.get(slug=volunteer_slug)
        duty = Duty.objects.get(pk=duty_id)

        Assignment.objects.create(volunteer=volunteer, duty=duty)
        return redirect(request.path, permanent=False)

class EventReportView(TemplateView):

    template_name = 'volunteering/event_report.html'

    def get_context_data(self, **kwargs):
        context = super(EventReportView, self).get_context_data(**kwargs)

        event = Event.objects.get(id=kwargs['event_id'])

        context['event'] = event
        context['generated_datetime'] = datetime.now()
        return context

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(EventReportView, self).dispatch(*args, **kwargs)

class EmailContentView(TemplateView):

    template_name = 'volunteering/email_content.html'

    def get_context_data(self, **kwargs):
        context = super(EmailContentView, self).get_context_data(**kwargs)

        sendable = Sendable.objects.get(id=kwargs['sendable_id'])

        context['body'] = sendable.email_body()
        return context

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(EmailContentView, self).dispatch(*args, **kwargs)
<commit_msg>Attempt at streaming response during import.<commit_after>import csv
from datetime import datetime
from StringIO import StringIO

from django.contrib import messages
from django.shortcuts import redirect, render
from django.views.generic.base import TemplateView
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

from volunteering.models import (Assignment, Duty, Volunteer, Family,
                                 Event, Sendable)

def importer(request):
    if request.method == 'POST':
        data_file = StringIO(request.POST['csv'])
        data_csv = csv.DictReader(data_file, dialect=csv.excel_tab)
        return StreamingHttpResponse(import_records(data_csv))
    else:
        return render(request, 'volunteering/import.html')

def import_records(data_csv):
    created_count = 0
    updated_count = 0
    for record in data_csv:
        created = _update_or_create_volunteer(record)
        if created:
            created_count += 1
            yield(".")
        else:
            updated_count += 1
            yield("-")
    message = '%s volunteers created and %s updated.' %
                     (created_count, updated_count))
    messages.success(request, message)
    yield(message)

def _update_or_create_volunteer(record):
    family, _ = Family.objects.get_or_create(external_id=record['FAMILY ID'])
    params = {
        'title': record['TITLE'],
        'first_name': record['FIRSTNAMES'],
        'surname': record['SURNAME'],
        'dear_name': record['DEARNAMES'],
        'external_id': record['MEMBER ID'],
        'family': family,
        'email_address': record['EMAIL'],
        'home_phone': record['HOME'],
        'mobile_phone': record['MOBILE'],
    }
    volunteer, created = Volunteer.objects.update_or_create(
        params, external_id=record['MEMBER ID'])
    # attribute_names = [a.strip() for a in record['ATTRIBUTES'].split(",")]
    # volunteer.attributes.clear()
    # for attribute_name in attribute_names:
    #     attribute = Attribute.objects.get(name=attribute_name)
    #     volunteer.attributes.add(attribute)

    # volunteer.save()
    return created

class SummaryView(TemplateView):

    template_name = 'volunteering/summary.html'

    def get_context_data(self, **kwargs):
        context = super(SummaryView, self).get_context_data(**kwargs)
        volunteer = Volunteer.objects.get(slug=kwargs['volunteer_slug'])

        self.set_volunteer_last_view(volunteer)

        context['volunteer'] = volunteer
        context['assigned'] = Duty.objects.upcoming_assigned_to(volunteer)
        context['assignable'] = Duty.objects.assignable_to(volunteer). \
            order_by('event', 'start_time').distinct()

        return context

    def set_volunteer_last_view(self, volunteer):
        volunteer.last_summary_view = timezone.now()
        volunteer.save()

class AssignmentView(TemplateView):

    template_name = 'volunteering/assignment.html'

    def get_context_data(self, **kwargs):
        context = super(AssignmentView, self).get_context_data(**kwargs)

        volunteer = Volunteer.objects.get(slug=kwargs['volunteer_slug'])
        duty = Duty.objects.get(id=kwargs['duty_id'])

        context['volunteer'] = volunteer
        context['duty'] = duty
        context['is_claimed'] = volunteer.has_claimed(duty)
        return context

    def post(self, request, *args, **kwargs):
        volunteer_slug = kwargs['volunteer_slug']
        duty_id = kwargs['duty_id']

        volunteer = Volunteer.objects.get(slug=volunteer_slug)
        duty = Duty.objects.get(pk=duty_id)

        Assignment.objects.create(volunteer=volunteer, duty=duty)
        return redirect(request.path, permanent=False)

class EventReportView(TemplateView):

    template_name = 'volunteering/event_report.html'

    def get_context_data(self, **kwargs):
        context = super(EventReportView, self).get_context_data(**kwargs)

        event = Event.objects.get(id=kwargs['event_id'])

        context['event'] = event
        context['generated_datetime'] = datetime.now()
        return context

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(EventReportView, self).dispatch(*args, **kwargs)

class EmailContentView(TemplateView):

    template_name = 'volunteering/email_content.html'

    def get_context_data(self, **kwargs):
        context = super(EmailContentView, self).get_context_data(**kwargs)

        sendable = Sendable.objects.get(id=kwargs['sendable_id'])

        context['body'] = sendable.email_body()
        return context

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(EmailContentView, self).dispatch(*args, **kwargs)
<|endoftext|>


<commit_before>from test_support import verbose
import string, sys

def test(name, input, output, *args):
    if verbose:
        print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
    try:
        try:
            f = getattr(string, name)
            value = apply(f, (input,) + args)
        except AttributeError:
            f = getattr(input, name)
            value = apply(f, args)
    except:
         value = sys.exc_type
    if value != output:
        if verbose:
            print 'no'
        print f, `input`, `output`, `value`
    else:
        if verbose:
            print 'yes'

test('atoi', " 1 ", 1)
test('atoi', " 1x", ValueError)
test('atoi', " x1 ", ValueError)
test('atol', "  1  ", 1L)
test('atol', "  1x ", ValueError)
test('atol', "  x1 ", ValueError)
test('atof', "  1  ", 1.0)
test('atof', "  1x ", ValueError)
test('atof', "  x1 ", ValueError)

test('capitalize', ' hello ', ' hello ')
test('capitalize', 'hello ', 'Hello ')
test('find', 'abcdefghiabc', 0, 'abc')
test('find', 'abcdefghiabc', 9, 'abc', 1)
test('find', 'abcdefghiabc', -1, 'def', 4)
test('rfind', 'abcdefghiabc', 9, 'abc')
test('lower', 'HeLLo', 'hello')
test('lower', 'hello', 'hello')
test('upper', 'HeLLo', 'HELLO')
test('upper', 'HELLO', 'HELLO')

transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'

test('maketrans', 'abc', transtable, 'xyz')
test('maketrans', 'abc', ValueError, 'xyzq')

test('split', 'this is the split function',
     ['this', 'is', 'the', 'split', 'function'])
test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|')
test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2)
test('split', 'a b c d', ['a', 'b c d'], None, 1)
test('split', 'a b c d', ['a', 'b', 'c d'], None, 2)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 0)
test('split', 'a  b  c  d', ['a', 'b', 'c  d'], None, 2)

# join now works with any sequence type
class Sequence:
    def __init__(self): self.seq = 'wxyz'
    def __len__(self): return len(self.seq)
    def __getitem__(self, i): return self.seq[i]

test('join', ['a', 'b', 'c', 'd'], 'a b c d')
test('join', ('a', 'b', 'c', 'd'), 'abcd', '')
test('join', Sequence(), 'w x y z')
test('join', 7, TypeError)

class BadStr:
    def __str__(self): raise RuntimeError

class BadSeq(Sequence):
    def __init__(self): self.seq = [7, 'hello', BadStr()]

test('join', BadSeq(), RuntimeError)

# try a few long ones
print string.join(['x' * 100] * 100, ':')
print string.join(('x' * 100,) * 100, ':')

test('strip', '   hello   ', 'hello')
test('lstrip', '   hello   ', 'hello   ')
test('rstrip', '   hello   ', '   hello')
test('strip', 'hello', 'hello')

test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS')
test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def')

table = string.maketrans('a', 'A')
test('translate', 'abc', 'Abc', table)
test('translate', 'xyz', 'xyz', table)

test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1)
test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@')
test('replace', 'one!two!three!', 'one!two!three!', 'x', '@')
test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2)

test('startswith', 'hello', 1, 'he')
test('startswith', 'hello', 1, 'hello')
test('startswith', 'hello', 0, 'hello world')
test('startswith', 'hello', 1, '')
test('startswith', 'hello', 0, 'ello')
test('startswith', 'hello', 1, 'ello', 1)
test('startswith', 'hello', 1, 'o', 4)
test('startswith', 'hello', 0, 'o', 5)
test('startswith', 'hello', 1, '', 5)
test('startswith', 'hello', 0, 'lo', 6)
test('startswith', 'helloworld', 1, 'lowo', 3)
test('startswith', 'helloworld', 1, 'lowo', 3, 7)
test('startswith', 'helloworld', 0, 'lowo', 3, 6)

test('endswith', 'hello', 1, 'lo')
test('endswith', 'hello', 0, 'he')
test('endswith', 'hello', 1, '')
test('endswith', 'hello', 0, 'hello world')
test('endswith', 'helloworld', 0, 'worl')
test('endswith', 'helloworld', 1, 'worl', 3, 9)
test('endswith', 'helloworld', 1, 'world', 3, 12)
test('endswith', 'helloworld', 1, 'lowo', 1, 7)
test('endswith', 'helloworld', 1, 'lowo', 2, 7)
test('endswith', 'helloworld', 1, 'lowo', 3, 7)
test('endswith', 'helloworld', 0, 'lowo', 4, 7)
test('endswith', 'helloworld', 0, 'lowo', 3, 8)

string.whitespace
string.lowercase
string.uppercase
<commit_msg>Added a couple of endswith test cases for bugs reported by Timbot.<commit_after>from test_support import verbose
import string, sys

# XXX: kludge... short circuit if strings don't have methods
try:
    ''.join
except AttributeError:
    raise ImportError

def test(name, input, output, *args):
    if verbose:
        print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
    try:
        try:
            f = getattr(string, name)
            value = apply(f, (input,) + args)
        except AttributeError:
            f = getattr(input, name)
            value = apply(f, args)
    except:
         value = sys.exc_type
    if value != output:
        if verbose:
            print 'no'
        print f, `input`, `output`, `value`
    else:
        if verbose:
            print 'yes'

test('atoi', " 1 ", 1)
test('atoi', " 1x", ValueError)
test('atoi', " x1 ", ValueError)
test('atol', "  1  ", 1L)
test('atol', "  1x ", ValueError)
test('atol', "  x1 ", ValueError)
test('atof', "  1  ", 1.0)
test('atof', "  1x ", ValueError)
test('atof', "  x1 ", ValueError)

test('capitalize', ' hello ', ' hello ')
test('capitalize', 'hello ', 'Hello ')
test('find', 'abcdefghiabc', 0, 'abc')
test('find', 'abcdefghiabc', 9, 'abc', 1)
test('find', 'abcdefghiabc', -1, 'def', 4)
test('rfind', 'abcdefghiabc', 9, 'abc')
test('lower', 'HeLLo', 'hello')
test('lower', 'hello', 'hello')
test('upper', 'HeLLo', 'HELLO')
test('upper', 'HELLO', 'HELLO')

transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'

test('maketrans', 'abc', transtable, 'xyz')
test('maketrans', 'abc', ValueError, 'xyzq')

test('split', 'this is the split function',
     ['this', 'is', 'the', 'split', 'function'])
test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|')
test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2)
test('split', 'a b c d', ['a', 'b c d'], None, 1)
test('split', 'a b c d', ['a', 'b', 'c d'], None, 2)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4)
test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 0)
test('split', 'a  b  c  d', ['a', 'b', 'c  d'], None, 2)

# join now works with any sequence type
class Sequence:
    def __init__(self): self.seq = 'wxyz'
    def __len__(self): return len(self.seq)
    def __getitem__(self, i): return self.seq[i]

test('join', ['a', 'b', 'c', 'd'], 'a b c d')
test('join', ('a', 'b', 'c', 'd'), 'abcd', '')
test('join', Sequence(), 'w x y z')
test('join', 7, TypeError)

class BadStr:
    def __str__(self): raise RuntimeError

class BadSeq(Sequence):
    def __init__(self): self.seq = [7, 'hello', BadStr()]

test('join', BadSeq(), RuntimeError)

# try a few long ones
print string.join(['x' * 100] * 100, ':')
print string.join(('x' * 100,) * 100, ':')

test('strip', '   hello   ', 'hello')
test('lstrip', '   hello   ', 'hello   ')
test('rstrip', '   hello   ', '   hello')
test('strip', 'hello', 'hello')

test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS')
test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def')

table = string.maketrans('a', 'A')
test('translate', 'abc', 'Abc', table)
test('translate', 'xyz', 'xyz', table)

test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1)
test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@')
test('replace', 'one!two!three!', 'one!two!three!', 'x', '@')
test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2)

test('startswith', 'hello', 1, 'he')
test('startswith', 'hello', 1, 'hello')
test('startswith', 'hello', 0, 'hello world')
test('startswith', 'hello', 1, '')
test('startswith', 'hello', 0, 'ello')
test('startswith', 'hello', 1, 'ello', 1)
test('startswith', 'hello', 1, 'o', 4)
test('startswith', 'hello', 0, 'o', 5)
test('startswith', 'hello', 1, '', 5)
test('startswith', 'hello', 0, 'lo', 6)
test('startswith', 'helloworld', 1, 'lowo', 3)
test('startswith', 'helloworld', 1, 'lowo', 3, 7)
test('startswith', 'helloworld', 0, 'lowo', 3, 6)

test('endswith', 'hello', 1, 'lo')
test('endswith', 'hello', 0, 'he')
test('endswith', 'hello', 1, '')
test('endswith', 'hello', 0, 'hello world')
test('endswith', 'helloworld', 0, 'worl')
test('endswith', 'helloworld', 1, 'worl', 3, 9)
test('endswith', 'helloworld', 1, 'world', 3, 12)
test('endswith', 'helloworld', 1, 'lowo', 1, 7)
test('endswith', 'helloworld', 1, 'lowo', 2, 7)
test('endswith', 'helloworld', 1, 'lowo', 3, 7)
test('endswith', 'helloworld', 0, 'lowo', 4, 7)
test('endswith', 'helloworld', 0, 'lowo', 3, 8)
test('endswith', 'ab', 0, 'ab', 0, 1)
test('endswith', 'ab', 0, 'ab', 0, 0)

string.whitespace
string.lowercase
string.uppercase
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import glm_parser
import re, sys

HELP_MSG =\
"""

script for train and test glm_parser

options:
    -h:     help message

    -b:     begining section of training data
    -e:     ending section of training data
    (   training would not be processed
        unless both begin and ending section is specfied    )

    -a:     list of sections that should be used in accuracy testing
            please seperate the sections with ','
            i.e.  "-a 1,2,3,4,55"
    (   accuracy test would not be processed
        if testing sections are not specified   )

    -d:     name of the db file to load for parsing
    -o:     prefix of the name of the output file
            default: "weight"
            the name would be prefix + iteration number
            i.e. "weight_iter_0.db"
    -t:     test data path, default: "./penn-wsj-deps/"

"""

if __name__ == "__main__":
    import getopt
    db_name = None
    train = False
    test = False
    train_begin = -1
    train_end = -1
    #trainsection = [(2,21)]
    #testsection = [0,1,22,24]
    output_file = "weight"
    test_data_path = "./penn-wsj-deps/"
    try:
        opt_spec = "hb:e:a:d:o:t:"
        opts, args = getopt.getopt(sys.argv[1:], opt_spec)
        for opt, value in opts:
            if opt == "-h":
                print HELP_MSG
                sys.exit(0)
            elif opt == "-b":
                train_begin = int(value)
            elif opt == "-e":
                train_end = int(value)
            elif opt == "-a":
                testsection = [int(sec) for sec in value.split(',')]
                test = True
            elif opt == "-d":
                db_name = value
            elif opt == "-o":
                output_file = value
            elif opt == "-t":
                test_data_path = value
            else:
                print "invalid input, see -h"
                sys.exit(0)

        if train_begin >= 0 and train_end >= 0:
            trainsection = [(train_begin, train_end)]
            train = True

        gp = glm_parser.GlmParser(db_name)
        if train:
            print output_file, trainsection
            gp.train(trainsection, test_data_path, output_file)
        if test:
            print gp.unlabeled_accuracy(testsection, test_data_path)
    except getopt.GetoptError, e:
        print "invalid arguments!! \n" + HELP_MSG
        sys.exit(1)

<commit_msg>Delete test_glm_parser.py<commit_after><|endoftext|>


<commit_before># coding: UTF-8

from __future__ import unicode_literals

import telwoord

def test_cardinal():

    inputs = {
        # Normal numbers
        0: "nul",
        1: "een",
        2: "twee",
        20: "twintig",
        22: "tweeëntwintig",
        100: "honderd",
        200: "tweehonderd",
        222: "tweehonderdtweeëntwintig",
        999: "negenhonderdnegenennegentig",
        # 1000: "duizend",
        # 2200: "tweeëntwintighonderd",
        # 2220: "tweeduizend tweehonderdtwintig",
        # 2220222: "twee miljoen tweehonderdtwintigduizend "
        #          "tweehonderdtweeëntwintig",

        # Negative numbers
        -1: "min een",
        -10: "min tien",
    }

    for n, w in inputs.items():
        assert telwoord.cardinal(n) == w

def test_threshold():
    assert telwoord.cardinal(5, threshold=7) == "vijf"
    assert telwoord.cardinal(5, threshold=3) == "5"

    assert telwoord.cardinal(-5, threshold=7) == "min vijf"
    assert telwoord.cardinal(-5, threshold=3) == "-5"
<commit_msg>Add more tests (many are failing)<commit_after># coding: UTF-8

from __future__ import unicode_literals

import telwoord

def test_cardinal():

    inputs = {
        # Normal numbers
        0: "nul",
        1: "een",
        11: "elf",
        19: "negentien",
        20: "twintig",
        100: "honderd",
        200: "tweehonderd",
        999: "negenhonderdnegenennegentig",
        1000: "duizend",
        12001: "twaalfduizend een",
        99999: "negenennegentigduizend negenhonderdnegenennegentig",

        # From http://woordenlijst.org/leidraad/6/9/
        2: "twee",
        20: "twintig",
        22: "tweeëntwintig",
        200: "tweehonderd",
        222: "tweehonderdtweeëntwintig",
        2200: "tweeëntwintighonderd",
        2220: "tweeduizend tweehonderdtwintig",
        2220222: "twee miljoen tweehonderdtwintigduizend "
                 "tweehonderdtweeëntwintig",

        # From https://onzetaal.nl/taaladvies/advies/getallen-uitschrijven
        108: "honderdacht",
        678: "zeshonderdachtenzeventig",
        2013: "tweeduizend dertien",
        2577: "tweeduizend vijfhonderdzevenenzeventig",
        17053980: "zeventien miljoen drieënvijftigduizend negenhonderdtachtig",

        # Negative numbers
        -1: "min een",
        -10: "min tien",
    }

    for n, w in inputs.items():
        assert telwoord.cardinal(n) == w

def test_threshold():
    assert telwoord.cardinal(5, threshold=7) == "vijf"
    assert telwoord.cardinal(5, threshold=3) == "5"

    assert telwoord.cardinal(-5, threshold=7) == "min vijf"
    assert telwoord.cardinal(-5, threshold=3) == "-5"
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
  File: test.py

  Автоматизированный тест работы декодера диапазонов.

"""

from Tkinter import *
from tkMessageBox import *
import time
import threading
import thread
import serial

"""
  'Сценарий' тестирования, набор данных для тестирования.

    freq - 'текущая' частота
    output_code - бинарный код соответсвующий 'текщему' диапазону
                  (заложен на будующее для считывания с устройства 'обратной связи')
    dialog - текст выводимый в диалоговом окне
"""

data_for_test_script = [

  {"freq":"00003500000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"}, #1
  {"freq":"00001829999", "output_code":0x00, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001830000", "output_code":0x00, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00003800000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001930000", "output_code":0x00, "dialog":"Включен диапазон 1.8 мГц"}, #5
  {"freq":"00003600000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001939999", "output_code":0x00, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00007000000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00003499999", "output_code":0x02, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00014000000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"}, #10
  {"freq":"00003899999", "output_code":0x02, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00007100000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00014350000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00006999999", "output_code":0x04, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00021100000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"}, #15
  {"freq":"00007199999", "output_code":0x04, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00028800000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00013999999", "output_code":0x08, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00021450000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00014359999", "output_code":0x08, "dialog":"Включен диапазон 21.0 мГц"}, #20
  {"freq":"00001900000", "output_code":0x01, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00020999999", "output_code":0x10, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00007040000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00021459999", "output_code":0x10, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00027999999", "output_code":0x20, "dialog":"Включен диапазон 7.0 мГц."}, #25
  {"freq":"00029700000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00014200000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00029799999", "output_code":0x20, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00021100000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00029000000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"} #30

]

"""
  Набор данных для 'нагрузочного' тестирования.

    count - число циклов
    delay - задержка между переключениями (в секундах)
    [...] - набор частот
"""

data_for_load_test = [

  {"count":2, "delay":1},
  ["00001900000", "00003600000", "00007040000", "00014200000", "00021100000", "00029000000"]
]

""" 'Текущая' частота - переменная используется для передачи значения между потоками """
g_s_frequency = 00000000000

class gui(Tk):
  def __init__(self):
    Tk.__init__(self)

    self.title("Автоматический тест декодера диапазонов для TS-590")
    #self.geometry('500x200')

    self.button_run_test = Button( self, text = "Начать автоматизированное тестирование",
                               command = lambda:self.run_test() )
    self.button_run_test.pack()

    self.button_run_test = Button( self, text = "Начать нагрузочное тестирование",
                               command = lambda:self.loading_test() )
    self.button_run_test.pack()

    self.result_text = Label(self)
    self.result_text.pack()

    self.progress_label = Label(self, text=self.get_progress_text(0, 0), bg="light sky blue")
    self.progress_label.pack()

    self.set_frequency("00000000000")

    thread.start_new_thread( trx_imitator, ("/dev/ttyS0", "") )

    #thread_serial = threading.Thread(target=trx_imitator, args=("/dev/ttyUSB0", self.s_frequency))
    #thread_serial.daemon = True
    #thread_serial.run()

  def get_progress_text(self, current_value, max_value):
    return "Выполнено " + str(current_value) + " из " + str(max_value) + " тестовых случаев."

  def paint_result(self,successful, failure, total ):

    self.result_text["width"]=50
    self.result_text["height"]=10

    if failure == 0:
      self.result_text["bg"]="green"
    else:
      self.result_text["bg"]="red"

    self.result_text["text"]=" \
    Резльтат тестирования: \n\
    Успешных тестов = " + str(successful) + "\n\
    Сбоев           = " + str(failure) + "\n\
    Всего тестов    = " + str(total)

  def run_test(self):
    """
      Автоматизированный тест.
    """

    len_list_test_case = len(data_for_test_script)
    successful = 0
    failure = 0
    self.progress_label["text"]=self.get_progress_text(0, len_list_test_case)

    for index, item in enumerate(data_for_test_script):

      self.set_frequency( item["freq"] )

      ret = askyesno("Тестовый случай #" + str(index+1),
                     "Вы наблюдаете следующее состояние?\n\n" + item["dialog"])

      if ret:
        successful +=1
      else:
        failure +=1

      self.progress_label["text"]=self.get_progress_text(index+1, len_list_test_case)

    self.paint_result(successful, failure, len_list_test_case )

  def loading_test(self):
    """
      'Нагрузочный' тест. Разработка не завершена.
      В текущей реализации используется как 'двухкратный прогон' по всем диапазонам

      TODO: 'Вынести' в отдельный поток.

    """
    self.progress_label["text"]= "Выполнено циклов : 0 из " + str( data_for_load_test[0]["count"] )

    for iteration in range(data_for_load_test[0]["count"]):

      for index, item in enumerate(data_for_load_test[1]):
        self.set_frequency( item )
        time.sleep(data_for_load_test[0]["delay"])

      self.progress_label["text"]= "Выполнено циклов : " + str(iteration+1) + " из " + str( data_for_load_test[0]["count"] )

    showinfo("Выполнено", "Нагрузочное тестирование завершено.")

  def set_frequency(self, freq):
    if len(freq) != 11:
      showerror("Ошибка", "Значение частоты должно состоять из 11 символов.")

    global g_s_frequency
    g_s_frequency = freq

def trx_imitator(device, arg2):

  global g_s_frequency

  ser = serial.Serial( port=device, baudrate=9600,
                          parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                          bytesize=serial.EIGHTBITS )

  receive_command = ""

  while(True):
    receive_char = ser.read()
    receive_command += receive_char

    if receive_char == ";":
      if receive_command == "IF;":
        send_command = "IF" + str(g_s_frequency) + "2222233333456789ABCDEEF;"
        ser.write(send_command)

      receive_command = ""

if __name__ == '__main__':
  gui().mainloop()

<commit_msg>ref #29.<commit_after># -*- coding: utf-8 -*-
"""
  File: test.py

  Автоматизированный тест работы декодера диапазонов.

"""

from Tkinter import *
from tkMessageBox import *
import time
import thread
import serial

"""
  'Сценарий' тестирования, набор данных для тестирования.

    freq - 'текущая' частота
    output_code - бинарный код соответсвующий 'текщему' диапазону
                  (заложен на будующее для считывания с устройства 'обратной связи')
    dialog - текст выводимый в диалоговом окне
"""

data_for_test_script = [

  {"freq":"00003500000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"}, #1
  {"freq":"00001829999", "output_code":0x00, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001830000", "output_code":0x00, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00003800000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001930000", "output_code":0x00, "dialog":"Включен диапазон 1.8 мГц"}, #5
  {"freq":"00003600000", "output_code":0x02, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00001939999", "output_code":0x00, "dialog":"Включен диапазон 3.5 мГц"},
  {"freq":"00007000000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00003499999", "output_code":0x02, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00014000000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"}, #10
  {"freq":"00003899999", "output_code":0x02, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00007100000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00014350000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00006999999", "output_code":0x04, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00021100000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"}, #15
  {"freq":"00007199999", "output_code":0x04, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00028800000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00013999999", "output_code":0x08, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00021450000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00014359999", "output_code":0x08, "dialog":"Включен диапазон 21.0 мГц"}, #20
  {"freq":"00001900000", "output_code":0x01, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00020999999", "output_code":0x10, "dialog":"Включен диапазон 1.8 мГц"},
  {"freq":"00007040000", "output_code":0x04, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00021459999", "output_code":0x10, "dialog":"Включен диапазон 7.0 мГц."},
  {"freq":"00027999999", "output_code":0x20, "dialog":"Включен диапазон 7.0 мГц."}, #25
  {"freq":"00029700000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"},
  {"freq":"00014200000", "output_code":0x08, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00029799999", "output_code":0x20, "dialog":"Включен диапазон 14.0 мГц"},
  {"freq":"00021100000", "output_code":0x10, "dialog":"Включен диапазон 21.0 мГц"},
  {"freq":"00029000000", "output_code":0x20, "dialog":"Включен диапазон 28.0 мГц"} #30

]

"""
  Набор данных для 'нагрузочного' тестирования.

    count - число циклов
    delay - задержка между переключениями (в секундах)
    [...] - набор частот
"""

data_for_load_test = [

  {"count":2, "delay":1},
  ["00001900000", "00003600000", "00007040000", "00014200000", "00021100000", "00029000000"]
]

""" 'Текущая' частота - переменная используется для передачи значения между потоками """
g_s_frequency = 00000000000

class gui(Tk):
  def __init__(self):
    Tk.__init__(self)

    self.title("Автоматический тест декодера диапазонов для TS-590")
    #self.geometry('500x200')

    self.button_run_test = Button( self, text = "Начать автоматизированное тестирование",
                               command = lambda:self.run_test() )
    self.button_run_test.pack()

    self.button_run_test = Button( self, text = "Начать нагрузочное тестирование",
                               command =  lambda:thread.start_new_thread( self.loading_test, () ) )
    self.button_run_test.pack()

    self.result_text = Label(self)
    self.result_text.pack()

    self.progress_label = Label(self, text=self.get_progress_text(0, 0), bg="light sky blue")
    self.progress_label.pack()

    self.set_frequency("00000000000")

    thread.start_new_thread( trx_imitator, ("/dev/ttyS0", "") )

    #thread_serial = threading.Thread(target=trx_imitator, args=("/dev/ttyUSB0", self.s_frequency))
    #thread_serial.daemon = True
    #thread_serial.run()

  def get_progress_text(self, current_value, max_value):
    return "Выполнено " + str(current_value) + " из " + str(max_value) + " тестовых случаев."

  def paint_result(self,successful, failure, total ):

    self.result_text["width"]=50
    self.result_text["height"]=10

    if failure == 0:
      self.result_text["bg"]="green"
    else:
      self.result_text["bg"]="red"

    self.result_text["text"]=" \
    Резльтат тестирования: \n\
    Успешных тестов = " + str(successful) + "\n\
    Сбоев           = " + str(failure) + "\n\
    Всего тестов    = " + str(total)

  def run_test(self):
    """
      Автоматизированный тест.
    """

    len_list_test_case = len(data_for_test_script)
    successful = 0
    failure = 0
    self.progress_label["text"]=self.get_progress_text(0, len_list_test_case)

    for index, item in enumerate(data_for_test_script):

      self.set_frequency( item["freq"] )

      ret = askyesno("Тестовый случай #" + str(index+1),
                     "Вы наблюдаете следующее состояние?\n\n" + item["dialog"])

      if ret:
        successful +=1
      else:
        failure +=1

      self.progress_label["text"]=self.get_progress_text(index+1, len_list_test_case)

    self.paint_result(successful, failure, len_list_test_case )

  def loading_test(self):
    """
      'Нагрузочный' тест. Разработка не завершена.
      В текущей реализации используется как 'двухкратный прогон' по всем диапазонам

      TODO: 'Вынести' в отдельный поток.

    """
    self.progress_label["text"]= "Выполнено циклов : 0 из " + str( data_for_load_test[0]["count"] )

    for iteration in range(data_for_load_test[0]["count"]):

      for index, item in enumerate(data_for_load_test[1]):
        self.set_frequency( item )
        time.sleep(data_for_load_test[0]["delay"])

      self.progress_label["text"]= "Выполнено циклов : " + str(iteration+1) + " из " + str( data_for_load_test[0]["count"] )

    showinfo("Выполнено", "Нагрузочное тестирование завершено.")

  def set_frequency(self, freq):
    if len(freq) != 11:
      showerror("Ошибка", "Значение частоты должно состоять из 11 символов.")

    global g_s_frequency
    g_s_frequency = freq

def trx_imitator(device, arg2):

  global g_s_frequency

  ser = serial.Serial( port=device, baudrate=9600,
                          parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                          bytesize=serial.EIGHTBITS )

  receive_command = ""

  while(True):
    receive_char = ser.read()
    receive_command += receive_char

    if receive_char == ";":
      if receive_command == "IF;":
        send_command = "IF" + str(g_s_frequency) + "2222233333456789ABCDEEF;"
        ser.write(send_command)

      receive_command = ""

if __name__ == '__main__':
  gui().mainloop()

<|endoftext|>