def save_chart(self): """This method uses a pre-defined XML layout and adds the random strings generated above and then saves the password chart as a png. :return: None """ xml_data = etree.fromstring(layout.get_layout()) for i in range(36): tmp = getattr(self, "label_{}".format(i)).text() etree.ETXPath( "//{%s}*[@id='label_%s']" % (u"http://www.w3.org/2000/svg", i))(xml_data)[0].text = tmp svg = etree.tostring(xml_data) file_handle, filename = tempfile.mkstemp() try: os.write(file_handle, svg) subprocess.call( # Default location of inkscape x64. Change if inkscape is # installed in a separate location [ r"C:\Program Files\Inkscape\inkscape.exe", filename, "--export-png", "password_chart.png", "--export-dpi", "96" ]) os.close(file_handle) finally: os.remove(filename)
def create_dash_app(): """ Creates the dash app and gets the related data """ app = Dash("expensor", external_stylesheets=[BOOTSTRAP]) app.config.supress_callback_exceptions = True app.title = c.names.TITLE app.layout = layout.get_layout() return app
def create_dash_app(): """ Creates the dash app and gets the related data """ app = Dash("expensor_personal", external_stylesheets=[BOOTSTRAP]) app.config.supress_callback_exceptions = True _ = dash_auth.BasicAuth(app, VALID_USERNAME_PASSWORD_PAIRS) app.title = c.names.TITLE app.layout = layout.get_layout() return app
def read_command(): """ Processes the command used to run the program from the command line. ([str]) -> { str : object } """ from argparse import ArgumentParser usage_str = """ USAGE: python red_bird.py <options> EXAMPLES: (1) python red_bird.py -p MinimaxAgent -l anuAdversarial -a depth=4 -b GreedyBlackBirdAgent --frame_time 0.05 will start an adversarial game with your MinimaxAgent vs the GreedyBlackBirdAgent on the anuAdversarial level (2) python red_bird.py -l anuAdversarial -p KeyboardAgent -b GreedyBlackBirdAgent will allow you to play with the keyboard on the same level """ parser = ArgumentParser(usage_str) parser.add_argument('-n', '--num_games', dest='num_games', type=int, action='store', help='the number of GAMES to play', metavar='GAMES', default=1) parser.add_argument( '-l', '--layout', dest='layout', help='the LAYOUT_FILE from which to load the map layout (Mandatory)', metavar='LAYOUT_FILE', default=None) parser.add_argument( '-b', '--black_bird', dest='black_bird', help='the black_bird agent TYPE in the agents module to use', metavar='TYPE', default='BlackBirdAgent') parser.add_argument( '-a', '--agent_args', dest='agent_args', help= 'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_argument( '-p', '--red_bird', dest='red_bird', help='the agent TYPE in the search_agents module to use', metavar='TYPE', default='KeyboardAgent') parser.add_argument('-t', '--text_graphics', action='store_true', dest='text_graphics', help='Display output as text only', default=False) parser.add_argument('-q', '--quiettext_graphics', action='store_true', dest='quiet_graphics', help='Generate minimal output and no graphics', default=False) parser.add_argument('-z', '--zoom', type=float, dest='zoom', help='Zoom the size of the graphics window', default=1.0) parser.add_argument( '-f', '--fix_random_seed', action='store_true', dest='fix_random_seed', help='Fixes the random seed to always play the same game', default=False) parser.add_argument('--frame_time', dest='frame_time', type=float, help='Time to delay between frames; <0 means keyboard', default=0.1) parser.add_argument( '-c', '--catch_exceptions', action='store_true', dest='catch_exceptions', help='Turns on exception handling and timeouts during games', default=False) parser.add_argument( '--timeout', dest='timeout', type=float, help= 'Maximum length of time an agent can spend computing in a single game', default=30) options = parser.parse_args() args = dict() # Fix the random seed if options.fix_random_seed: random.seed('comp3620_6320_2016') # Choose a layout if options.layout is None: raise SystemExit("[Fatal]: No map layout was specified!") args['layout'] = layout.get_layout(options.layout) if args['layout'] == None: raise SystemExit("[Fatal]: Map layout " + options.layout + " cannot be found") # Choose a red_bird agent no_keyboard = options.text_graphics or options.quiet_graphics red_bird_type = load_agent(options.red_bird, no_keyboard) agent_opts = parse_agent_args(options.agent_args) red_bird = red_bird_type( 0, **agent_opts) # Instantiate red_bird with agent_args args['red_bird'] = red_bird # Choose a black_bird agent black_bird_type = load_agent(options.black_bird, no_keyboard) if args['layout'].has_black_bird(): args['black_bird'] = black_bird_type(1) else: args['black_bird'] = None # Choose a display format if options.quiet_graphics: import text_display args['display'] = text_display.NullGraphics() elif options.text_graphics: import text_display text_display.SLEEP_TIME = options.frame_time args['display'] = text_display.RedBirdGraphics() else: import graphics_display args['display'] = graphics_display.RedBirdGraphics( options.zoom, frame_time=options.frame_time) args['num_games'] = options.num_games args['catch_exceptions'] = options.catch_exceptions args['timeout'] = options.timeout return args
def execute(self, grades, module_dict, solution_dict): """Test student's code. Overrides test_classes.TestCase.execute """ start_time = time.time() agent_type = getattr(module_dict['multi_agents'], self.agent_name) agent_opts = (pacman.parse_agent_args(self.agent_args) if self.agent_args != '' else {}) agent = agent_type(**agent_opts) lay = layout.get_layout(self.layout_name, 3) disp = self.question.display random.seed(self.seed) games = pacman.run_games(lay, agent, self.ghosts, disp, self.num_games, False, catch_exceptions=True, timeout=self.max_time) total_time = time.time() - start_time stats = { 'time': total_time, 'wins': [g.state.is_win() for g in games].count(True), 'games': games, 'scores': [g.state.get_score() for g in games], 'timeouts': [g.agent_timeout for g in games].count(True), 'crashes': [g.agent_crashed for g in games].count(True) } average_score = sum(stats['scores']) / float(len(stats['scores'])) non_timeouts = self.num_games - stats['timeouts'] wins = stats['wins'] def grade_threshold(value, minimum, thresholds, name): points = 0 passed = (minimum is None) or (value >= minimum) if passed: for t in thresholds: if value >= t: points += self.points_per_threshold return (passed, points, value, minimum, thresholds, name) results = [ grade_threshold(average_score, self.score_minimum, self.score_thresholds, "average score"), grade_threshold(non_timeouts, self.non_timeout_minimum, self.non_timeout_thresholds, "games not timed out"), grade_threshold(wins, self.wins_minimum, self.wins_thresholds, "wins") ] total_points = 0 for passed, points, value, minimum, thresholds, name in results: if minimum is None and len(thresholds) == 0: continue # print passed, points, value, minimum, thresholds, name total_points += points if not passed: assert points == 0 self.add_message("%s %s (fail: below minimum value %s)" % (value, name, minimum)) else: self.add_message("%s %s (%s of %s points)" % (value, name, points, self.points_per_threshold * len(thresholds))) if minimum is not None: self.add_message(" Grading scheme:") self.add_message(" < %-5s: fail" % (minimum, )) if len(thresholds) == 0 or minimum != thresholds[0]: self.add_message(" >= %-5s: 0 points" % (minimum, )) for idx, threshold in enumerate(thresholds): self.add_message(" >= %-5s: %s points" % (threshold, (idx + 1) * self.points_per_threshold)) elif len(thresholds) > 0: self.add_message(" Grading scheme:") self.add_message(" < %-5s: 0 points" % (thresholds[0], )) for idx, threshold in enumerate(thresholds): self.add_message(" >= %-5s: %s points" % (threshold, (idx + 1) * self.points_per_threshold)) if any([not passed for passed, _, _, _, _, _ in results]): total_points = 0 return self.test_partial(grades, total_points, self.max_points)
Dash app """ import pandas as pd from dash import Dash from dash.dependencies import Input, Output import plots import constants as c from layout import get_layout APP = Dash("auth") APP.config.supress_callback_exceptions = True APP.title = c.DASH_TITLE APP.layout = get_layout() SERVER = APP.server DF = pd.read_excel("data/indexa.xlsx") @APP.callback(Output("plot_one_invest", "figure"), [ Input("drop_method", "values"), Input("drop_size", "values"), Input("drop_risk", "values") ]) #pylint: disable=unused-variable,unused-argument def update_plot_one_invest(method, sizes, risks): """ Updates the one_invest plot """
from layout import get_layout from panels import CallBackLogic import sys import dash if __name__ == '__main__': app = dash.Dash() # Layout if len(sys.argv) != 2: raise ValueError( 'There should be one command line arguments specifying the location of the drift detector status directory.' ) dir = sys.argv[1] app.layout = get_layout(dir) # Callbacks @app.callback(CallBackLogic.get_outputs(), CallBackLogic.get_inputs()) def update_plots(*args): CallBackLogic.update(*args) return CallBackLogic.get_return() app.run_server(debug=False)
def read_command( argv ): """ Processes the command used to run the program from the command line. ([str]) -> { str : object } """ from optparse import OptionParser usage_str = """ USAGE: python red_bird.py <options> EXAMPLES: (1) python red_bird.py -p MinimaxAgent -l anuAdversarial -a depth=4 -b GreedyBlackBirdAgent --frame_time 0.05 will start an adversarial game with your MinimaxAgent vs the GreedyBlackBirdAgent on the anuAdversarial level (2) python red_bird.py -l anuAdversarial -p KeyboardAgent -b GreedyBlackBirdAgent will allow you to play with the keyboard on the same level """ parser = OptionParser(usage_str) parser.add_option('-n', '--num_games', dest='num_games', type='int', help=default('the number of GAMES to play'), metavar='GAMES', default=1) parser.add_option('-l', '--layout', dest='layout', help=default('the LAYOUT_FILE from which to load the map layout'), metavar='LAYOUT_FILE', default='anuMaze') parser.add_option('-b', '--black_bird', dest='black_bird', help=default('the black_bird agent TYPE in the agents module to use'), metavar = 'TYPE', default='BlackBirdAgent') parser.add_option('-a','--agent_args',dest='agent_args', help='Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"') parser.add_option('-p', '--red_bird', dest='red_bird', help=default('the agent TYPE in the search_agents module to use'), metavar='TYPE', default='KeyboardAgent') parser.add_option('-t', '--text_graphics', action='store_true', dest='text_graphics', help='Display output as text only', default=False) parser.add_option('-q', '--quiettext_graphics', action='store_true', dest='quiet_graphics', help='Generate minimal output and no graphics', default=False) parser.add_option('-z', '--zoom', type='float', dest='zoom', help=default('Zoom the size of the graphics window'), default=1.0) parser.add_option('-f', '--fix_random_seed', action='store_true', dest='fix_random_seed', help='Fixes the random seed to always play the same game', default=False) parser.add_option('--frame_time', dest='frame_time', type='float', help=default('Time to delay between frames; <0 means keyboard'), default=0.1) parser.add_option('-c', '--catch_exceptions', action='store_true', dest='catch_exceptions', help='Turns on exception handling and timeouts during games', default=False) parser.add_option('--timeout', dest='timeout', type='int', help=default('Maximum length of time an agent can spend computing in a single game'), default=30) options, otherjunk = parser.parse_args(argv) if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + str(otherjunk)) args = dict() # Fix the random seed if options.fix_random_seed: random.seed('comp3620_6320_2014') # Choose a layout args['layout'] = layout.get_layout( options.layout ) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a red_bird agent no_keyboard = options.text_graphics or options.quiet_graphics red_bird_type = load_agent(options.red_bird, no_keyboard) agent_opts = parse_agent_args(options.agent_args) red_bird = red_bird_type(0, **agent_opts) # Instantiate red_bird with agent_args args['red_bird'] = red_bird # Choose a black_bird agent black_bird_type = load_agent(options.black_bird, no_keyboard) if args['layout'].has_black_bird(): args['black_bird'] = black_bird_type( 1 ) else: args['black_bird'] = None # Choose a display format if options.quiet_graphics: import text_display args['display'] = text_display.NullGraphics() elif options.text_graphics: import text_display text_display.SLEEP_TIME = options.frame_time args['display'] = text_display.RedBirdGraphics() else: import graphics_display args['display'] = graphics_display.RedBirdGraphics(options.zoom, frame_time = options.frame_time) args['num_games'] = options.num_games args['catch_exceptions'] = options.catch_exceptions args['timeout'] = options.timeout return args
def read_command(argv): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usage_str = """ USAGE: python pacman.py <options> EXAMPLES: (1) python pacman.py - starts an interactive game (2) python pacman.py --layout small_classic --zoom 2 OR python pacman.py -l small_classic -z 2 - starts an interactive game on a smaller board, zoomed in """ parser = OptionParser(usage_str) parser.add_option('-n', '--num_games', dest='num_games', type='int', help=default('the number of GAMES to play'), metavar='GAMES', default=1) parser.add_option( '-l', '--layout', dest='layout', help=default('the LAYOUT_FILE from which to load the map layout'), metavar='LAYOUT_FILE', default='medium_classic') parser.add_option( '-p', '--pacman', dest='pacman', help=default('the agent TYPE in the pacman_agents module to use'), metavar='TYPE', default='KeyboardAgent') parser.add_option('-t', '--text_graphics', action='store_true', dest='text_graphics', help='Display output as text only', default=False) parser.add_option('-q', '--quiet_text_graphics', action='store_true', dest='quiet_graphics', help='Generate minimal output and no graphics', default=False) parser.add_option( '-g', '--ghosts', dest='ghost', help=default('the ghost agent TYPE in the ghost_agents module to use'), metavar='TYPE', default='RandomGhost') parser.add_option('-k', '--numghosts', type='int', dest='num_ghosts', help=default('The maximum number of ghosts to use'), default=4) parser.add_option('-z', '--zoom', type='float', dest='zoom', help=default('Zoom the size of the graphics window'), default=1.0) parser.add_option( '-f', '--fix_random_seed', action='store_true', dest='fix_random_seed', help='Fixes the random seed to always play the same game', default=False) parser.add_option( '-r', '--record_actions', action='store_true', dest='record', help= 'Writes game histories to a file (named by the time they were played)', default=False) parser.add_option('--replay', dest='game_to_replay', help='A recorded game file (pickle) to replay', default=None) parser.add_option( '-a', '--agent_args', dest='agent_args', help= 'Comma separated values sent to agent. e.g. "opt1=val1,opt2,opt3=val3"' ) parser.add_option( '-x', '--num_training', dest='num_training', type='int', help=default('How many episodes are training (suppresses output)'), default=0) parser.add_option( '--frame_time', dest='frame_time', type='float', help=default('Time to delay between frames; <0 means keyboard'), default=0.1) parser.add_option( '-c', '--catch_exceptions', action='store_true', dest='catch_exceptions', help='Turns on exception handling and timeouts during games', default=False) parser.add_option( '--timeout', dest='timeout', type='int', help=default( 'Maximum length of time an agent can spend computing in a single game' ), default=30) options, otherjunk = parser.parse_args(argv) if len(otherjunk) != 0: raise Exception('Command line input not understood: ' + str(otherjunk)) args = dict() # Fix the random seed if options.fix_random_seed: random.seed('cs188') # Choose a layout args['layout'] = layout.get_layout(options.layout) if args['layout'] == None: raise Exception("The layout " + options.layout + " cannot be found") # Choose a Pacman agent no_keyboard = options.game_to_replay == None and (options.text_graphics or options.quiet_graphics) pacman_type = load_agent(options.pacman, no_keyboard) agent_opts = parse_agent_args(options.agent_args) if options.num_training > 0: args['num_training'] = options.num_training if 'num_training' not in agent_opts: agent_opts['num_training'] = options.num_training pacman = pacman_type(**agent_opts) # Instantiate Pacman with agent_args args['pacman'] = pacman # Don't display training games if 'num_train' in agent_opts: options.num_quiet = int(agent_opts['num_train']) options.num_ignore = int(agent_opts['num_train']) # Choose a ghost agent ghost_type = load_agent(options.ghost, no_keyboard) args['ghosts'] = [ghost_type(i + 1) for i in range(options.num_ghosts)] # Choose a display format if options.quiet_graphics: import text_display args['display'] = text_display.NullGraphics() elif options.text_graphics: import text_display text_display.SLEEP_TIME = options.frame_time args['display'] = text_display.PacmanGraphics() else: import graphics_display args['display'] = graphics_display.PacmanGraphics( options.zoom, frame_time=options.frame_time) args['num_games'] = options.num_games args['record'] = options.record args['catch_exceptions'] = options.catch_exceptions args['timeout'] = options.timeout # Special case: recorded games don't use the run_games method or args structure if options.game_to_replay != None: print('Replaying recorded game %s.' % options.game_to_replay) import pickle f = open(options.game_to_replay) try: recorded = pickle.load(f) finally: f.close() recorded['display'] = args['display'] replay_game(**recorded) sys.exit(0) return args
def read_command(argv): """ Processes the command used to run pacman from the command line. """ from optparse import OptionParser usage_str = """ USAGE: python pacman.py <options> EXAMPLES: (1) python capture.py - starts a game with two baseline agents (2) python capture.py --keys0 - starts a two-player interactive game where the arrow keys control agent 0, and all other agents are baseline agents (3) python capture.py -r baseline_team -b my_team - starts a fully automated game where the red team is a baseline team and blue team is my_team """ parser = OptionParser(usage_str) parser.add_option('-r', '--red', help=default('Red team'), default='baseline_team') parser.add_option('-b', '--blue', help=default('Blue team'), default='baseline_team') parser.add_option('--red-name', help=default('Red team name'), default='Red') parser.add_option('--blue-name', help=default('Blue team name'), default='Blue') parser.add_option('--red_opts', help=default('Options for red team (e.g. first=keys)'), default='') parser.add_option('--blue_opts', help=default('Options for blue team (e.g. first=keys)'), default='') parser.add_option('--keys0', help='Make agent 0 (first red player) a keyboard agent', action='store_true', default=False) parser.add_option('--keys1', help='Make agent 1 (second red player) a keyboard agent', action='store_true', default=False) parser.add_option('--keys2', help='Make agent 2 (first blue player) a keyboard agent', action='store_true', default=False) parser.add_option('--keys3', help='Make agent 3 (second blue player) a keyboard agent', action='store_true', default=False) parser.add_option('-l', '--layout', dest='layout', help=default('the LAYOUT_FILE from which to load the map layout; use RANDOM for a random maze; use RANDOM<seed> to use a specified random seed, e.g., RANDOM23'), metavar='LAYOUT_FILE', default='default_capture') parser.add_option('-t', '--textgraphics', action='store_true', dest='textgraphics', help='Display output as text only', default=False) parser.add_option('-q', '--quiet', action='store_true', help='Display minimal output and no graphics', default=False) parser.add_option('-Q', '--super-quiet', action='store_true', dest="super_quiet", help='Same as -q but agent output is also suppressed', default=False) parser.add_option('-z', '--zoom', type='float', dest='zoom', help=default('Zoom in the graphics'), default=1) parser.add_option('-i', '--time', type='int', dest='time', help=default('TIME limit of a game in moves'), default=1200, metavar='TIME') parser.add_option('-n', '--num_games', type='int', help=default('Number of games to play'), default=1) parser.add_option('-f', '--fix_random_seed', action='store_true', help='Fixes the random seed to always play the same game', default=False) parser.add_option('--record', action='store_true', help='Writes game histories to a file (named by the time they were played)', default=False) parser.add_option('--replay', default=None, help='Replays a recorded game file.') parser.add_option('-x', '--num_training', dest='num_training', type='int', help=default('How many episodes are training (suppresses output)'), default=0) parser.add_option('-c', '--catch_exceptions', action='store_true', default=False, help='Catch exceptions and enforce time limits') options, otherjunk = parser.parse_args(argv) assert len(otherjunk) == 0, "Unrecognized options: " + str(otherjunk) args = dict() # Choose a display format #if options.pygame: # import pygame_display # args['display'] = pygame_display.PacmanGraphics() if options.textgraphics: import text_display args['display'] = text_display.PacmanGraphics() elif options.quiet: import text_display args['display'] = text_display.NullGraphics() elif options.super_quiet: import text_display args['display'] = text_display.NullGraphics() args['mute_agents'] = True else: import capture_graphics_display # Hack for agents writing to the display capture_graphics_display.FRAME_TIME = 0 args['display'] = capture_graphics_display.PacmanGraphics(options.red, options.blue, options.zoom, 0, capture=True) import __main__ __main__.__dict__['_display'] = args['display'] args['red_team_name'] = options.red_name args['blue_team_name'] = options.blue_name if options.fix_random_seed: random.seed('CSI480') # Special case: recorded games don't use the run_games method or args structure if options.replay != None: print('Replaying recorded game %s.' % options.replay) import pickle recorded = pickle.load(open(options.replay)) recorded['display'] = args['display'] replay_game(**recorded) sys.exit(0) # Choose a pacman agent red_args, blue_args = parse_agent_args(options.red_opts), parse_agent_args(options.blue_opts) if options.num_training > 0: red_args['num_training'] = options.num_training blue_args['num_training'] = options.num_training nokeyboard = options.textgraphics or options.quiet or options.num_training > 0 print('\nRed team %s with %s:' % (options.red, red_args)) red_agents = load_agents(True, options.red, nokeyboard, red_args) print('\nBlue team %s with %s:' % (options.blue, blue_args)) blue_agents = load_agents(False, options.blue, nokeyboard, blue_args) args['agents'] = sum([list(el) for el in zip(red_agents, blue_agents)], []) # list of agents num_keyboard_agents = 0 for index, val in enumerate([options.keys0, options.keys1, options.keys2, options.keys3]): if not val: continue if num_keyboard_agents == 0: agent = keyboard_agents.KeyboardAgent(index) elif num_keyboard_agents == 1: agent = keyboard_agents.KeyboardAgent2(index) else: raise Exception('Max of two keyboard agents supported') num_keyboard_agents += 1 args['agents'][index] = agent # Choose a layout import layout layouts = [] for i in range(options.num_games): if options.layout == 'RANDOM': l = layout.Layout(random_layout().split('\n')) elif options.layout.startswith('RANDOM'): l = layout.Layout(random_layout(int(options.layout[6:])).split('\n')) elif options.layout.lower().find('capture') == -1: raise Exception('You must use a capture layout with capture.py') else: l = layout.get_layout(options.layout) if l == None: raise Exception("The layout " + options.layout + " cannot be found") layouts.append(l) args['layouts'] = layouts args['length'] = options.time args['num_games'] = options.num_games args['num_training'] = options.num_training args['record'] = options.record args['catch_exceptions'] = options.catch_exceptions return args
# data stores ip = "172.26.132.96:5984" user = "******" pw = "123" db = database.database(ip, user, pw) db.connect() # app and server host = '127.0.0.1' # '172.26.134.13' port = '8050' #'3000' server = flask.Flask(__name__) app = dash.Dash(__name__, server=server, routes_pathname_prefix='/app/', external_stylesheets=layout.get_stylesheet()) app.layout = layout.get_layout() # invoke callbacks callbacks.positive_callback(app, 't-val', 'n_clicks', 'positive-chart') callbacks.negative_callback(app, 't-val', 'n_clicks', 'negative-chart') callbacks.trend_callback(app, 't-val', 'n_clicks', 'trends-chart') callbacks.unemp_callback(app, 't-val', 'n_clicks', 'unemployment-chart') def dump_data(database, idx): view_data = database.collect_data(idx) view_data.pop('_id', None) view_data.pop('_rev', None) return json.dumps(view_data)
__name__, external_stylesheets=[ dbc.themes.BOOTSTRAP, "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" ]) cache.init_app(app.server, config={ 'CACHE_TYPE': 'filesystem', 'CACHE_DIR': 'cache-directory', }) app.title = "Unacademy Analytics" app.config['suppress_callback_exceptions'] = True server = app.server app.layout = get_layout() @app.callback(dash.dependencies.Output('page-content', 'children'), [ dash.dependencies.Input('url', 'pathname'), Input('session_id', 'children') ]) def display_dashboard(pathname, session_id): if pathname == '/': return sleep_time.content elif pathname == '/sleep-time': return sleep_time.content elif pathname == '/routine': return routine.content elif pathname == '/mess': return mess.content
import dash_html_components as html from layout import get_layout from callbacks import * from app_setup import cyto_elements server = app.server app.title = 'CMU NET' app.layout = html.Div(children=get_layout(cyto_elements)) # Main if __name__ == "__main__": app.run_server(debug=True)
from layout import get_layout external_stylesheets = ['static/style.css'] # initial coordinates for the map lat0, lon0 = 36.107, -115.168 zoom0 = 12 pitch0 = bearing0 = 0 # Connect to Pulsar to get the metrics data and controller for the source latency_tracker = LatencyTracker() source_controller = SourceController('checkin_controller') redis_connector = RedisConnector() app = dash.Dash(__name__, external_stylesheets=external_stylesheets) app.layout = get_layout(lat0, lon0, zoom0, pitch0, bearing0) app.title = 'Skip-the-Line' server = app.server def create_latency_figure(max_len=60): """Create the average latency figure""" latency_tracker.update() keys = sorted(latency_tracker.time.keys()) now = datetime.datetime.now() time_vals = [ datetime.datetime.fromtimestamp(t) for t in latency_tracker.time['all'][-max_len:] ] latency = np.array(latency_tracker.latency['all'][-max_len:]) * 1e-3