예제 #1
0
    def _test_rpc():
        ''' For doctest
            >>> from zero.rpc import ZeroRPC
            >>> ZeroRPC._test_rpc()
            REP u'hello'
            REP 100
        '''
        from zero import Zero, ZeroSetup
        class Z(ZeroRPC):
            def hi(self):
                return "hello"

            def sqr(self, x):
                return x*x

        def listen():
            zero = Zero(ZeroSetup('rep', 8000)).activated(Z())
            for _, msg in izip(range(2), zero):
                zero(msg)
            zero.close()

        from threading import Thread
        t = Thread(name='TestRPC', target=listen)
        t.daemon = True
        t.start()

        zero = Zero(ZeroSetup('req', 8000))
        msg = ['hi']
        rep = zero(msg)
        print 'REP %r' % rep
        msg = ['sqr', {'x': 10}]
        rep = zero(msg)
        print 'REP %r' % rep
        zero.close()
        t.join()
예제 #2
0
    def setup(self, table):
        """
        normalize the data ranges before calling parent setup with normalized table
        """

        self.data = table.to_numpyMA('ac')[0]
        
        pred_columns = [table.domain.index(table.domain[c]) for c in self.cols]
        search_cols = [pos for pos in pred_columns
                       if table.domain[pos].varType != orange.VarTypes.Discrete]

        bounds = Zero.compute_bounds(self.data[:, search_cols])
        self.zero = Zero(search_cols, bounds=bounds)
        self.zerod_data = self.zero.zero(self.data)
        self.zerod_table = Orange.data.Table(table.domain, self.zerod_data.data)
        super(ZeroBottomUp, self).setup(self.zerod_table)
예제 #3
0
def main():
    import os.path
    from sys import argv
    from json import load
    from zero import Zero, ZeroSetup
    HERE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    conf = HERE + '/log.json'
    if len(argv) > 1:
        conf = argv[1]
    print 'Loading config from', conf
    with open(conf) as fin:
        conf = load(fin)['log']
    setup = ZeroSetup('pull', conf['port'])
    path = conf['file']
    if path[0] != '/':
        path = HERE + '/' + path
    print 'Logger started for', setup
    print 'Logging to', path
    with open(path, 'a', 1) as fout:
        logout = Logout(conf)
        try:
            for line in Zero(setup):
                fout.write(line)
                fout.write('\n')
                logout.tty(line)
        except KeyboardInterrupt:
            print 'Logger quitting.'
    print 'Logger stopped on', setup
예제 #4
0
def main():
    'For CLI use, see usage in __doc__.'
    import os.path
    from sys import argv, exit
    from json import load
    from os.path import exists
    from itertools import imap
    from collections import deque
    HERE = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    args = deque(argv[1:])
    if len(args) < 3:
        exit(__doc__)
    conf = HERE + '/log.json'
    level = args.popleft()
    if exists(level):
        conf = level
        level = args.popleft()
    with open(conf) as fin:
        conf = load(fin)['log']
    sender = args.popleft()
    if args[0] == '-':
        messages = ZeroSetup.iter_stdin()
    else:
        messages = iter(args)
    messages = imap(lambda x: ZLogger.format(sender, level, x), messages)
    z = Zero(ZeroSetup('push', conf['port']))
    for msg in messages:
        z(msg)
예제 #5
0
def main():
    import sys
    if len(sys.argv) > 1 and sys.argv[1] == 'test':
        # Running tests, not zeros
        import doctest
        sys.path.insert(0, '..')
        import zero
        import zero.rpc
        fails, tests = doctest.testmod(zero)
        fails2, tests2 = doctest.testmod(zero.rpc)
        tests += tests2
        if fails + fails2:
            msg = 'Completed %d tests, %d failed. Run zero test -v for more information.'
            sys.exit(msg % (tests, fails + fails2))
        print 'Successfully completed %d tests.' % tests
        return

    import json
    from zero import Zero, ZeroSetup, zauto, UnsupportedZmqMethod
    try:
        # Regular zero run
        setup, loop = ZeroSetup.argv()
        zero = Zero(setup)

        for msg in zauto(zero, loop, setup.args['--wait']):
            sys.stdout.write(json.dumps(msg) + '\n')
            sys.stdout.flush()
    except UnsupportedZmqMethod, e:
        args = e.args[2]
        if args['rpc']:
            # Configured RPC not supported by zauto
            from zero.rpc import zrpc
            with open(args['<config>']) as fin:
                config = json.load(fin)
            if len(args['<type>']) == 1:
                zero = zrpc(config, args['<type>'][0])
                setup = zero.setup
                if args['--dbg']:
                    setup.debugging(True)
                for msg in zero:
                    if setup.transmits:
                        zero(msg)
            else:
                raise ValueError('Multiple RPC workers not yet supported.',
                                 args['<type>'])
        else:
            # Something happened...
            raise e
        if setup.args['--wait']:
            raw_input('Press enter when done.')
        zero.close()
예제 #6
0
파일: rpc.py 프로젝트: philipbergen/zero
    def _test_rpc():
        """ For doctest
            >>> from zero.rpc import ZeroRPC
            >>> ZeroRPC._test_rpc()
            REP u'hello'
            REP 100
        """
        from zero import Zero, ZeroSetup

        class Z(ZeroRPC):
            def hi(self):
                return "hello"

            def sqr(self, x):
                return x * x

        def listen():
            zero = Zero(ZeroSetup("rep", 8000)).activated(Z())
            for _, msg in izip(range(2), zero):
                zero(msg)
            zero.close()

        from threading import Thread

        t = Thread(name="TestRPC", target=listen)
        t.daemon = True
        t.start()

        zero = Zero(ZeroSetup("req", 8000))
        msg = ["hi"]
        rep = zero(msg)
        print "REP %r" % rep
        msg = ["sqr", {"x": 10}]
        rep = zero(msg)
        print "REP %r" % rep
        zero.close()
        t.join()
예제 #7
0
파일: rpc.py 프로젝트: philipbergen/zero
    def _test_rpc():
        ''' For doctest
            >>> from zero.rpc import ZeroRPC
            >>> ZeroRPC._test_rpc()
            REP u'hello'
            REP 100
        '''
        from zero import Zero, ZeroSetup

        class Z(ZeroRPC):
            def hi(self):
                return "hello"

            def sqr(self, x):
                return x * x

        def listen():
            zero = Zero(ZeroSetup('rep', 8000)).activated(Z())
            for _, msg in izip(range(2), zero):
                zero(msg)
            zero.close()

        from threading import Thread
        t = Thread(name='TestRPC', target=listen)
        t.daemon = True
        t.start()

        zero = Zero(ZeroSetup('req', 8000))
        msg = ['hi']
        rep = zero(msg)
        print 'REP %r' % rep
        msg = ['sqr', {'x': 10}]
        rep = zero(msg)
        print 'REP %r' % rep
        zero.close()
        t.join()
예제 #8
0
def zlogger(config, sender):
    ''' Convenience function for setting up a ZLogger and queue. Returns a ZLogger
        object with .fyi, .wtf, .omg functions as specified in config['log']['levels'].
    '''
    from Queue import Queue
    from threading import Thread
    logq = Queue()
    slog = Zero(
        ZeroSetup('push', 'tcp://%(host)s:%(port)s' % config).nonblocking())

    def thread(slog=slog):
        for t in iter(logq.get, ''):
            slog(t)

    t = Thread(target=thread)
    t.daemon = True
    t.start()
    return ZLogger(config, logq, sender, gethostname())
예제 #9
0
파일: rpc.py 프로젝트: philipbergen/zero
def zrpc(sysconfig, workertype):
    ''' Returns an activated Zero with RPC worker of type workertype as specified in sysconfig.
        >>> from .test import _get_test_config
        >>> from zero import zbg
        >>> from itertools import izip
        >>> from socket import gethostname
        >>> from time import time
        >>> cfg = _get_test_config()
        >>> z = zrpc(cfg, 'common')
        >>> o = z.opposite()
        >>> z  # doctest: +ELLIPSIS
        Zero(ZeroSetup('rep', 8000).binding(True)).activated(<zero.test.CommonRPC object at ...>)
        >>> o
        Zero(ZeroSetup('req', 8000).binding(False))
        >>> t = zbg(o, [['ping'], ['echo', {'msg': 'Hello'}], ['hostname'], ['time']], lambda x: x)
        >>> reps = []
        >>> for _, msg in izip(range(4), z):  # doctest: +ELLIPSIS
        ...     reps.append(msg)
        ...     z(msg)
        >>> reps[0]
        'pong'
        >>> reps[1]
        u'Hello'
        >>> reps[2] == gethostname()
        True
        >>> abs(time() - reps[3]) < 1
        True
        >>> t.join()
    '''
    from zero import Zero, ZeroSetup
    wconf = sysconfig['workers'][workertype]
    zconf = wconf['zmq']
    setup = ZeroSetup(zconf['method'],
                      zconf['port']).debugging(zconf.get('debug', False))
    if 'bind' in zconf:
        setup.binding(zconf['bind'])
    if 'host' in zconf and not setup.bind:
        setup._point = 'tcp://%(host)s:%(port)s' % zconf
    mod = __import__(wconf['module'])
    for modpart in wconf['module'].split('.')[1:]:
        mod = getattr(mod, modpart)
    klass = getattr(mod, wconf['class'])
    return Zero(setup).activated(klass(sysconfig, workertype))
예제 #10
0
class ZeroBottomUp(BottomUp):

    def __init__(self, *args, **kwargs):
        self.zero = None
        BottomUp.__init__(self, *args, **kwargs)
        

    def setup(self, table):
        """
        normalize the data ranges before calling parent setup with normalized table
        """

        self.data = table.to_numpyMA('ac')[0]
        
        pred_columns = [table.domain.index(table.domain[c]) for c in self.cols]
        search_cols = [pos for pos in pred_columns
                       if table.domain[pos].varType != orange.VarTypes.Discrete]

        bounds = Zero.compute_bounds(self.data[:, search_cols])
        self.zero = Zero(search_cols, bounds=bounds)
        self.zerod_data = self.zero.zero(self.data)
        self.zerod_table = Orange.data.Table(table.domain, self.zerod_data.data)
        super(ZeroBottomUp, self).setup(self.zerod_table)

        
        

    def __call__(self, table, **kwargs):

        BottomUp.__call__(self, table, **kwargs)

        # unzero all clusters and final clusters
        self.all_clusters = map(self.zero.unzero_cluster, self.all_clusters)
        self.final_clusters = map(self.zero.unzero_cluster, self.final_clusters)

        return self.final_clusters
예제 #11
0
파일: cv.py 프로젝트: sairajesh1303/qna
	a = 4685763
	b = 47831
	n = 47564875
	u = [u0]
	for i in range(nb_hidden * nb_students):
		u.append(((a * u[-1] + b) % n) % nb_questions)
	return u


chrono = Chrono()
files = IO()
for dataset_name in ['fraction']:
	dataset = Dataset(dataset_name, files)
	q = QMatrix()
	q.load('qmatrix-%s' % dataset_name)
	models = [Zero(), IRT(), MIRT(dim=2), MIRT(dim=3), MIRT(q=q)]  # [IRT()]#, MIRT(dim=2), MIRT(dim=3), MIRT(q=q)]  # , MHRM(dim=2), , MHRM(dim=2)
	dataset.load_subset()
	print(dataset)
	for i_exp in range(STUDENT_FOLD):
		# train_subset = dataset.train_subsets[i_exp]
		# test_subset = dataset.test_subsets[i_exp]
		for j_exp in range(QUESTION_FOLD):
			# validation_index = set(dataset.validation_question_sets[j_exp])
			files.update(i_exp, j_exp)
			for model in models:
				print(model.name)
				begin = datetime.now()
				print(begin)
				data = np.array(dataset.data)
				nb_students, nb_questions = data.shape
				nb_hidden = round(HIDDEN_RATE * nb_questions)
예제 #12
0
# -*- coding: utf-8 -*-

from flask import Flask, g, send_from_directory, request
from zero import Zero
from camera import GIF, TimeLapse
from json import dumps

# Variabili globali
app = Flask(__name__)
zero = Zero(g)
gif = GIF(zero)
timelapse = TimeLapse(zero)


# OPERAZIONI DI SESSIONE

@app.before_request
def apri_connessione():
    zero.database.apri_connessione()

@app.teardown_request
def chiudi_connessione(exception):
    zero.database.chiudi_connessione()


# INVIO DI FILE

# Home
@app.route('/')
def home():
    return send_from_directory('../client-side/html/', 'home.html')
예제 #13
0
 def listen():
     zero = Zero(ZeroSetup('rep', 8000)).activated(Z())
     for _, msg in izip(range(2), zero):
         zero(msg)
     zero.close()
예제 #14
0
파일: rpc.py 프로젝트: philipbergen/zero
 def listen():
     zero = Zero(ZeroSetup('rep', 8000)).activated(Z())
     for _, msg in izip(range(2), zero):
         zero(msg)
     zero.close()
예제 #15
0
from zero import Zero
from cessna import Cessna
from ram import Ram
from tesla import Tesla

fxs = Zero()
fxs.main_color = "red"
fxs.drive()
fxs.turn("right")
fxs.stop()

modelS = Tesla()
modelS.main_color = "green"
modelS.drive()
modelS.turn("left")
modelS.stop()

mx410 = Cessna()
mx410.main_color = "white"
mx410.drive()
mx410.turn("right")
mx410.stop()

ram1500 = Ram()
ram1500.main_color = "orange"
ram1500.drive()
ram1500.turn("left")
ram1500.stop()
예제 #16
0
from tesla import Tesla
from ram import Ram
from cessna import Cessna
from zero import Zero
# my_tesla = Tesla()

# my_tesla.main_color = "blue"

# print(my_tesla.main_color)

fxs = Zero()
modelS = Tesla()
mx410 = Cessna()
dodgeRam = Ram()

fxs.drive()
modelS.drive()
mx410.drive()
dodgeRam.drive()
예제 #17
0
# car1 = Vehicle("Porsche", "Black", 140)
# car2 = Vehicle("Jaguar", "Gray", 100)
# car3 = Vehicle("Audi", "Red", 110)
# car4 = Vehicle("BMW", "White", 120)
# car5 = Vehicle("Subaru", "Blue", 200)

# Create a drive() method in the Vehicle class.
# Override the drive() method in all the other vehicle classes. Include the vehicle's color in the message (i.e. "The blue Ram drives past. RRrrrrrummbbble!").

# Create a turn(self, direction) method, and a stop(self) method on Vehicle. Define a basic implementation of each.

# Override all three of those methods on some of the vehicles. For example, the stop() method for a plane would be to output the message "The white Cessna rolls to a stop after rolling a mile down the runway."
# Make your vehicle instances perform all three behaviors.

model_s = Tesla()
fxs = Zero()
mx410 = Cessna()
e350 = MB()

model_s.drive()
fxs.drive()
mx410.drive()
e350.drive()

fxs.turn("left")
fxs.stop()

e350.turn("left")
fxs.stop()