Exemplo n.º 1
0
def test_appendo():
    reset_names()
    w, x, y, z = variables("w, x, y, z")

    goal = conj(same(z, (x, y)), appendo(x, y, [1, 2, 3]))
    assert list(run(z, goal)) == [([], [1, 2, 3]), ([1], [2, 3]), ([1,
                                                                    2], [3]),
                                  ([1, 2, 3], [])]

    goal = conj(same(z, (x, y)), appendo([1, 2, 3], x, y))
    assert list(run(3, z, goal)) == [([], [1, 2, 3]), (['_0'], [1, 2, 3,
                                                                '_0']),
                                     (['_0', '_1'], [1, 2, 3, '_0', '_1'])]

    goal = conj(same(z, (x, y)), appendo(x, [1, 2, 3], y))
    assert list(run(3, z, goal)) == [([], [1, 2, 3]), (['_0'], ['_0', 1, 2,
                                                                3]),
                                     (['_0', '_1'], ['_0', '_1', 1, 2, 3])]

    goal = conj(same(z, (w, x, y)), appendo(w, x, y))
    assert list(run(6, z, goal)) == [([], [], []), ([], ['_0'], ['_0']),
                                     (['_0'], [], ['_0']),
                                     ([], ['_0', '_1'], ['_0', '_1']),
                                     (['_0'], ['_1'], ['_0', '_1']),
                                     (['_0', '_1'], [], ['_0', '_1'])]
Exemplo n.º 2
0
def test_local_fresh():
    @defrel
    def caro(l, a):
        return fresh(lambda d: (same(a, l[0]), same(d, l[1:])))

    @defrel
    def cdro(l, d):
        return fresh(lambda a: (same(a, l[0]), same(d, l[1:])))

    q = variables('q')
    l = ['a', 'c', 'o', 'r', 'n']

    assert list(run(q, caro(l, q))) == ['a']
    assert list(run(q, cdro(l, q))) == [['c', 'o', 'r', 'n']]
Exemplo n.º 3
0
def index():
	if request.method == "POST":
		sentence_raw = request.form["sentence"]
		sentence_seg = api.segment(sentence_raw)
		contexts = api.run(sentence_raw)
		return myRender(render_template("index.html", raw=sentence_raw, seg=sentence_seg, contexts=contexts))
	return myRender(render_template("index.html", raw=raw))
Exemplo n.º 4
0
def test_defrel():
    @defrel
    def teacupo(t):
        return disj(same('tea', t), same('cup', t))

    x = variables('x')
    r = run(x, teacupo(x))
    assert list(r) == ['tea', 'cup']
Exemplo n.º 5
0
def main():
    # TODO: Register first
    # ret = register_myself()
    # if not ret['success']:
    # LOG.error(ret['data'])
    # sys.exit(1)

    # Start Agent
    exp_agent = ExpAgent('ExpAgent', 1)
    exp_state_agent = ExpStateAgent('ExpStateAgent', 1)

    exp_agent.start()
    exp_state_agent.start()

    # Start API
    sys.argv.append(api_port)
    sys.argv[1] = api_port
    api_server.run()
Exemplo n.º 6
0
async def run():
    cameras = db.get_cameras()
    if cameras is not None:
        for cam in cameras:
            asyncio.create_task(frameserver.capture(cam))
        motiondetector = BSMotionDetector(db, frameserver)
        motiondetector.run().subscribe(on_next=lambda res: asyncio.create_task(
            motion_result_handler(res)))
    asyncio.create_task(websocketserver.run())
    asyncio.create_task(api.run(frameserver, db))
Exemplo n.º 7
0
def test_recursion():
    @defrel
    def listo(l):
        return disj(nullo(l), fresh(lambda d: (cdro(l, d), listo(d))))

    @defrel
    def nullo(x):
        return same(x, ())

    @defrel
    def cdro(l, d):
        return fresh(lambda a: same((a, d), l))

    q = variables('q')

    goal = listo(())
    r = run(3, q, goal)
    assert list(r) == ['_0']

    r = run(4, q, listo(q))
    assert list(r) == [(), ('_0', ()), ('_0', ('_1', ())),
                       ('_0', ('_1', ('_2', ())))]
Exemplo n.º 8
0
def generate_image():
    image_id1 = request.args.get('image_id1')
    image_id2 = request.args.get('image_id2')
    weight = request.args.get('weight')
    task_type = request.args.get('task_type')
    choice = request.args.get('choice')
    resolution = request.args.get('resolution')
    print(image_id1, image_id2, weight, task_type, resolution)

    if image_id1 is None or task_type is None:
        abort(404)
    if weight is not None:
        try:
            weight = float(weight)
        except:
            abort(404)
    if resolution is not None:
        try:
            resolution = int(resolution)
        except:
            abort(404)

    start = time.time()
    images = API.run(image_id1,
                     task_type,
                     weight,
                     image_id2=image_id2,
                     choice=choice,
                     resolution=resolution)
    print('Cost', time.time() - start)

    for i, image in enumerate(images):
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        img_str = cv2.imencode('.png', image)[1].tostring()
        images[i] = base64.b64encode(img_str).decode('ascii')

    return jsonify(images=images)
Exemplo n.º 9
0
def test_run_same_order_invariant():
    q = variables('q')
    assert list(run(q, same(q, 'pea'))) == list(run(q, same('pea', q)))
Exemplo n.º 10
0
def main():
    """
    The main function of the ACC program. It starts up the ACC and runs the
    webserver for the user interface.
    """
    api.run(True)

@app.errorhandler(ValidationError)
def handle_exception(e: ValidationError):

    res = {'code': e.status_code,
           'errorType': 'Validation Error',
           'errorMessage': e.message}
#    if debug:
#        res['errorMessage'] = e.message if hasattr(e, 'message') else f'{e}'

    return res, 400

@app.after_request
def after_request(response):
    """
    Enable CORS. Disable it if you don't need CORS or install Cors Libaray
    https://parzibyte.me/blog
    """
    response.headers[
        "Access-Control-Allow-Origin"] = "*"  # <- You can change "*" for a domain for example "http://localhost"
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE, PATCH"
    response.headers["Access-Control-Allow-Headers"] = \
        "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
    return response


if __name__ == "__main__":
    app.run(host=host, threaded=False)
Exemplo n.º 12
0
def _main(args):
    only_run = False

    if args['api']:
        if args['run']:
            api.run()
            return

    if args['init']:
        dagor_focus.rehome()
        dagor_track.run()

    if args['configure']:
        dagor_motors.init()
        dagor_motors.configure()
        return

    got_get_arg = any(
        (args['celest'], args['local'], args['altaz'], args['chirality']))
    if args['get'] and got_get_arg:
        values = {}
        template = ''
        if args['celest']:
            if args['human']:
                template = "ra={ra}\nde={de}"
            else:
                template = "{ra} {de}"
            values = dagor_position.get_celest()
            if not args['float']:
                values = {
                    'ra': format_hours(values['ra']),
                    'de': format_degrees(values['de']),
                }
        elif args['local']:
            if args['human']:
                template = "ha={ha}\nde={de}"
            else:
                template = "{ha} {de}"
            values = dagor_position.get_local()
            if not args['float']:
                values = {
                    'ha': format_hours(values['ha']),
                    'de': format_degrees(values['de']),
                }
        elif args['altaz']:
            if args['human']:
                template = "alt={alt}\naz={az}"
            else:
                template = "{alt} {az}"
            values = dagor_position.get_altaz()
            if not args['float']:
                values = {
                    'alt': format_degrees(values['alt']),
                    'az': format_degrees(values['az']),
                }
        elif args['chirality']:
            template = "{chirality}"
            values = {'chirality': dagor_position.get_chirality()}
        print(template.format(**values))
        return

    if args['goto'] and not args['focus']:
        track = False
        stop_on_target = True
        quick = True if args['quick'] else False
        target_celest = None
        chirality = None  # default: None (keep chirality)

        if args['ce']:
            chirality = dagor_position.CHIRAL_E
        if args['cw']:
            chirality = dagor_position.CHIRAL_W
        if args['cc']:
            chirality = dagor_position.CHIRAL_CLOSEST

        if args['home']:
            chirality = dagor_position.HOME_CHIRALITY
            if args['ce']:
                chirality = dagor_position.CHIRAL_E
            target_celest = dagor_position.altaz_to_celest(
                dagor_position.HOME_ALTAZ)
            quick = True
            stop_on_target = True

        if args['home2']:
            chirality = dagor_position.HOME_N_CHIRALITY
            if args['cw']:
                chirality = dagor_position.CHIRAL_W
            target_celest = dagor_position.altaz_to_celest(
                dagor_position.HOME_N_ALTAZ)
            quick = True
            stop_on_target = True

        if args['park']:
            chirality = dagor_position.PARK_CHIRALITY
            if args['ce']:
                chirality = dagor_position.CHIRAL_E
            target_celest = dagor_position.altaz_to_celest(
                dagor_position.PARK_ALTAZ)
            quick = True
            stop_on_target = True

        elif args['altaz']:
            track = True if args['track'] else False
            stop_on_target = not track
            altaz_end = {
                'alt': parse_degrees(args['<ALT>']),
                'az': parse_degrees(args['<AZ>']),
            }
            if chirality is None:
                chirality = dagor_position.CHIRAL_CLOSEST
            target_celest = dagor_position.altaz_to_celest(altaz_end)

        elif args['local']:
            track = True if args['track'] else False
            stop_on_target = not track
            local_end = {
                'ha': parse_hours(args['<HA>']),
                'de': parse_degrees(args['<DE>']),
            }
            target_celest = dagor_position.local_to_celest(local_end)

        elif args['celest'] or args['stellarium']:

            if args['celest']:
                target_celest = {
                    'ra': parse_hours(args['<RA>']),
                    'de': parse_degrees(args['<DE>']),
                }

            elif args['stellarium']:
                # read stdin:
                stellarium_ra_dec = None
                target_prefix = "RA/Dec ({}): ".format(
                    configuration.TRACKING["stellarium_mode"])
                print("Paste object info from"
                      " Stellarium then press Enter twice:")
                while True:
                    input_ = raw_input().strip()
                    if input_ == '':
                        break
                    if input_.startswith(target_prefix):
                        stellarium_ra_dec = input_[len(target_prefix):]
                if not stellarium_ra_dec:
                    sys.stderr.write(
                        'No line starts with "{}" in the pasted data.\n'
                        .format(target_prefix))
                    exit(1)
                stellarium_ra, stellarium_de = stellarium_ra_dec.split('/', 1)
                target_celest = {
                    'ra': parse_hours(stellarium_ra),
                    'de': parse_degrees(stellarium_de),
                }

            track = False if args['notrack'] else True
            stop_on_target = not track

        elif args['internal']:
            internal_end = {
                'ha': args['<int_HA>'],
                'de': args['<int_DE>'],
            }
            target_celest = dagor_position.internal_to_celest(internal_end)
            track = True if args['track'] else False
            stop_on_target = True

        elif args['this']:
            # stat tracking current coordinates
            track = True
            stop_on_target = False
            quick = False
            target_celest = None

        elif args['run']:
            # stat tracking current coordinates
            only_run = True

        # start track console:
        if only_run:
            dagor_track.run()
        else:
            dagor_track.speed_tracking(
                target_celest,
                chirality=chirality,
                target_is_static=not track,
                stop_on_target=stop_on_target,
                rough=quick,
                force=args['force'],
            )
        return

    if args['sync'] and args['console']:
        dagor_track.sync_console()
        return

    if args['stop']:
        dagor_motors.init()
        dagor_motors.stop()
        return

    if args['manual']:
        dagor_motors.set_manual()
        return

    if args['set']:
        if args['celest']:
            if args['<RA_DE>']:
                rade = args['<RA_DE>']
                try:
                    rade = rade.replace('RA ', '').replace('  Dec ', '')
                    arg_ra, arg_de = rade.split(',')
                except Exception:
                    raise ValueError('Cannot parse format')
            else:
                arg_ra = args['<RA>']
                arg_de = args['<DE>']
            ra = parse_hours(arg_ra)
            de = parse_degrees(arg_de)
            dagor_position.set_internal(
                dagor_position.celest_to_internal(
                    {'ra': ra, 'de': de}),
                args['blind'])

        if args['altaz']:
            arg_alt = args['<ALT>']
            arg_az = args['<AZ>']
            alt = parse_degrees(arg_alt)
            az = parse_degrees(arg_az)
            chirality = None
            if args['ce']:
                chirality = dagor_position.CHIRAL_E
            if args['cw']:
                chirality = dagor_position.CHIRAL_W

            dagor_position.set_internal(
                dagor_position.altaz_to_internal(
                    {'alt': alt, 'az': az},
                    chirality
                ),
                args['blind'])
        return

    if args['focus']:
        if args['get']:
            print(dagor_focus.get_position())
        elif args['set']:
            dagor_focus.set_position(args['<N>'])
        elif args['goto']:
            dagor_focus.goto(args['<N>'])
        elif args['rehome']:
            dagor_focus.rehome()
        return

    if args['motors']:
        if args['reset']:
            dagor_motors.reset(args['ha'], args['de'])
        if args['status']:
            dagor_motors.status_str(args['ha'] or None, args['de'] or None)
        return

    if args['dome']:
        if args['up']:
            dagor_dome.dome_up()
        if args['down']:
            dagor_dome.dome_down()
        if args['stop']:
            dagor_dome.dome_stop()
        if args['open']:
            dagor_dome.dome_open()
        if args['close']:
            dagor_dome.dome_close()
        return

    if args['lights']:
        n = None
        if args['0']:
            n = 0
        elif args['1']:
            n = 1
        elif args['2']:
            n = 2
        elif args['3']:
            n = 3
        if n is None:
            print(dagor_lights.get_lights())
        else:
            dagor_lights.set_lights(n)
        return

    if args['fans']:
        n = None
        if args['0']:
            n = 0
        elif args['1']:
            n = 1
        elif args['2']:
            n = 2
        if n is None:
            print(dagor_fans.get_fan(1))
        else:
            dagor_fans.set_fan(1, n)
        return
Exemplo n.º 13
0
def test_run_same():
    q = variables('q')
    assert list(run(q, same(q, 'pea'))) == ['pea']
Exemplo n.º 14
0
def startServer():
    GPIO.output(serverLed,True);
    app.run();
    GPIO.output(serverLed,False);
Exemplo n.º 15
0
# -*- coding: utf-8 -*-
#
#
# Author: alex
# Created Time: 2018年04月02日 星期一 14时53分50秒
from api import API, run


class Example:
    def hello(self, name='world'):
        return 'Hello {name}!'.format(name=name)


if __name__ == '__main__':
    API(Example)
    run(debug=True, output_json=False)
Exemplo n.º 16
0
def test_run_fresh():
    q = variables('q')
    r = run(q, fresh(lambda x: same([x], q)))
    assert list(r) == [['_0']]
Exemplo n.º 17
0
# -*- coding: utf-8 -*-
''' This is the actual Twitter API script entry point '''

from __future__ import absolute_import, division, unicode_literals
import os.path
import sys
from xbmc import translatePath
from xbmcaddon import Addon


def to_unicode(text, encoding='utf-8'):
    ''' Force text to unicode '''
    return text.decode(encoding) if isinstance(text, bytes) else text


sys.path.append(os.path.join(to_unicode(translatePath(Addon().getAddonInfo('path'))), 'lib'))
from api import run  # noqa: E402

run(sys.argv)
Exemplo n.º 18
0
 def Start(self):
     api.run()
Exemplo n.º 19
0
def execute_task(*args, **kwargs):
    tasks, command = args
    if command in tasks:
        return tasks[command]()
    else:
        return print(run(command))
Exemplo n.º 20
0
def test_run_succeed():
    q = variables('q')
    assert list(run(q, succeed)) == ['_0']
Exemplo n.º 21
0
def test_run_fresh_ignore_query_var():
    q = variables('q')
    r = run(q, fresh(lambda x: same(x, 'pea')))
    assert list(r) == ['_0']
Exemplo n.º 22
0
# -*- coding:utf-8 -*-
"""
@author: xuesu

"""

import api
import config

if __name__ == '__main__':

    app = api.run()
Exemplo n.º 23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# main
'''
:author:  madkote
:contact: madkote(at)bluewin.ch

Main
----
The main entry point

Usage
-----
>>> python main.py
'''

import api as app

VERSION = (0, 1, 0)

__all__ = []
__author__ = 'madkote <madkote(at)bluewin.ch>'
__version__ = '.'.join(str(x) for x in VERSION)


if __name__ == '__main__':
    app.run()
Exemplo n.º 24
0
import api

positions = api.run()

for (x, y) in positions():
	print("x: {0} y: {1}".format(x, y))
Exemplo n.º 25
0
def test_run_fail():
    q = variables('q')
    assert list(run(q, fail)) == []
Exemplo n.º 26
0
# -*- coding: utf-8 -*-
#
# 多个对象
# Author: alex
# Created Time: 2018年04月02日 星期一 14时53分50秒
from api import API, run


class Example:
    def hello(self, name='world'):
        """这是Example的hello帮助文档"""
        return 'Hello {name} in Example!'.format(name=name)


class Example2:
    def hello(self, name='world'):
        """
        这是Example2的hello帮助文档
        """
        return 'Hello {name} in Example2!'.format(name=name)


if __name__ == '__main__':
    API(Example)
    API(Example2)
    run(debug=True)
Exemplo n.º 27
0
Arquivo: test.py Projeto: ziaoang/demo
# encoding=utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf8")

import api

paragraph = "有一天晚上放学回来,我发现桌上摆着许多好吃的菜,那气氛好像是在等什么重要的客人。我急忙去问妈妈,妈妈说:“在等你奶奶。”正说着,奶奶骑着三轮车回来了。爸爸连忙迎上去,把奶奶的三轮车接了过来,妈妈也打来了一盆热水,让奶奶洗脸,然后把她扶到饭桌前坐下。这时,我从妈妈的口中得知,奶奶辛辛苦苦卖牙刷挣的钱都捐给了一位山区的失学儿童。那位失学儿童在重返校园的第一天,就给我们家寄来了一封感谢信,她在信中说,要以最好的成绩来报答我的奶奶。爸爸、妈妈准备这桌丰盛的晚餐,就是给奶奶“庆功”的!"

res_list = api.run(paragraph)

for res in res_list:
	print('-'*20)
	for v in res[0]:
		print(v)
	print('-'*20)
	print(res[1][0])
	print('-'*20)
	for v in res[2]:
		print(v)
	print('-'*20)
	for v in res[3]:
		print("%s\t%.4f"%(v[0], v[1]))
	
Exemplo n.º 28
0
def execute_task(*args, **kwargs):
    tasks, command = args
    if command in tasks:
        return tasks[command]()
    else:
        return print(run(command))
Exemplo n.º 29
0
def test_poso():
    x = variables("x")
    assert list(run(3, x, poso('abc'))) == []
    assert list(run(3, x, poso(42))) == ['_0']
    assert list(run(3, x, poso(x))) == [1, 2, 3]
Exemplo n.º 30
0
Options:
    -m --mock    Mock any hardware devices, useful for testing and development.
    -h --help    Show this screen or description of specific command.
    --version    Show version.
"""
import os
import sys
from docopt import docopt
from api import version, run

# noinspection PyUnboundLocalVariable
__doc__ = __doc__.format(VERSION=version)


# mock early, before first import:
if __name__ == '__main__':
    # noinspection PyUnboundLocalVariable
    args = docopt(__doc__, version=__doc__.strip().split('\n')[0])
    if args['run']:
        if args['--mock']:
            os.environ['DAGOR_API_MOCK'] = '1'


if __name__ == '__main__':
    API_DIR = os.path.dirname(__file__)
    BASE_DIR = os.path.dirname(API_DIR)
    sys.path.append(BASE_DIR)
    args = docopt(__doc__, version=__doc__.strip().split('\n')[0])
    if args['run']:
        run()
Exemplo n.º 31
0
def test_symeq_integers():
    a, x, y, z = variables("a, x, y, z")
    goal = conj(same(a, (x, y, z)), rangeo(-1, y, 2), rangeo(1, z, 3),
                symeq(x + y, z))
    assert list(run(a, goal)) == [(2, -1, 1), (1, 0, 1), (3, -1, 2), (0, 1, 1),
                                  (2, 0, 2), (1, 1, 2)]
Exemplo n.º 32
0
Arquivo: auto.py Projeto: Huni-0721/1
    from secret import *
except:
    with open('secret.py', 'w') as f:
        f.write('''
# single user or test settings
student_id = ''
password = ''

# database settings
host = '127.0.0.1'
port = 3306
user = ''
passwd = ''
db = ''
charset = 'utf8mb4'
''')
    print('请在 secret.py 中手动填写相应配置,并重新运行程序')
    sys.exit()

con = sql.connect(host=host,
                  port=port,
                  user=user,
                  passwd=passwd,
                  db=db,
                  charset=charset)
c = con.cursor()
c.execute('select school_id, password, name from pafd_student')
for datum in c.fetchall():
    print(datum[2], end='  ')
    print(run(datum[0], datum[1]))
con.close()
Exemplo n.º 33
0
def find_class(event):
    class_name = lb.get(lb.curselection())
    if api.run(class_name) is False:
        messagebox.askokcancel('敬请期待', '功能还在开发中,敬请期待')
Exemplo n.º 34
0
def test_rangeo():
    x = variables("x")
    assert list(run(x, rangeo(-2, 'abc', 2))) == []
    assert list(run(x, rangeo(-2, 42, 2))) == []
    assert list(run(x, rangeo(-2, -1, 2))) == ['_0']
    assert list(run(x, rangeo(-2, x, 2))) == [-2, -1, 0, 1]
Exemplo n.º 35
0
import argparse

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        prog="kanjiku_backend.py",
        description="a backend for a manga website",
    )

    parser.add_argument("--configfile",
                        "-cfg",
                        help="specify a config here",
                        default="./config.ini",
                        type=str)
    parser.add_argument(
        "--debug",
        "-d",
        action="store_true",
        help="should the backend be run in debug mode (default: false)",
        default=False,
    )

    inputvars = parser.parse_args()

    print(inputvars.configfile)

    config = ConfigObj(inputvars.configfile)

    #print(config["general"]["language"])
    run(config, inputvars.debug)
Exemplo n.º 36
0
import stock_rates
import db_init
import api
from datetime import date


if __name__ == "__main__":

    from_date = date(2005, 12, 30)
    to_date = date(2008, 1, 1)

    db_init.init(from_date, to_date)

    api.run()

Exemplo n.º 37
0
def run():
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, threaded=True, debug=True)