コード例 #1
0
def testhaltsViaPeano():
    # Since trueInPeano() is an oracle function that could never be
    # implemented, there is nothing reasonable to assert in this
    # test. We just run the code.
    inString = 'asdf'
    val = haltsViaPeano(inString)
    utils.tprint(inString, ':', val)
コード例 #2
0
ファイル: tspDirK.py プロジェクト: mshibatatt/wcbc_problems
def testTspDirK():
    testvals = [
        (';1', 'no'),
        ('a,a,3;1', 3),
        ('a,a,3 ; 1 ', 3),
        ('a,a,3;2', 'no'),
        ('a,b,4;1', 'no'),
        ('a,b,4;2', 'no'),
        ('a,b,4;3', 'no'),
        ('a,b,4 b,a,9;1', 13),
        ('a,b,4 b,a,9;2', 13),
        ('a,b,4 b,a,9;3', 'no'),
        ('a,b,4 b,a,9 b,c,6 c,a,10;2', 13),
        ('a,b,4 b,a,9 b,c,6 c,a,10;3', 20),
        ('a,b,4 b,a,9 b,c,6 c,a,1;2', 11),
        ('a,b,4 b,a,9 b,c,6 c,a,10;4', 'no'),
        ('a,b,4 b,a,9 b,c,6 c,a,10 a,c,2 c,b,3;3', 14),
        ('a,b,4 b,a,9 b,c,6 c,a,10 a,c,2 c,b,3;4', 'no'),
    ]
    for (inString, solution) in testvals:
        val = tspDirK(inString)
        utils.tprint(inString.strip(), ':', val)
        if solution == 'no':
            assert val == solution
        else:
            (graphString, K) = inString.split(';')
            graph = Graph(graphString, directed=True)
            K = int(K)
            cycle = Path.fromString(val)
            dist = graph.cycleLength(cycle)
            assert graph.isCycle(cycle)
            assert len(cycle) >= K
            assert dist == solution
コード例 #3
0
def testprovableInPeano():
    # isPeanoProof() works only for one particular string ('0=0') in our
    # artificial, skeletal implementation for testing purposes. So we test only that string.
    inString = '0=0'
    val = provableInPeano(inString)
    utils.tprint(inString, ':', val)
    assert val == 'yes'
コード例 #4
0
ファイル: wmf.py プロジェクト: kiminh/top-k-rec
 def train(self, max_iter: int = 200, tol: float = 1e-4, model_path: str = None) -> None:
     loss = np.exp(50)
     Ik   = np.eye(self.k, dtype=np.float32)
     if model_path is not None and os.path.isdir(model_path):
         self.import_embeddings(model_path)
     for it in range(max_iter):
         t1 = time.time()
         loss_old = loss
         loss     = 0
         Vr = self.fie[np.array(self.i_rated), :]
         XX = np.dot(Vr.T, Vr)*self.b + Ik*self.lu
         for i in self.usm:
             if len(self.usm[i]) > 0:
                 Vi = self.fie[np.array(self.usm[i]), :]
                 self.fue[i, :] = np.linalg.solve(np.dot(Vi.T, Vi)*(self.a-self.b)+XX, np.sum(Vi, axis=0)*self.a)
                 loss += 0.5 * self.lu * np.sum(self.fue[i,:]**2)
         Ur = self.fue[np.array(self.u_rated), :]
         XX = np.dot(Ur.T, Ur)*self.b
         for j in self.ism:
             if len(self.ism[j]) > 0:
                 Uj = self.fue[np.array(self.ism[j]), :]
                 B  = np.dot(Uj.T, Uj)*(self.a-self.b) + XX 
                 self.fie[j, :] = np.linalg.solve(B+Ik*self.lv, np.sum(Uj, axis = 0) * self.a)
                 loss += 0.5 * len(self.ism[j])*self.a
                 loss += 0.5 * np.linalg.multi_dot((self.fie[j, :], B, self.fie[j, :]))
                 loss -= np.sum(np.multiply(Uj, self.fie[j, :]))*self.a
                 loss += 0.5 * self.lv * np.sum(self.fie[j, :]**2)
         cond = np.abs(loss_old - loss) / loss_old
         tprint('Iter %3d, loss %.6f, converge %.6f, time %.2fs'%(it, loss, cond, time.time()-t1))
         if cond < tol:
             break
コード例 #5
0
def testEmptyOnEmpty():
    testvals = [('containsGAGA.py', 'no'), ('isEmpty.py', 'no'),
                ('onlyZs.py', 'yes')]
    for (progName, solution) in testvals:
        val = emptyOnEmpty(rf(progName))
        utils.tprint(progName, ":", val)
        assert val == solution
コード例 #6
0
def testConvertSatTo3Sat():
    s0 = '(x1 OR x2 OR NOT x3 OR NOT x4 OR x5) AND (NOT x1 OR NOT x2 OR x3 OR x4) AND (x4 OR NOT x5)'
    s0soln = '(d1 OR d2 OR x1) AND (NOT d2 OR x2 OR NOT x3) AND (NOT d1 OR NOT x4 OR x5) AND (d3 OR NOT x1 OR NOT x2) AND (NOT d3 OR x3 OR x4) AND (x4 OR NOT x5)'
    s1 = ''
    s1soln = ''
    s2 = 'x1'
    s2soln = '(x1)'
    s3 = 'x1 AND NOT x2'
    s3soln = '(x1) AND (NOT x2)'
    s4 = 'x1 OR NOT x2'
    s4soln = '(x1 OR NOT x2)'

    testvals = [
        (s0, s0soln),
        (s1, s1soln),
        (s2, s2soln),
        (s3, s3soln),
        (s4, s4soln),
    ]

    for (inString, soln) in testvals:
        utils.tprint('**', inString, '**')
        converted = convertSatTo3Sat(inString)
        utils.tprint(converted, '\n\n')
        assert converted == soln
コード例 #7
0
def testThreshToOpt():
    global FThresh
    FThresh = minThresh
    inStrings = [\
                 '13 18 16 35 23 19 42 73 4 13 8 22',\
                 '',\
                 '0',\
                 '0 1 2 3',\
                 '4',\
                 '4 4 4',\
                 '7 6 5 4',\
                 '4 5',\
                 '4 5 6',\
                 '5',\
                 '5 6',\
                 '5 6 7',\
                 '105 106 107',\
                 '100 105 106 107',\
                 ]
    upperBound = 100
    for inString in inStrings:
        val = threshToOpt(inString, upperBound)
        utils.tprint('with upper bound', upperBound, ', min of', inString, ':', val)
        nums = [int(x) for x in inString.split()]
        if len(nums)==0 or min(nums) > upperBound:
            solution = 'no'
        else:
            solution = str(min(nums))
        assert val == solution
コード例 #8
0
def testConvertDHCtoUHC():
    from uhc import uhc
    from dhc import dhc
    from graph import Path
    instances = [
        '',
        'a,a',
        'a,b',
        'a,b b,a',
        'a,b b,c c,a',
        'a,b b,c a,c',
        'a,b b,c c,d',
        'a,b b,c c,d d,a',
        'a,b b,c c,d a,d',
        'a,b b,c c,d a,d d,b c,a',
    ]
    for instance in instances:
        convertedInstance = convertDHCtoUHC(instance)
        instanceSolution = dhc(instance)
        convertedInstanceSolution = uhc(convertedInstance)
        revertedSolution = revertSolution(convertedInstanceSolution)

        utils.tprint(instance, 'maps to', convertedInstance,\
              ' solutions were: ', instanceSolution, ';', convertedInstanceSolution)
        utils.tprint('revertedSolution', revertedSolution)

        if revertedSolution == 'no':
            assert instanceSolution == 'no'
        else:
            g = Graph(instance, weighted=False)
            path = Path.fromString(revertedSolution)
            # print('g', g, 'path', path)
            assert g.isHamiltonCycle(path) or g.isHamiltonCycle(path.reverse())
コード例 #9
0
def testMultiply():
    testVals = [('4 5', 4 * 5), ('100 10000', 100 * 10000),
                ('1024 256', 1024 * 256)]
    for (inString, solution) in testVals:
        val = multiply(inString)
        utils.tprint(inString, val)
        assert int(val) == solution
コード例 #10
0
ファイル: turingMachine.py プロジェクト: HughMacConvery/Lab-4
def testHasSameTransitions():
    s1 = '''
q0->q0:f;x,R
q0->q1:abc;x,R
q0->q1:d;x,S
q0->q1:e;y,R
'''

    s2 = '''
q0->q0:!abcde;x,R
q0->q1:ab;x,R
q0->q1:c;x,R
q0->q1:d;x,S
q0->q1:e;y,R
q1->q2:~;R
'''
    testVals = [
        ( rf('containsGAGA.tm'), rf('containsGAGA.tm'), True),
        ( rf('binaryIncrementer.tm'), rf('binaryIncrementer.tm'), True),
        ( s1, s2, True),
        ( s2, s1, False),
    ]
    for (tm1str, tm2str, result) in testVals:
        tm1 = TuringMachine(tm1str)
        tm2 = TuringMachine(tm2str)
        val = tm1.hasSameTransitions(tm2)
        utils.tprint(val, result)
        assert val == result
コード例 #11
0
def testhaltsOnString():
    for (progName, inString, solution) in [
            ('loopIfContainsGAGA.py', 'GAGAGAGAG', 'no'), \
            ('loopIfContainsGAGA.py', 'TTTTGGCCGGT', 'yes') ]:
        val = haltsOnString(rf(progName), inString)
        utils.tprint((progName, inString), ":", val)
        assert val == solution
コード例 #12
0
def testNdFindNANADivConq():
    testVals = [
        ('1000Ts', 1000 * 'T', 'no'),
        ('1000Ts1GAGA', 1000 * 'T' + 'GAGA', 'yes'),
        ('1millionTs', 1000000 * 'T', 'no'),
        ('1millionTs1GAGA', 1000000 * 'T' + 'GAGA', 'yes'),
        ('10millionTs', 10000000 * 'T', 'no'),
        ('10millionTs1GAGA', 10000000 * 'T' + 'GAGA', 'yes'),
        ('10000CACAs10000TATAs', 10000 * 'CACA' + 10000 * 'TATA', 'yes'),
        ('10000CACAs10000TATAs', 10000 * 'CACA' + 10000 * 'TATA', 'yes'),
        ('10000CACAs10000TATAs', 10000 * 'CACA' + 10000 * 'TATA', 'yes'),
        ('10000CACAs10000TATAs', 10000 * 'CACA' + 10000 * 'TATA', 'yes'),
        ('10000CACAs10000TATAs', 10000 * 'CACA' + 10000 * 'TATA', 'yes'),
    ]
    for (desc, inString, solution) in testVals:
        val = ndFindNANADivConq(inString)
        utils.tprint(desc, ':', val)
        if val == 'no':
            assert val == solution
        else:
            assert val in ['GAGA', 'CACA', 'AAAA', 'TATA']
            assert val in inString
        utils.NonDetSolution.printLock.acquire()
        utils.tprint(desc, ':', val)
        utils.NonDetSolution.printLock.release()
コード例 #13
0
ファイル: dpm.py プロジェクト: wahidahrusli/top-k-rec
 def export_model(self, model_path: str) -> None:
     if os.path.exists(
             model_path
     ) and self.__sess is not None and self.__saver is not None:
         file_path = os.path.join(model_path, 'weights')
         tprint('Saving tensorflow graph to path %s' % (file_path))
         self.__saver.save(self.__sess, file_path)
コード例 #14
0
    def evaluate(self):
        """
        + example:
        >> pipeline = Pipeline()
        >> pipeline.prepare_data()
        >> pipeline.build_network()
        >> pipeline.evaluate()
        """
        self.load_model()
        self.network.eval()
        error_count = 0
        psnr_list = []
        for step, (img, target, path) in enumerate(self.dataloader_inference):
            if config.device == "cuda":
                img, target = [item.cuda() for item in (img, target)]

            new_img = self.network(img)

            output_img = new_img.squeeze().permute(1, 2, 0).detach().cpu().numpy()
            plt.imsave(os.path.join(self.config.DATA_ROOT_PATH, "inference_generated", path[0]), output_img)

            if target.shape != new_img.shape:
                error_count += 1
                continue
            psnr_list.append(get_batch_PSNR(target.float(), new_img.float()))

            tprint("Processed %.2f%% samples...\r" % (step / self.dataloader_inference.__len__() * 100), end="")
        print("error: %s" % error_count)
        print("\n")
        return np.mean(psnr_list)
コード例 #15
0
ファイル: cer.py プロジェクト: wahidahrusli/top-k-rec
 def export_model(self, model_path: str) -> None:
     if os.path.exists(model_path):
         if hasattr(self, 'E'):
             tprint('Saving content projection matrix to %s' %
                    os.path.join(model_path, 'final-E.dat'))
             export_embed_to_file(os.path.join(model_path, 'final-E.dat'),
                                  self.E)
コード例 #16
0
def testConvertPartitionToPacking():
    from packing import packing
    from partition import partition
    instances = [
        '5',
        '5 6',
        '5 6 7',
        '5 6 7 8',
        '',
        '5 7',
        '6 6',
        '6 6 7 7',
        '10 20 30 40 11 21 31 41',
    ]
    for instance in instances:
        convertedInstance = convertPartitionToPacking(instance)
        instanceSolution = partition(instance)
        convertedInstanceSolution = packing(convertedInstance)
        revertedSolution = convertedInstanceSolution
        utils.tprint(instance, 'maps to', convertedInstance,\
              ' solutions were: ', instanceSolution, ';', convertedInstanceSolution)

        if revertedSolution == 'no':
            assert instanceSolution == 'no'
        else:
            total = sum([int(x) for x in instance.split()])
            solutionTotal = sum([int(x) for x in revertedSolution.split()])
            assert solutionTotal * 2 == total
コード例 #17
0
ファイル: dpm.py プロジェクト: wahidahrusli/top-k-rec
 def import_model(self, model_path: str) -> None:
     file_path = os.path.join(model_path, 'weights')
     if os.path.exists(
             model_path
     ) and self.__sess is not None and self.__saver is not None:
         tprint('Restoring tensorflow graph from path %s' % (file_path))
         self.__saver.restore(self.__sess, file_path)
コード例 #18
0
ファイル: tfrecorder.py プロジェクト: KryoEM/tfmodels
    def get_example_keys(self):
        tprint(
            'Converting micrographs to tiles of %d pixels, particle diameter %d pixels ...'
            % (cfg.PICK_WIN, cfg.PART_D_PIXELS))
        micros = self.allmicros.keys()
        # random.shuffle(micros)
        # convert each micro into a set of tiles of cfg.PICK_WIN size
        # the training will run on one tile per record
        keys = []
        for m in micros:
            D = self.allmicros[m]['part_diameter']
            sz, bn = calc_micro_pick_shape(m, D)
            xs, ys = image.tile2D(sz, (cfg.PICK_WIN, ) * 2, 0.0)
            # create keys using tile coordinates
            for x in xs:
                for y in ys:
                    tcoords = self.calc_tile_coords(m, x, y, bn)
                    # see how many particles of each class
                    lens = [len(tcoords[k]) for k in tcoords]
                    if np.sum(np.array(lens)) < 1:
                        # skip empty tile
                        continue
                    else:
                        keys.append('%s:%d,%d' % (m, x, y))

        # shuffle all example records to sit randomly in shards
        random.shuffle(keys)
        return keys
コード例 #19
0
ファイル: twoTDCM.py プロジェクト: mshibatatt/wcbc_problems
def testTwoTDCM():
    for (filename, inString, tapeSoln, outputSoln) in [
        ('containsGAGA.tm', 'CCCCCCCCCAAAAAA', 'no', ''),
        ('containsGAGA.tm', 'CCCGAGACCAAAAAA', 'yes', ''),
        ('loop.tm', 'x', TuringMachine.exceededMaxStepsMsg, ''),
        ('alternating01.tm', '', TuringMachine.exceededMaxStepsMsg,
         '010101010101010101010101'),
        ('unarySequence.tm', '', TuringMachine.exceededMaxStepsMsg,
         '0010110111011110111110111111011111110111111110'),
    ]:
        tm = TwoTDCM(rf(filename), inString)
        try:
            tape = tm.run()
        except utils.WcbcException as e:
            if str(e).startswith(TuringMachine.exceededMaxStepsMsg):
                tape = TuringMachine.exceededMaxStepsMsg
            else:
                raise

        output = tm.getOutput()

        utils.tprint('filename:', filename, 'inString:', inString, 'tape:',
                     tape, 'output:', output)
        assert tape == tapeSoln
        if outputSoln == '':
            assert output == outputSoln
        else:
            assert output.startswith(outputSoln)
コード例 #20
0
def testOnlyZs():
    for (inString, solution) in [('', ''), ('aassdc', ''), ('ZZZ', 'ZZZ'),
                                 ('Z', 'Z'),
                                 ('ascZsfaasZZsacscaZZZ', 'ZZZZZZ')]:
        val = onlyZs(inString)
        utils.tprint(inString, ":", val)
        assert val == solution
コード例 #21
0
def testRecYesOnString():
    for (progName, inString, solution) in [('containsGAGA.py', 'GAGAGAGAG', 'yes'), \
                                 ('containsGAGA.py', 'TTTTGGCCGGT', 'no') ]:
        combinedString = utils.ESS(rf(progName), inString)
        val = recYesOnString(combinedString)
        utils.tprint( (progName, inString), ":", val )
        assert val == solution
コード例 #22
0
    def fit(self, X, y):
        y = y.flatten()
        if len(y) != X.shape[0]:
            raise ValueError('Data has {} samples and {} labels.'.format(
                X.shape[0], len(y)))

        if self.verbose_:
            tprint('Fitting MLP ensemble with {} regressors'.format(
                self.n_regressors_))

        self._create_models(X, y)

        if self.backend_ == 'sklearn':
            [model.fit(X, y) for model in self.models_]

        elif self.backend_ == 'keras':
            [
                model.fit(X,
                          y,
                          batch_size=self.batch_sizes_[model_idx],
                          epochs=self.max_iters_[model_idx],
                          verbose=self.verbose_)
                for model_idx, model in enumerate(self.models_)
            ]

        if self.verbose_:
            tprint('Done fitting MLP ensemble.')

        return self
コード例 #23
0
def testPathContains():
    p1 = Path([])
    p2 = Path(['a'])
    p4 = Path(['a', 'b'])
    p6 = Path(['a', 'b', 'c'])
    e5 = Edge(['a123', 'b123'])

    testvals = [
        (p1, 'a', False),
        (p2, 'a', True),
        (p4, 'a', True),
        (p4, 'b', True),
        (p4, 'c', False),
        (e5, 'a123', True),
        (e5, 'b123', True),
        (e5, 'c123', False),
        (p6, 'a', True),
        (p6, 'b', True),
        (p6, 'c', True),
        (p6, 'd', False),
    ]
    for (path, node, solution) in testvals:
        val = (node in path)
        utils.tprint(path, node, ':', val)
        assert val == solution
コード例 #24
0
def testGraphCycleLength():
    graphStr = 'a,b,1 b,c,2 c,d,3 d,e,4 e,a,5 c,c,6 z'
    g1 = Graph(graphStr)
    g2 = Graph(graphStr, directed=False)

    testvals = [
        ( (Graph(''), ''), 0),
        ( (Graph('a'), ''), 0),
        ( (Graph('a'), 'a'), 'exception'),
        ( (Graph('a,a,1'), 'a'), 1),
        ( (Graph('a,a,1'), 'a,a'), 'exception'),
        ( (g1, 'a,d'), 'exception'),
        ( (g1, 'a,b'), 'exception'),
        ( (g1, 'c'), 6),
        ( (g1, 'a,b,c,d,e'), 15),
        ( (g2, 'a,b,c,d,e'), 15),
    ]
    for ( args, solution) in testvals:
        g, pathStr = args
        path = Path.fromString(pathStr)
        try:
            val = g.cycleLength(path)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                val = 'exception'
        utils.tprint(args, ':', val)
        assert val == solution
コード例 #25
0
def testGraphIsHamiltonCycle():
    graphStr = 'a,b,1 b,c,2 c,d,3 d,e,4 c,c,6'
    g1 = Graph(graphStr)
    g2 = Graph(graphStr, directed=False)
    g3 = g1.clone(); g3.addEdge(Edge(['e','a']))
    g3b = g1.clone(); g3b.addEdge(Edge(['a','e']))
    g4 = g2.clone(); g4.addEdge(Edge(['a','e']))

    testvals = [
        ( (Graph(''), ''), True),
        ( (Graph('a'), ''), False),
        ( (Graph('a'), 'a'), False),
        ( (Graph('a,a', weighted=False), 'a'), True),
        ( (Graph('a,a,1'), 'a'), True),
        ( (Graph('a,a,1'), 'a,a'), False),
        ( (g1, 'a,b'), False),
        ( (g1, 'a,b,c'), False),
        ( (g2, 'a,b,c'), False),
        ( (g1, 'a,b,c,d,e'), False),
        ( (g2, 'a,b,c,d,e'), False),
        ( (g3, 'a,b,c,d,e'), True),
        ( (g3b, 'a,b,c,d,e'), False),
        ( (g4, 'a,b,c,d,e'), True),
        ( (g3, 'a,b,c,c,d,e'), False),
        ( (g4, 'a,b,c,c,d,e'), False),
    ]
    for ( args, solution) in testvals:
        g, pathStr = args
        path = Path.fromString(pathStr)
        val = g.isHamiltonCycle(path)
        utils.tprint(args, ':', val)
        assert val == solution
コード例 #26
0
def testPathStr():
    testvals = [
        ([], ''),
        ([''], 'exception'),
        ('', 'exception'),
        ('asdf', 'exception'),
        ([1,2,3,4], 'exception'),
        (['a1'], 'a1'),
        (['ab1'], 'ab1'),
        (['ab1', 'zxy'], 'ab1,zxy'),
        ('a,b,c'.split(','), 'a,b,c'),
        ('a,b,,c'.split(','), 'exception'),
        ('a1,b1,c1'.split(','), 'a1,b1,c1'),
    ]
    for (nodes, solution) in testvals:
        try:
            p = Path(nodes)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                val = 'exception, as expected'
        utils.tprint(nodes,':',solution)
        s = str(p)
        if solution != 'exception':
            assert s == solution
コード例 #27
0
def testGraphRemoveEdge():
    testvals = [
        ( ('',), Edge(['a','b']), 'exception'),
        ( ('a',), Edge(['a','a']), 'exception'),
        ( ('a,a b', False), Edge(['a','a']), 'a b'),
        ( ('a,a', False), Edge(['a','a']), 'a'),
        ( ('a,b', False), Edge(['a','b']), 'a b'),
        ( ('a,b', False), Edge(['b','a']), 'exception'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6',), Edge(['a','ccc']), 'ccc b,a,3 a,a,4 b,d,6'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6',), Edge(['ccc','a']), 'exception'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6', True, False), Edge(['d','b']), 'd b,a,3 a,a,4 a,ccc,5'),
    ]
    for ( args, edge, solution) in testvals:
        g = Graph(*args)

        try:
            g.removeEdge(edge)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                g = 'exception'

        solnArgs = list(args)
        solnArgs[0] = solution
        if solution != 'exception':
            solution = Graph(*solnArgs)
        utils.tprint(args, edge, ':', g)
        assert g == solution
コード例 #28
0
def testGraphAddEdge():
    testvals = [
        ( ('',), Edge(['a','b']), 'exception'),
        ( ('a',), Edge(['a','a']), 'a,a,1'),
        ( ('a,a b', False), Edge(['b','a']), 'a,a b,a'),
        ( ('a,a', False), Edge(['a','a']), 'exception'),
        ( ('a,b', False), Edge(['a','b']), 'exception'),
        ( ('a,b', False), Edge(['b','a']), 'a,b b,a'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6',), (Edge(['a','ccc']),9), 'exception'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6',), (Edge(['ccc','a']),9), 'ccc,a,9 b,a,3 a,a,4 a,ccc,5 b,d,6'),
        ( ('b,a,3 a,a,4 a,ccc,5 b,d,6', True, False), (Edge(['b','ccc']),9), 'b,ccc,9 b,a,3 a,a,4 a,ccc,5 b,d,6'),
        ( ('b,a,3 a,a,4 z a,ccc,5 b,d,6',), Edge(['z','z']), 'b,a,3 a,a,4 z,z,1 a,ccc,5 b,d,6'),
    ]
    for ( args, edgeArgs, solution) in testvals:
        g = Graph(*args)
        if isinstance(edgeArgs, Edge):
            edgeArgs = tuple(edgeArgs,)

        try:
            g.addEdge(*edgeArgs)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                g = 'exception'

        solnArgs = list(args)
        solnArgs[0] = solution
        if solution != 'exception':
            solution = Graph(*solnArgs)
        utils.tprint(args, edgeArgs, ':', g)
        assert g == solution
コード例 #29
0
def testNeighbors():
    testvals = [
                ( ('',), 'a', 'exception'),
                ( ('a',),'a', []),
                ( ('', False), 'a', 'exception'),
                ( ('', False, False), 'a', 'exception'),
                ( ('a,a', False), 'a', ['a']),
                ( ('a,b', False), 'a', ['b']),
                ( ('a,b', False), 'b', []),
                ( ('b,a,3 a,a,4', True, False), 'a', ['a', 'b']),
                ( ('b,a,3 a,a,4 a,ccc,5 b,d,6 e',), 'e', []),
                ( ('b,a,3 a,a,4 a,ccc,5 b,d,6 e a,d,3',), 'a', ['a', 'ccc', 'd']),
                ( ('b,a,3 a,a,4 a,ccc,5 b,d,6 e a,d,3',), 'b', ['a', 'd']),
    ]
    for ( args, node, solution) in testvals:
        g = Graph(*args)
        try:
            val = g.neighbors(node)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                val = 'exception'
        utils.tprint(args, node, ':', val)
        if solution != 'exception':
            solution = set(solution)
            val = set(val)
        assert val == solution
コード例 #30
0
def testGraphAddNode():
    testvals = [
                ( ('',), 'a', 'a'),
                ( ('a',), 'a', 'exception'),
                ( ('', False), 'a', 'a'),
                ( ('', False, False), 'a', 'a'),
                ( ('a,a', False), 'b', 'a,a b'),
                ( ('a,a', False), 'a', 'exception'),
                ( ('a,b', False), 'a', 'exception'),
                ( ('b,a,3 a,a,4', True, False), 'c', 'a,a,4 b,a,3 c'),
                ( ('b,a,3 a,a,4 a,ccc,5 b,d,6',), 'aaa', 'aaa a,a,4 a,ccc,5 b,a,3 b,d,6'),
                ( ('b,a,3 a,a,4', True, False), 'c', 'a,a,4 a,b,3 c'),
    ]
    for ( args, node, solution) in testvals:
        graphString = args[0]
        try:
            g = Graph(*args)
            g.addNode(node)
        except utils.WcbcException as e:
            if solution != 'exception':
                raise e
            else:
                g = 'exception'
        utils.tprint(args, node, ':', g)
        if solution != 'exception':
            solution = Graph(solution, *args[1:])
        assert g == solution
コード例 #31
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def __init__(self):
     tprint("HomeState")
     tprint("== Pizaid ==")
     tprint(time.strftime("%H:%M:%S"))
     tprint("\033[3A")
     send_clr()
     send_str("  == Pizaid ==")
     send_newline()
     send_str(time.strftime("%H:%M:%S") + " 30% AC")
コード例 #32
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def updateDisplay(self):
     tprint("HomeState: update        ")
     tprint(time.strftime("%H:%M:%S"))
     tprint("\033[3A")
     send_newline()
     send_str(time.strftime("%H:%M:%S"))
     return self
コード例 #33
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def updateDisplay(self):
     tprint("NetworkState: update        ")
     tprint(self.network.get_ipv4() + "        ")
     tprint("\033[3A")
     send_newline()
     send_str(self.network.get_ipv4() + "        ")
     return self
コード例 #34
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def __init__(self):
     tprint("Battery State        ")
     tprint(" "*30)
     tprint("\033[3A")
     send_clr()
     send_str("Battery State")
     send_newline()
     send_str("100% Ganbaru ZOI")
コード例 #35
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def __init__(self):
     tprint("Storage State        ")
     tprint(" "*30)
     tprint("\033[3A")
     send_clr()
     send_str("Storage State")
     send_newline()
     send_str("XXX GB / YYY GB")
コード例 #36
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def __init__(self):
     tprint("Storage Detail        ")
     tprint(" "*30)
     tprint("\033[3A")
     send_clr()
     send_str("Storage Detail")
     send_newline()
     send_str("1:TOSHIBA,Main")
コード例 #37
0
ファイル: ioserver.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def run(self):
     tprint("start ioserver")
     self.timer.start()
     lcd = self.lcd
     while True:
         c = getch()
         if (c == 'w'):
             lcd.up()
         elif (c == 'a'):
             lcd.left()
         elif (c == 's'):
             lcd.down()
         elif (c == 'd'):
             lcd.right()
         elif (c == ' '):
             lcd.center()
         elif (c == 'u'):
             lcd.updateDisplay()
         elif (c == 'q'):
             self.quit = True
             break
         else:
             tprint("Unknown Command")
コード例 #38
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def __init__(self):
     tprint("NetworkState        ")
     self.network = get_controllercomm().network()
     tprint(self.network.get_ipv4() + "        ")
     tprint("\033[3A")
     send_clr()
     send_str("Network")
     send_newline()
     send_str(self.network.get_ipv4() + "        ")
コード例 #39
0
ファイル: lcdserver.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def run(self):
     self.ioserver = IOServer()
     self.ioserver.start()
     tprint("Run io and dbus server")
     tprint("Wait to stop ioserver")
     self.ioserver.join()
コード例 #40
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def up(self):
     tprint("NetworkState: up        ")
     tprint("\033[2A")
     return HomeState()
コード例 #41
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def down(self):
     tprint("NetworkState: down        ")
     tprint("\033[2A")
     return StorageState()
コード例 #42
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def up(self):
     tprint("HomeState: up        ")
     tprint(time.strftime("%d/%m/%Y %H:%M:%S"))
     tprint("\033[3A")
     return BatteryState()
コード例 #43
0
ファイル: state.py プロジェクト: Pizaid/Pizaid-LCDPanel
 def down(self):
     tprint("HomeState: down        ")
     tprint(time.strftime("%d/%m/%Y %H:%M:%S"))
     tprint("\033[3A")
     return NetworkState()
コード例 #44
0
ファイル: __init__.py プロジェクト: Pizaid/Pizaid-LCDPanel
def start():
    tprint("Hello Pizaid!")
    tprint("This program is a server to display the status of RaspberryPi.")
    server = create_lcdserver()
    server.run()