예제 #1
0
def main():
    #handle argument
    parser = argparse.ArgumentParser(description='fetch and check free proxies')
    parser.add_argument('-v', '--verbose', action='store_true')
    parser.add_argument('-l', '--load', action='store_true', help='load hub.plk file')
    args = parser.parse_args(sys.argv[1:])

    if args.verbose:
        set_console_log_level(logging.DEBUG)

    if args.load:
        with (open("hub.pkl", "rb")) as f:
            _hub = pickle.load(f)
            hub = Hub(_hub)
    else:
        hub = Hub()

    log.info('Start')
    loop = asyncio.get_event_loop()
    queue = asyncio.Queue()
    factory = Factory(loop, queue, fetchers, hub)
    tasks = factory.get_tasks()
    tasks.append(asyncio.ensure_future(Server(hub).run()))
    tasks = asyncio.gather(*tasks, loop=loop)
    try:
        loop.run_until_complete(tasks)
    except KeyboardInterrupt:
        with open('hub.pkl', 'wb') as f:
            pickle.dump(hub.copy(), f, pickle.HIGHEST_PROTOCOL)
    finally:
        loop.close()
예제 #2
0
def setup_value(line_name, alist, conn=False):
    """
    Set value in instance type for all stations and all transfer points.
    """
    from station import Station
    from hub import Hub

    ls_instance = []
    for item in alist:
        ls_inform = item.split(':')
        flag_set = False
        if conn and len(ls_inform) == 4:
            new_instance = Hub()
            new_instance.conn = ls_inform[-1]
            flag_set = True

        if not conn:
            new_instance = Station()
            flag_set = True

        if flag_set:
            new_instance.name = ls_inform[1]
            new_instance.line = line_name
            new_instance.id = ls_inform[0]

        if not conn or conn and len(ls_inform) == 4:
            ls_instance.append(new_instance)

    return ls_instance
예제 #3
0
    def __init__(self, nLines=64, associativity=8, pageSize=0x1000, tlb=None, cache=None, hub=None):
        """Simple associative cache.

        Parameters
        ----------

        size (int):
            Cache size in bytes. (Default 0x8000 (32 kB))
        associtivilty (int):
            Number of ways for an associative cache, -1 for fully associative.
        cacheLine (int):
            Number of bytes per cache line, determiines the number of offset bits.
        child (Cache):
            The next level of cache, must be a hub for etlb, default is None, which means default Hub.
        """
        self.nLines = nLines
        self.associativity = associativity
        self.hub = hub
        self.cache = cache
        self.tlb = tlb
        self.pageSize = pageSize


        if self.associativity == -1:
            self.associativity = self.nLines

        if self.hub is None:
            self.hub = Hub(associativity=self.associativity, pageSize=self.pageSize)
        if self.cache is None:
            self.cache = Cache(size=0x8000, associativity=16)
            self.cache.accessEnergy = 0.0111033
            self.cache.accessTime = 4
            self.cache.tagTime = 1
            self.cache.tagEnergy = 0.000539962

        self.hub.eTLB = self

        self.cacheLine = self.cache.cacheLine

        self.nSets = self.nLines // self.associativity

        self.offsetBits = int(math.ceil(math.log2(self.cacheLine)))
        self.wayBits = int(math.ceil(math.log2(self.associativity)))
        self.pageBits = int(math.ceil(math.log2(self.pageSize))) - self.offsetBits
        self.setBits = int(math.ceil(math.log2(self.nSets)))
        self.tagBits = 48 - self.setBits - self.pageBits - self.offsetBits

        if self.tlb is None:
            self.tlb = TLB(512, self.tagBits + self.setBits)

        self.freeList = [list(range(self.associativity)) for i in range(self.nSets)]

        self.counter = 0
        self.entries = [[ETLBEntry(self.pageSize, self.cacheLine) for i in range(self.associativity)] for j in range(self.nSets)]

        self.hit = [0,0,0,0] #DRAM,L1I,L1D,L2  Note: L1 is actually a unified cache at present, for forward compatability if separate caches are ever implemented
        self.miss = 0
        self.cycles = 0
        self.energy = 0.
예제 #4
0
def main():
    # print(os.path.abspath(os.path.dirname(__file__)))

    # print(schema_etl)

    order_load = ["hub", "lnk", "sat", 'raw', 'hashed']
    for type_obj in order_load:
        for etl_val_obj in schema_etl[type_obj]:
            hub = Hub()
            next_sql = hub.generate_general_fill(etl_val_obj)
            print(next_sql)
예제 #5
0
    def test_post_success(self):
        r1 = self.delete_server_hub_map()

        self.assertEqual(r1.status_code, server.OK)

        r2 = self.post_server_hub_map()

        hub = Hub(restaurant_id=self.restaurant_id)

        self.assertEqual(r2.status_code, server.CREATED)
        self.assertTrue(hub.get_attendant_id(self.hub_id), self.attendant_id)
예제 #6
0
파일: server.py 프로젝트: edolinsky/cpen391
def restaurant_endpoint(table_id=''):
    """
    Handles creation and queries for restaurant data.
    :param table_id: hub device ID.
    :return: JSON or CSV response body and status code.
    """

    if request.method == 'GET':
        hub_id = request.args.get('table_id', table_id)

        hub = Hub('')
        hub.get_restaurant_id(hub_id=hub_id)

        # if Mime Type is CSV, respond with simple restaurant ID string.
        if request.content_type == 'text/csv':
            print hub.restaurant_id
            if hub.restaurant_id:
                return hub.restaurant_id, OK
            else:
                return 'error', BAD_REQUEST

        # Otherwise, respond in JSON format.
        else:
            if hub.restaurant_id:
                return jsonify({
                    'table_id': hub_id,
                    'restaurant_id': hub.restaurant_id
                }), OK
            else:
                return jsonify({
                    'table_id':
                    hub_id,
                    'error':
                    'Specified table ID is not affiliated with a restaurant.'
                }), BAD_REQUEST

    elif request.method == 'POST':
        request_body = flask.request.get_json()

        # Restaurant name must be supplied in request body.
        if 'name' in request_body:
            restaurant_name = request_body['name']
        else:
            request_body.update({'error': 'Restaurant name not specified.'})
            return jsonify(request_body), BAD_REQUEST

        # Create new restaurant, and return result to user.
        restaurant = Restaurant(restaurant_id='')
        restaurant_info = restaurant.create(name=restaurant_name)

        if 'error' in restaurant_info:
            return jsonify(restaurant_info), SERVER_ERROR
        else:
            return jsonify(restaurant_info), OK
예제 #7
0
 def __init__(self, _engine):
     super(Scene, self).__init__()
     self._ais = []
     self._engine = _engine
     self._resx, self._resy = _engine.getResolution()
     self.surface = pygame.Surface((self._resx, self._resy))
     drawText(self.surface, "Wczytywanie mapy...", 48, (255, 255, 255),
              (self._resx / 2, self._resy / 2))
     self._map = Map(_engine)
     self._hub = Hub(_engine, self._map)
     self._cursor = Cursor(_engine, self._map)
     self._ais.append(AI(_engine, self._map, _engine.players[0], 0))
     self._ais.append(AI(_engine, self._map, _engine.players[1], 1))
예제 #8
0
 def init(self, hubs_data):
     for data in hubs_data:
         data = json.loads(data.__repr__())
         # print(data)
         # print(data["location"])
         # print(data["sequence"])
         # sys.stdout.flush()
         self.hubs.append(Hub(id, data["location"]))
         for l in json.loads(data["sequence"]):
             # print("l: ", l)
             # sys.stdout.flush()
             object = l
             self.hubs[-1].addLayer(
                 SequenceLayer(object["user_id"], object["sound_id"],
                               object["rhythm"]))
예제 #9
0
    def run(self):
        hub = Hub(
            self.args.src,
            self.args.dst,
            self.args.dst_token,
            account_type=self.args.account_type,
            clone_style=self.args.clone_style,
            src_account_type=self.args.src_account_type,
            dst_account_type=self.args.dst_account_type,
        )
        src_type, src_account = self.args.src.split('/')

        # Using static list when static_list is set
        repos = self.static_list
        src_repos = repos if repos else hub.dynamic_list()

        total, success, skip = len(src_repos), 0, 0
        failed_list = []
        for src_repo in src_repos:
            # Set dst_repo to src_repo mapping or src_repo directly
            dst_repo = self.mappings.get(src_repo, src_repo)
            print("Map %s to %s" % (src_repo, dst_repo))
            if self.test_black_white_list(src_repo):
                print("Backup %s" % src_repo)
                try:
                    mirror = Mirror(
                        hub,
                        src_repo,
                        dst_repo,
                        cache=self.args.cache_path,
                        timeout=self.args.timeout,
                        force_update=self.args.force_update,
                    )
                    mirror.download()
                    mirror.create()
                    mirror.push()
                    success += 1
                except Exception as e:
                    print(e)
                    failed_list.append(src_repo)
            else:
                skip += 1
        failed = total - success - skip
        res = (total, skip, success, failed)
        print("Total: %s, skip: %s, successed: %s, failed: %s." % res)
        print("Failed: %s" % failed_list)
        if failed_list:
            sys.exit(1)
예제 #10
0
def default_hub(hub_name, genome, short_label, long_label, email):
    """
    Returns a fully-connected set of hub components using default filenames.
    """
    hub = Hub(
        hub=hub_name,
        short_label=short_label,
        long_label=long_label,
        email=email)
    genome = Genome(genome)
    genomes_file = GenomesFile()
    trackdb = TrackDb()
    hub.add_genomes_file(genomes_file)
    genomes_file.add_genome(genome)
    genome.add_trackdb(trackdb)
    return hub, genomes_file, genome, trackdb
예제 #11
0
    def init(self, hub_files):
        id = 0
        for f in hub_files:
            with open(f, 'r') as data:
                location = f.replace(".hub", "")
                id += 1
                self.hubs.append(Hub(id, location))

                for l in data:
                    object = json.loads(l)
                    self.hubs[-1].addLayer(
                        SequenceLayer(object["user_id"], object["sound_id"],
                                      object["rhythm"]))

        for h in self.hubs:
            print(h.getLocation())
            print(h.getHubObject())
예제 #12
0
    def test_delete_success(self):
        r1 = self.delete_server_hub_map()

        self.assertEqual(r1.status_code, server.OK)
        self.assertTrue('message' in r1.json())

        r2 = self.delete_server_hub_map()

        self.assertEqual(r2.status_code, server.OK)
        self.assertTrue('message' in r2.json())

        # Place mapping back in db.
        r3 = self.post_server_hub_map()

        hub = Hub(restaurant_id=self.restaurant_id)

        self.assertEqual(r3.status_code, server.CREATED)
        self.assertTrue(hub.get_attendant_id(self.hub_id), self.attendant_id)
예제 #13
0
    def __init__(self, _engine):
        super(Scene, self).__init__()

        if not Scene.image:
            Scene.image = loadImage('data/gfx/background.png')

        self._engine = _engine
        self._resx, self._resy = _engine.getResolution()
        self._background = pygame.transform.smoothscale(
            self.image, (self._resx, self._resy))
        self.surface = self._background.copy()
        drawText(self.surface, "Poziom %d..." % self._engine.game['level'], 48,
                 (255, 255, 255), (self._resx / 2, self._resy / 2))
        self._engine.show(self.surface)
        self._hub = Hub(_engine)
        self.planets = pygame.sprite.Group()
        self.rocket = pygame.sprite.GroupSingle()
        self.stars = pygame.sprite.Group()
        self.canisters = pygame.sprite.Group()
        self._first = True
예제 #14
0
def run_game():
    """ Main game structure that runs the whole program """
    # Initialize pygame
    pygame.init()

    # Set up the hub
    hub = Hub()
    pygame.display.set_caption(hub.WINDOW_TITLE)
    pygame.display.set_icon(hub.WINDOW_ICON)

    while True:
        """ Game Loop, as long as this is true the game will run. """
        # Clear Screen
        hub.main_screen.fill(hub.BG_COLOR)

        # Decide what screen to display
        hub.display_screen()

        # Display the screen onto the window
        pygame.display.flip()
        dt = hub.CLOCK.tick(hub.FRAMERATE)
        hub.speed = 1 / float(dt)
예제 #15
0
파일: server.py 프로젝트: edolinsky/cpen391
def call_server_endpoint():
    """
    Gateway for mobile notifications as initiated by a table hub.
    :return: JSON response body and status code.
    """
    request_body = flask.request.get_json()

    # Restaurant ID and Table ID must be specified in request body.
    if 'restaurant_id' in request_body:
        restaurant_id = request_body['restaurant_id']
    else:
        request_body.update({'error': 'Restaurant ID is not specified.'})
        return jsonify(request_body), BAD_REQUEST
    if 'table_id' in request_body:
        table_id = request_body['table_id']
    else:
        request_body.update({'error': 'Table ID is not specified.'})
        return jsonify(request_body), BAD_REQUEST

    hub = Hub(restaurant_id=restaurant_id)
    user = User('')

    # Get current attendant user from hub information.
    attendant_id = hub.get_attendant_id(hub_id=table_id)
    attendant_app_id = user.get_app_id(attendant_id)

    # Get table name for message body.
    table_name = hub.get_table_name(hub_id=table_id)

    # Trigger notification to attendant.
    success = hub.trigger_notification(attendant_app_id=attendant_app_id,
                                       table_name=table_name)
    if success:
        request_body.update({'message': 'Notification Successful.'})
        return jsonify(request_body), OK
    else:
        request_body.update({'error': 'Could not send Notification.'})
        return jsonify(request_body), SERVER_ERROR
예제 #16
0
파일: agent.py 프로젝트: automenta/beccaj
    def __init__(self,
                 num_sensors,
                 num_actions,
                 show=True,
                 agent_name='test_agent'):
        """
        Configure the Agent

        num_sensors and num_actions are the only absolutely necessary
        arguments. They define the number of elements in the 
        sensors and actions arrays that the agent and the world use to
        communicate with each other. 
        """
        self.BACKUP_PERIOD = 10**4
        self.show = show
        self.name = agent_name
        self.pickle_filename = "log/" + agent_name + ".pickle"
        # TODO: Automatically adapt to the number of sensors pass in
        self.num_sensors = num_sensors
        self.num_actions = num_actions

        # Initialize agent infrastructure
        self.num_blocks = 1
        first_block_name = ''.join(('block_', str(self.num_blocks - 1)))
        self.blocks = [
            Block(self.num_actions + self.num_sensors, name=first_block_name)
        ]
        self.hub = Hub(self.blocks[0].max_cables)
        self.action = np.zeros((self.num_actions, 1))
        self.cumulative_reward = 0
        self.time_since_reward_log = 0
        self.reward_history = []
        self.reward_steps = []
        self.surprise_history = []
        self.recent_surprise_history = [0.] * 100
        self.timestep = 0
        self.graphing = True
import config
from hub import Hub

hub = Hub(
    solar_temp = None,
    tank_temp = None,
    tank_target_temp = config.TANK_TARGET_TEMP,
    pump = False,
    mode = 'auto',
)

from internet import Internet
internet = hub.add(Internet)

from temperature import Temperature
hub.add(Temperature)

from display import Display
hub.add(Display, priority=True)

from controller import Controller
hub.add(Controller, priority=True)

from pump import Pump
hub.add(Pump, priority=True)

from components.retain import Retain
hub.add(Retain)

hub.run()
예제 #18
0
# set required vdc variables before calling function
vdc.tags = config.default_tags
# all resources will be created in configuration location
resource_group_name = vdc.resource_group(config.stack)

# single hub with gateways, firewall, DMZ, shared services, bastion (optional)
hub = Hub(
    'hub',  # stem of child resource names (<4 chars)
    HubProps(
        azure_bastion=config.azure_bastion,
        forced_tunnel=config.forced_tunnel,
        firewall_address_space=config.firewall_address_space,
        hub_address_space=config.hub_address_space,
        peer=config.peer,
        reference=config.reference,
        resource_group_name=resource_group_name,
        stack=config.stack,
        subnets=[  # extra columns for future ASGs
            ('domain', 'any', 'any'),
            ('files', 'any', 'none'),
        ],
        tags=config.default_tags,
    ),
)

# multiple spokes for application environments with bastion access (optional)
spoke1 = Spoke(
    's01',  # stem of child resource names (<6 chars)
    SpokeProps(
        azure_bastion=config.azure_bastion,
        fw_rt_name=hub.fw_rt_name,
예제 #19
0
    auto_unregister = True
    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()

        if opt == "--disable-unregister":
            auto_unregister = False

    if len(args) != 1:
        usage("incorrect number of arguments")
    instance_id = args[0]

    apikey = os.getenv('HUB_APIKEY', None)
    if not apikey:
        fatal("HUB_APIKEY not specified in environment")

    hub = Hub(apikey)

    try:
        server = hub.servers.get(instance_id)[0]
        server.destroy(auto_unregister=auto_unregister)
    except hub.Error, e:
        fatal(e.description)

    print fmt_server_header()
    print fmt_server(server)

if __name__ == "__main__":
    main()

예제 #20
0
 def generateHubs(self):
     hub = Hub((50, 50))
     for row in range(self.gridsize):
예제 #21
0
loop = ZMQIOLoop()
loop.install()

settings = {
    'xsrf_cookies': False,
    'debug': True,
    'autoreload': True,
    'websocket_ping_interval': 60  # 定时发送ping, 保持心跳
}

app = tornado.web.Application([
    (r'/ws', PushWebSocket),
], **settings)

if __name__ == '__main__':
    port = '8000'
    remote = '127.0.0.1:5560'  # MPC 消息发布中心 发布 地址

    opts, argvs = getopt.getopt(sys.argv[1:], 'r:p:')
    for op, value in opts:
        if op == '-r':
            remote = value
        if op == '-p':
            port = int(value)

    Hub(*remote.split(':'))

    app.listen(port)

    loop.start()
예제 #22
0
import hashlib
import hmac
import os

from auth import KeyProvider
from hub import Hub

# Without `pure=True`, I get an exception about str / byte issues
yaml = YAML(typ='safe', pure=True)

HERE = Path(__file__).parent
PROXY_SECRET_KEY = bytes.fromhex(os.environ['PROXY_SECRET_KEY'])

AUTH0_DOMAIN = 'yuvipanda.auth0.com'
auth0_token = KeyProvider.get_token(
    AUTH0_DOMAIN, os.environ['AUTH0_MANAGEMENT_CLIENT_ID'],
    os.environ['AUTH0_MANAGEMENT_CLIENT_SECRET'])

k = KeyProvider(AUTH0_DOMAIN, auth0_token)


def load_hubs():
    with open(HERE / "hubs.yaml") as f:
        return yaml.load(f)


hubs = load_hubs()

for hub_yaml in hubs['hubs']:
    hub = Hub(hub_yaml, k, PROXY_SECRET_KEY)
    hub.deploy()
예제 #23
0
 def __init__(self, spec, config_path):
     self.spec = spec
     self.config_path = config_path
     self.hubs = [Hub(self, hub_spec) for hub_spec in self.spec["hubs"]]
     self.support = self.spec.get("support", {})
예제 #24
0
파일: server.py 프로젝트: edolinsky/cpen391
def order_endpoint(order_id='', restaurant_id='', customer_id='', table_id=''):
    """
    Handles user- or staff-initiated requests pertaining to individual orders.
    This endpoint does not handle order status.
    :param order_id: Unique order ID (only for GET/PUT).
    :param restaurant_id: Unique restaurant ID.
    :param customer_id: Unique user ID of customer.
    :param table_id: Unique hub device ID.
    :return: JSON response body and status code.
    """

    if request.method in ['POST', 'PUT']:
        # Request has json body.
        order_request = flask.request.get_json()
        restaurant_id = order_request.get('restaurant_id', '')
        customer_id = order_request.get('customer_id', '')
        table_id = order_request.get('table_id', '')

    else:
        # GET request
        restaurant_id = request.args.get('restaurant_id', restaurant_id)
        order_id = request.args.get('order_id', order_id)
        customer_id = request.args.get('customer_id', customer_id)
        table_id = request.args.get('table_id', table_id)
        order_request = {}

        # Order ID must be non-empty.
        if not order_id:
            order_request.update({'error': 'Order ID must be specified.'})
            return jsonify(order_request), BAD_REQUEST

    if not restaurant_id:
        order_request.update({'error': 'Restaurant ID is not specified.'})
        return jsonify(order_request), BAD_REQUEST

    if not customer_id:
        order_request.update({'error': 'Customer ID is not specified.'})
        return jsonify(order_request), BAD_REQUEST

    if not table_id:
        order_request.update({'error': 'Table ID is not specified.'})
        return jsonify(order_request), BAD_REQUEST

    # Restaurant must exist in database.
    restaurant = Restaurant(restaurant_id=restaurant_id)
    if not restaurant.exists():
        order_request.update({'error': 'Specified restaurant does not exist.'})
        return jsonify(order_request), BAD_REQUEST

    # Customer must exist in database.
    user = User('')
    user.get_email(customer_id)
    if not user.exists():
        order_request.update({'error': 'Specified customer does not exist.'})
        return jsonify(order_request), BAD_REQUEST

    # Table must exist and be affiliated with the restaurant.
    hub = Hub(restaurant_id=restaurant_id)
    if not hub.is_registered(hub_id=table_id):
        order_request.update(
            {'error': 'Specified table is not registered to this restaurant.'})
        return jsonify(order_request), UNAUTHORIZED

    order = Order(restaurant_id=restaurant_id)

    if request.method == 'GET':
        order_info = order.get_order(order_id=order_id,
                                     restaurant_id=restaurant_id,
                                     content_type=request.content_type)
        if request.content_type == 'text/csv':
            return order_info
        elif 'error' in order_info:
            return jsonify(order_info), SERVER_ERROR
        else:
            return jsonify(order_info), OK

    if request.method == 'POST':

        # List of items must exist and must be non-empty.
        if 'items' not in order_request:
            order_request.update({'error': 'List of items is not specified.'})
            return jsonify(order_request), BAD_REQUEST

        elif len(order_request['items']) < 1:
            order_request.update({'error': 'List of items is empty.'})
            return jsonify(order_request), BAD_REQUEST

        order_response = order.place_order(order=order_request,
                                           customer_id=customer_id,
                                           table_id=table_id)
        if 'error' in order_response:
            return jsonify(order_response), SERVER_ERROR
        else:
            return jsonify(order_response), OK

    if request.method == 'PUT':
        # PUT -> update order (insert/update)
        pass
예제 #25
0
파일: server.py 프로젝트: edolinsky/cpen391
def server_hub_map_endpoint(restaurant_id='', attendant_id=''):
    """
    Handles updates to waitstaff/table mappings, which is used for
    mobile notifications.
    :return: JSON response body and status code.
    """
    if request.method == 'POST':
        # POST Request.
        request_body = flask.request.get_json()
        restaurant_id = request_body.get('restaurant_id', '')
    elif request.method == 'GET':
        # GET Request.
        restaurant_id = request.args.get('restaurant_id', restaurant_id)
        request_body = {}
    else:
        # DELETE Request.
        restaurant_id = request.args.get('restaurant_id', restaurant_id)
        attendant_id = request.args.get('attendant_id', attendant_id)
        request_body = {}

    # Restaurant ID must be specified.
    if not restaurant_id:
        request_body.update({'error': 'Restaurant ID not specified.'})
        return jsonify(request_body), BAD_REQUEST

    restaurant = Restaurant(restaurant_id=restaurant_id)
    if not restaurant.exists():
        request_body.update({'error': 'Specified restaurant does not exist.'})
        return jsonify(request_body), BAD_REQUEST

    if request.method == 'POST':
        # update keys.
        if 'mappings' not in request_body:
            request_body.update({'error': 'Mappings not specified.'})
            return jsonify(request_body), BAD_REQUEST
        elif len(request_body['mappings']) < 1:
            request_body.update({'error': 'Mappings list is empty.'})
            return jsonify(request_body), BAD_REQUEST

        mappings = request_body['mappings']

        for mapping in mappings:
            user = User('')
            user_id = mapping.get('attendant_id', '')
            user.get_email(user_id=user_id)

            hub = Hub(restaurant_id=restaurant_id)
            hub_id = mapping.get('table_id', '')

            # User must exist, and be associated with the specified restaurant.
            if not user.exists():
                request_body.update({
                    'error':
                    'Specified user {} does not exist.'.format(user_id)
                })
                return jsonify(request_body), BAD_REQUEST

            elif user.get_my_restaurant(user_id=user_id) != restaurant_id:
                request_body.update({
                    'error':
                    'Specified user {} is not affiliated with specified restaurant.'
                    .format(user_id)
                })
                return jsonify(request_body), UNAUTHORIZED

            # Specified hub must be associated with the specified restaurant.
            if not hub.is_registered(hub_id=hub_id):
                request_body.update({
                    'error':
                    'Specified table ID {} is not affiliated with specified restaurant.'
                    .format(hub_id)
                })
                return jsonify(request_body), UNAUTHORIZED

        mapping_info = restaurant.update_staff_hub_mappings(
            mapping_info=request_body)
        return jsonify(mapping_info), CREATED

    elif request.method == 'GET':
        # GET all mappings in restaurant (with emails).
        mappings = restaurant.get_staff_hub_mappings()
        request_body.update(mappings)

        if 'error' in mappings:
            return jsonify(request_body), SERVER_ERROR
        else:
            return jsonify(request_body), OK

    elif request.method == 'DELETE':

        # Attendant ID must be specified.
        if not attendant_id:
            request_body.update({'error': 'User ID not specified.'})
            return jsonify(request_body), BAD_REQUEST

        user = User('')
        user.get_email(user_id=attendant_id)

        # Specified user must exist and be associated with the specified restaurant.
        if not user.exists():
            request_body.update({'error': 'Specified user does not exist.'})
            return jsonify(request_body), BAD_REQUEST

        elif user.get_my_restaurant(user_id=attendant_id) != restaurant_id:
            request_body.update(
                {'error': 'User restaurant combination does not match.'})
            return jsonify(request_body), UNAUTHORIZED

        response = restaurant.remove_staff_from_mappings(staff_id=attendant_id)
        request_body.update(response)

        if 'error' in response:
            return jsonify(response), SERVER_ERROR
        else:
            return jsonify(response), OK
예제 #26
0
파일: __main__.py 프로젝트: snegas/examples
    ref = f'{org}/{project}/{peer}'
else:
    ref = None

# single hub virtual network with gateway, firewall, DMZ and shared services
hub = Hub(
    'hub',  # stem of child resource names (<4 chars)
    HubProps(
        resource_group_name=resource_group_name,
        tags=default_tags,
        stack=stack,
        dmz_ar=config.require('firewall_dmz_subnet'),
        fwm_ar=config.get('firewall_management_subnet'),
        fws_ar=config.require('firewall_subnet'),
        fwz_as=config.require('firewall_address_space'),
        gws_ar=config.require('hub_gateway_subnet'),
        hbs_ar=config.get('hub_bastion_subnet'),
        hub_ar=config.require('hub_first_subnet'),
        hub_as=config.require('hub_address_space'),
        peer=peer,
        ref=ref,
        subnets=[  # extra columns for future NSGs
            ('domain', 'any', 'any'),
            ('files', 'any', 'none'),
        ],
    ),
)

# multiple spoke virtual networks for application environments
spoke1 = Spoke(
    's01',  # stem of child resource names (<6 chars)
    SpokeProps(
예제 #27
0
import config
from hub import Hub

hub = Hub(
    valve_open = False,
)

from ball_valve import BallValve
valve = hub.add(BallValve)

batt_low = False

if config.BATT:
    from components.battery import Battery
    hub.add(Battery)
    batt_low = valve.check_battery(hub)

if not batt_low:
    if config.BTN:
        from button import Button
        hub.add(Button)

    from internet import Internet
    internet = hub.add(Internet)

    hub.run()
import config
from hub import Hub

hub = Hub(
    count=-1,
    battery=100,
)

from internet import Internet
internet = hub.add(Internet)

from counter import Counter
hub.add(Counter)

if config.BATT:
    from components.battery import Battery
    hub.add(Battery)

hub.run()
import config
from hub import Hub

hub = Hub(
    light=False,
    light_cmd=False,
    brightness=config.INIT_BRI,
    motion=False,
    enable=False,
    auto=False,
    battery=100,
)

config.RETAIN = set(('light', ))

if config.BRIGHTNESS:
    config.RETAIN.add('brightness')

if config.BATT:
    config.RETAIN.add('battery')

if config.MOTN:
    config.RETAIN.add('auto')
    config.RETAIN.add('enable')

if len(config.RETAIN) > 0:
    from components.retain import Retain
    hub.add(Retain)

from light import Light
hub.add(Light, priority=True)  # put light above retain
예제 #30
0
파일: __main__.py 프로젝트: sylver/examples
stack = get_stack()
default_tags = {'environment': stack}

# all resources will be created in the Resource Group location
resource_group = core.ResourceGroup(
    stack + '-vdc-rg-',
    tags=default_tags,
)

# Hub virtual network with gateway, firewall, DMZ and shared services subnets
hub1 = Hub(
    config.require('hub_stem'),
    HubProps(
        config=config,
        resource_group=resource_group,
        tags=default_tags,
        stack=stack,
    ),
    opts=ResourceOptions(
        custom_timeouts=CustomTimeouts(create='1h', update='1h', delete='1h')),
)

# Spoke virtual network for application environments
spoke1 = Spoke(
    config.require('spoke_stem'),
    SpokeProps(
        config=config,
        resource_group=resource_group,
        tags=default_tags,
        hub=hub1,
    ),