def test3(): try: a = Scenario() except TypeError: a = Scenario(1, 2, 3, 4, 5, 6, 7) print(a) b = [a] c = [x.d for x in b] print(c)
def run_sim(d, scrip, a, amount, ledger): net_buys = 0 for i in a: f = d.get_first(i) s = d.stocks.get(f) qty = int(float(amount) / float(s.high)) net_buys += qty t0 = Transaction(scrip, BUY, s.date, s.high, qty) ledger.append(t0) a0 = d.get_last(a[-1]) s0 = d.stocks.get(a0) t1 = Transaction(scrip, SELL, s0.date, s0.high, net_buys) ledger.append(t1) # for i in ledger: # print( i.to_str(), i.tx_value()) investment = sum( [float(x.price) * x.qty for x in ledger if x.action == BUY]) sale = 0 profit = 0 roi = 0 if not investment == 0: sale = sum( [float(x.price) * x.qty for x in ledger if x.action == SELL]) profit = (sale - investment) roi = round((profit * 100) / investment, 2) #print( "Roi for {} months starting {} is {}".format( len(a) , a[0], round( roi,2))) scenario = Scenario(a[0], len(a), amount, profit, investment, ledger, roi) return scenario
async def new_game(sid, data: SioNewGame): """Handle the incoming request for creating a new game. A new game instance is created for the provided scenario. The game ID and the join password is returned as payload with event 'NEW_GAME'. A user_name will be provided, user_id will be initial and generated within this method. """ sio_data = SioNewGame.parse_obj(data) log.debug(f"Incoming request for creating a new game from {sio_data.user_name} ({sid})" f"for scenario {sio_data.game_scenario}.") # Create a new game instance. player = Player(sid, sio_data.user_name, sio_data.user_id) game = GameFactory().create(Scenario(id=sio_data.game_scenario), player) game_controller.add(game) # Update the user session with the new game. sess: SioSession = await sio.get_session(sid) sess.game = game sess.player = player await sio.save_session(sid, sess) log.debug(f"New game created with ID {game.id} and password {game.pwd}.") # Create a new socket IO room for the game. sio.enter_room(sid, game.id) # Emit the event that the game has been successfully created. sio_data.game = game sio_data.user_id = player.user_id log.debug(f"Emitting event {NEW_GAME} to {sio_data.user_name} ({sid}).") await sio.emit(NEW_GAME, data=sio_data.emit(), room=sid)
def test_click(self): scenario = Scenario({ "variables": [], "steps": [{ "action": "open_url", "value": "http://felt.sava.be/" }, { "action": "click", "selector": "#navbar > ul > li:nth-child(2) > a", }] }) result = self.runTest(scenario) self.assertEqual(2, len(result)) # Check action 1 self.assertLess(result[0]['start'], result[0]['end']) self.assertTrue(result[0]['success']) self.assertEquals(result[0]['time'], result[0]['end'] - result[0]['start']) self.assertEquals('http://felt.sava.be/', result[0]['url']) self.assertEquals('open_url', result[0]['step']['action']) self.assertEquals('http://felt.sava.be/', result[0]['step']['value']) # Check action 2 self.assertLess(result[1]['start'], result[1]['end']) self.assertTrue(result[1]['success']) self.assertEquals(result[1]['time'], result[1]['end'] - result[1]['start']) self.assertEquals('http://felt.sava.be/settings.php', result[1]['url']) self.assertEquals('click', result[1]['step']['action']) self.assertEquals('#navbar > ul > li:nth-child(2) > a', result[1]['step']['selector'])
def delete_scene(self, args, guild, channel, scenario, sc, user): messages = [] search = '' if len(args) == 1: if not sc: raise Exception('No scene provided for deletion') else: search = ' '.join(args[1:]) sc = Scene().find(guild.name, str(channel.id), str(scenario.id), search) if not sc: return [f'{search} was not found. No changes made.'] else: search = str(sc.name) scenario_id = str(sc.scenario_id) if sc.scenario_id else '' channel_id = str(sc.channel_id) if sc.channel_id else '' sc.character.archive(user) sc.archived = True sc.updated_by = str(user.id) sc.updated = T.now() sc.save() messages.append(f'***{search}*** removed') if scenario_id: secenario = Scenario().get_by_id(scenario_id) messages.append(secenario.get_string(channel)) elif channel_id: channel = Channel().get_by_id(channel_id) messages.append(channel.get_string()) return messages
def test_multiple(self): scenario = Scenario({ "variables": [{ "type": "constant", "value": "1", "name": "first_var" }, { "type": "constant", "value": "$[first_var]2", "name": "second_var" }, { "type": "constant", "value": "$[second_var]3", "name": "third_var" }], "steps": [{ "action": "set_value", "selector": "element", "value": "$[third_var]" }] }) self.assertEqual(scenario.preprocessScenario(), [{ 'action': 'set_value', 'value': '123', 'selector': 'element' }])
async def get_scenario(scenario_id: int) -> Scenario: return Scenario(id=scenario_id, titel='Asperger Syndrome: School inclusion', descr='**The scenario**\n\nMartin is an 10 year old boy with a level 2 Asperger Syndrome, ' + 'a type of autism.\nThe ethical decision is about whether Martin shall attend a ' + 'regular school ' + 'with an inclusion concept or a special school.', background_info='**Asperger syndrome - general information**\n\n' + 'Asperger syndrome (AS) is a milder autism spectrum disorder. AS is a lifelong ' + 'developmental disorder that includes differences or challenges in social ' + 'communication skills, fine and gross motor skills, speech, and intellectual ' + 'ability. The severity of autism is categorized as\n' + '* 1 - high–functioning,\n' + '* 2 – moderately severe and\n' + '* 3 – severe', decision_options=[DecisionOption(id='1', titel='What is the best choice for Martin?', descr='Shall Martin attend a regular school with ' + 'inclusion concept or a special school?')], personas=PersonaComposition( mandatory=[Persona(id=1, name='Martin, child with Asperger syndrome', descr='Martin is 10 years old with level 2 AS.'), Persona(id=2, name='Martin\'s parents', descr='- The family has modest income, only the father is employed\n' + '- Financial problems are associated with Martin\'s medical and ' + 'therapy expensed.'), Persona(id=3, name='Helen - teacher', descr='- She is perceived as patient, persistent and grateful.\n' + '- She is a good communicator, creative and inventing method to ' + 'help a child master the skills required by the curriculum ' + 'plan.')]) )
def on_new_game(data): # Store the game ID and game password. self.new_game_model.game = Game( scenario=Scenario(id=self.new_game_model.game_scenario), host=Player( sid=self.client1.sid, user_id=data['user_id'], user_name=data['user_name'], ), id=data['game_id'], pwd=data['game_pwd'])
def scenario(): eid = session['current_experiment'] nodes = Node.query.filter_by(eid=eid) #scenario = ScenarioForm() if request.method == "POST": en1 = request.form.get('en1', None) en2 = request.form.get('en2', None) scenario = Scenario(eid=eid, en1=en1, en2=en2) db.session.add(scenario) db.session.commit() return redirect(url_for("scenario")) elif request.method == "GET": return render_template("scenario.html", nodes=nodes)
def delete_scenario(self, args): """Delete (archive) the current active Scenario Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ return scenario_svc.delete_item(args, self.user, self.scenario, Scenario().find, {'guild': self.guild.name, 'channel_id': str(self.channel.id)})
def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for SessionCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- SessionCommand - object for processing session commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] self.guild = guild self.user = user self.command = self.args[0].lower() if len(self.args) > 0 else 'n' channel = 'private' if ctx.channel.type.name == 'private' else ctx.channel.name self.channel = Channel().get_or_create(channel, self.guild.name, self.user) self.scenario = Scenario().get_by_id( self.channel.active_scenario ) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id( self.channel.active_scene ) if self.channel and self.channel.active_scene else None self.session = Session().get_by_id( self.channel.active_session ) if self.channel and self.channel.active_session else None self.can_edit = self.user.role == 'Game Master' if self.user and self.session else True self.char = Character().get_by_id( self.user.active_character ) if self.user and self.user.active_character else None
def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for UndoCommand Parameters ---------- parent : DreamcraftHandler The handler for Dreamcraft Bot commands and subcommands ctx : object(Context) The Discord.Context object used to retrieve and send information to Discord users args : array(str) The arguments sent to the bot to parse and evaluate guild : Guild The guild object containing information about the server issuing commands user : User The user database object containing information about the user's current setttings, and dialogs channel : Channel The channel from which commands were issued Returns ------- UndoCommand - object for processing undo/redo commands and subcommands """ self.parent = parent self.new = parent.new self.delete = parent.delete self.ctx = ctx self.args = args[1:] self.guild = guild self.user = user self.channel = channel self.command = self.args[0].lower() if len(self.args) > 0 else 'undo' self.scenario = Scenario().get_by_id( self.channel.active_scenario ) if self.channel and self.channel.active_scenario else None self.sc = Scene().get_by_id( self.channel.active_scene ) if self.channel and self.channel.active_scene else None self.zone = Zone().get_by_id( self.channel.active_zone ) if self.channel and self.channel.active_zone else None self.char = Character().get_by_id( self.user.active_character ) if self.user and self.user.active_character else None
def test_random(self): scenario = Scenario({ "variables": [{ "type": "randomString", "length": 10, "name": "random" }], "steps": [{ "action": "set_value", "selector": "input#random", "value": "$[random]" }] }) # Take first element element = scenario.preprocessScenario()[0] self.assertNotEqual(element['value'], "") self.assertEqual(element["action"], "set_value") self.assertEqual(element["selector"], "input#random")
def test_single(self): scenario = Scenario({ "variables": [{ "type": "constant", "value": "constant_string", "name": "some_var" }], "steps": [{ "action": "set_value", "selector": "element", "value": "$[some_var]" }] }) self.assertEqual(scenario.preprocessScenario(), [{ 'action': 'set_value', 'value': 'constant_string', 'selector': 'element' }])
def bind_scenario(row, attendee, scenarios): for scenario_id, scenario in scenarios.items(): sce = Scenario() if scenario.get('show_rule'): if row[scenario.get('show_rule')['row_name']] != scenario.get( 'show_rule')['value_match']: continue sce.order = scenario['order'] sce.display_text = scenario['display_text'] sce.available_time = str2timestamp(scenario['available_time']) sce.expire_time = str2timestamp(scenario['expire_time']) sce.countdown = scenario['countdown'] if scenario.get('lock_message'): sce.disabled = scenario.get('lock_message') if scenario.get('attr'): for attr in scenario.get('attr'): if not attr.get('value'): sce.attr[attr['attr_name']] = row[attr['row_name']] else: sce.attr[attr['attr_name']] = attr.get('value')[row[ attr['row_name']]] if scenario.get('not_lock_rule'): if row[scenario.get('not_lock_rule')['row_name']] == scenario.get( 'not_lock_rule')['value_match']: sce.disabled = None else: sce.disabled = scenario.get( 'not_lock_rule')['not_match_disable_message'] attendee.scenario[scenario_id] = sce attendee.save()
def post(self): name = request.get_json()['name'] description = request.get_json()['description'] topo = request.get_json()['topo'] valid, errs = validate_topo(topo) if not valid: return jsonify(errors=errs), 400 isPublic = request.get_json()['isPublic'] sgRules = request.get_json()['sgRules'] new_scenario = Scenario(owner_id=g.user['id'], name=name, description=description, topo=topo, is_public=isPublic, sg_rules=sgRules) try: new_scenario.save() except UniqueViolatedError: abort( make_response(jsonify(message="Duplicated scenario name"), 409)) return jsonify(id=new_scenario.id)
def scenario_list(self, args): """Display a dialog for viewing and selecting Scenarios Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] def canceler(cancel_args): if cancel_args[0].lower() in ['scenario']: return ScenarioCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() messages.extend(Dialog({ 'svc': scenario_svc, 'user': self.user, 'title': 'Scenario List', 'command': 'scenario ' + (' '.join(args)), 'type': 'view', 'getter': { 'method': Scenario().get_by_channel, 'params': {'channel': self.channel, 'archived': False} }, 'formatter': lambda item, item_num, page_num, page_size: f'{item.get_short_string(self.channel)}', 'cancel': canceler }).open()) return messages
def new_scenario(self, args): """Create a new Scenario by name Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages = [] if len(args) == 0: if not self.scenario: return [ 'No active scenario or name provided\n\n', self.dialog('all') ] messages.append(scenario_svc.get_string(self.scenario, self.channel, self.user)) else: if len(args) == 1 and args[0].lower() == 'short': return [self.dialog('active_scenario_short')] scenario_name = ' '.join(args) if len(args) > 1 and args[1] == 'rename': scenario_name = ' '.join(args[2:]) if not self.scenario: return [ 'No active scenario or name provided\n\n', self.dialog('all') ] else: scenario = Scenario().find(self.user, scenario_name, self.guild.name) if scenario: return [f'Cannot rename to _{scenario_name}_. Scenario already exists'] else: self.scenario.name = scenario_name scenario_svc.save(self.scenario, self.user) messages.append(self.dialog('')) else: def canceler(cancel_args): if cancel_args[0].lower() in ['scenario']: return ScenarioCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() def selector(selection): self.scenario = selection self.channel.set_active_scenario(self.scenario, self.user) self.user.set_active_character(self.scenario.character) scenario_svc.save_user(self.user) return [self.dialog('')] messages.extend(Dialog({ 'svc': scenario_svc, 'user': self.user, 'title': 'Scenario List', 'command': 'new scenario ' + ' '.join(args), 'type': 'select', 'type_name': 'SCENARIO', 'getter': { 'method': Scenario.get_by_page, 'params': {'params': {'name__icontains': scenario_name, 'channel_id': str(self.channel.id), 'guild': self.guild.name, 'archived': False}} }, 'formatter': lambda item, item_num, page_num, page_size: f'_SCENARIO #{item_num+1}_\n{scenario_svc.get_string(item, self.channel)}', 'cancel': canceler, 'select': selector, 'confirm': { 'method': Scenario().get_or_create, 'params': {'user': self.user, 'name': scenario_name, 'channel': self.channel, 'guild': self.guild.name} } }).open()) return messages
def run(self): """ Represents the run method of a supervisor who receives messages from the director and sends scenario dependent other messages to the director. It uses a connector class to handle the actual connection to the director and a ScenarioRun objects to represent each scenario run by one subprocess. :rtype: None """ self.connector.start() while self.takes_new_scenarios: received_msg = self.receive_pipe.recv() if received_msg['type'] == "scenario_end": finished_scenario_run_id = received_msg['scenario_run_id'] finished_scenario_run = self.scenario_runs[ finished_scenario_run_id] finished_scenario_run.terminate() finished_scenario_run.join() del self.scenario_runs[finished_scenario_run_id] index_logger = [ i for i in range(len(self.logger_semaphores)) if self.logger_semaphores[i]["used_by"] == finished_scenario_run_id ][0] self.logger_semaphores[index_logger]["used_by"] = "" index_done = [ i for i in range(len(self.observations_done)) if self.observations_done[i]["used_by"] == finished_scenario_run_id ][0] self.observations_done[index_done]["used_by"] = "" self.send_queue.put(received_msg) elif received_msg['type'] == 'scenario_registration': print('Received Scenario Registration') # TODO: check if enough agents are left and scenario can be really started new_scenario_run_id = received_msg["scenario_run_id"] self.agents_in_use += len(received_msg["agents_at_supervisor"]) recv_end, send_end = aioprocessing.AioPipe(False) self.pipe_dict[new_scenario_run_id] = send_end # creating logger for new scenario run with already registered semaphore index_logger, logger_semaphore_dict = next( (index, semaphore) for (index, semaphore) in enumerate(self.logger_semaphores) if semaphore["used_by"] == "") logger_semaphore = logger_semaphore_dict["semaphore"] self.logger_semaphores[index_logger][ "used_by"] = new_scenario_run_id module = importlib.import_module( "loggers." + re.sub("([A-Z])", "_\g<1>", self.logger_str).lower()[1:]) logger_class = getattr(module, self.logger_str) logger = logger_class(new_scenario_run_id, logger_semaphore) # taking one observations_done list index_done, done_dict = next( (index, obs_done_dict) for (index, obs_done_dict) in enumerate(self.observations_done) if obs_done_dict["used_by"] == "") observations_done = done_dict["list"] self.observations_done[index_done][ "used_by"] = new_scenario_run_id # create and start scenario_run new_scenario_run = ScenarioRun( new_scenario_run_id, received_msg["agents_at_supervisor"], Scenario(**received_msg["scenario"]), self.ip_address, self.send_queue, recv_end, logger, observations_done, self.pipe_dict["supervisor"]) self.scenario_runs[new_scenario_run_id] = new_scenario_run new_scenario_run.start()
def main(args): """Main function. The main function parses the command line arguments, reads the input file and inits the generator. """ # Parse arguments parser = argparse.ArgumentParser(description='Start workload.') parser.add_argument('--debug', action='store_true', help="enable debug information") parser.add_argument('--verbose', action='store_true', help="makes generator more verbose") parser.add_argument('--threads', type=int, default=Options.DEFAULT_THREADS, help="number of threads to run simultaneously") parser.add_argument('--test', action='store_true', help="run a scenario only once") parser.add_argument('--slimerjs', action='store_true', help="use slimerjs instead of phantomjs") parser.add_argument('--screenshot', action='store_true', help="provide screenshots after each step") parser.add_argument('--user-agent', type=str, dest='userAgent', help="provide a custom User-Agent") parser.add_argument('--max-time', type=int, default=Options.DEFAULT_MAXTIME, dest='maxTime', help="provide a maximum runtime") parser.add_argument('scenario') args = parser.parse_args() # Check if scenario exists if not os.path.isfile(args.scenario): print "scenario '%s' not found" % args.scenario return # Load from file and parse with open(args.scenario, 'r') as content_file: content = content_file.read() scenario = commentjson.loads(content) # Load in scenario scenario = Scenario(scenario) # Parse options options = Options() # Which browser are we using if args.slimerjs: options.setBrowser('slimerjs') # Threads option options.setThreads(args.threads) # Test option options.setTest(args.test) # Output information options.setVerbose(args.verbose) # Debug mode options.setDebug(args.debug) # Screenshot mode options.setScreenshot(args.screenshot) # User agent options.setUserAgent(args.userAgent) # Create watchdog thread options.setMaximumExectionTime(args.maxTime) # Create new Felt class felt = Felt(options, scenario) # Start worker felt.run()
def new_scenario(): exploits = File.query.filter_by(file_type=FileTypeEnum.pov).all() vulns = File.query.filter_by(file_type=FileTypeEnum.vuln).all() if request.method == 'GET': is_pyro_running() return render_template('newScenario.html', exploits=exploits, vulns=vulns) else: form = NewScenarioForm(request.form) logger.info(request.form) if not is_pyro_running(): return render_template('newScenario.html', exploits=exploits, vulns=vulns, form=form) if not form.validate(): logger.info(form.errors) flash_form_errors(form) return render_template('newScenario.html', exploits=exploits, vulns=vulns, form=form) scenario = Scenario(name=form.name.data, description=form.description.data, cve_number=form.cve_number.data) files = get_files(form.exploits.data, form.vulns.data) scenario.file = files db.session.add(scenario) db.session.commit() rdpManager = RDPManager() rdpManager.add_user(scenario.id, scenario.id) guacUser = GuacUser(guac_username=scenario.id, guac_password=scenario.id, scenario_id=scenario.id) db.session.add(guacUser) db.session.commit() exploits = form.exploits.data for index, exploit in enumerate(exploits): f = File.query.filter_by(name=exploit).first() if f: rdp_ip = get_rdp_ip() os_rec = scenario_gen.generate_os_rec(f) rec_machine = Machine(name=scenario.name + '-Exploits' + str(index + 1), scenario_id=scenario.id, rdp_ip=rdp_ip) rec_machine.file.append(f) db.session.add(rec_machine) db.session.commit() machine_gen.generate(scenario, rec_machine, os_rec, vulns) db.session.commit() rdpManager = RDPManager(username=scenario.id, password=scenario.id) rdpManager.add_connection( name=rec_machine.id, username=rec_machine.machine_username, password=rec_machine.machine_password, hostname=rec_machine.rdp_ip, port=rec_machine.rdp_port) print(scenario.id) # machine_gen.generate(scenario, rec_machine, os_rec, vulns) # db.session.commit() connection_id = rdpManager.get_connection_id( str(rec_machine.id)) connection_link = rdpManager.get_connection_link(connection_id) # print(connection_link) rec_machine.connection_link = connection_link rec_machine.connection_id = connection_id db.session.commit() return redirect(url_for('configure', id=scenario.id))