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' } ])
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 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' }])
def show_or_add_scenario(): if request.method == 'POST': new_scenario = json.loads(request.get_data(as_text=True)) new_scenario_id = Scenario.insert(new_scenario) return json.dumps({'id': new_scenario_id}), 201 elif request.method == 'GET': return json.dumps({'scenarios': Scenario.get_all()}), 200
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 save_new_scenario(self, feature_save, sce): sequence = '' sce_save = Scenario().fill(feature_save, sce['scenario_name'], '') sce_save.save() steps = sce['steps'] for step in steps: step_save = self.save_new_step(sce_save, step) sequence += str(step_save.id) + '|' self.update_sequence(sce_save, sequence) return sce_save
def show_edit_delete_scenario(s_id): if request.method == 'PUT': edited_scenario = json.loads(request.get_data(as_text=True)) print('### ' + str(edited_scenario)) edited_scenario_id = Scenario.update(edited_scenario) return json.dumps({'id': edited_scenario_id}), 204 elif request.method == 'GET': return json.dumps({'scenario': Scenario.get_one(s_id)}), 200 elif request.method == 'DELETE': deleted_id = Scenario.delete(s_id) return json.dumps({'id': deleted_id}), 204
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)
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 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 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
def index(self): if request.args.get('privateOnly', 'false') == 'true': return _get_scenarios_private_only() else: public_scenarios = Scenario.fetchall(is_public=True) private_scenarios = Scenario.fetchall(is_public=False, owner_id=g.user['id']) ret = [] for s in public_scenarios + private_scenarios: r = { 'id': s.id, 'name': s.name, 'description': s.description, 'sgRules': s.sg_rules, 'topo': s.topo.value } ret.append(r) return jsonify(sorted(ret, key=lambda i: i['id'], reverse=True))
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 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 _get_scenarios_private_only(): ret = [] for scenario in Scenario.fetchall(owner_id=g.user['id']): ret.append({ 'id': scenario.id, 'name': scenario.name, 'description': scenario.description, 'sgRules': scenario.sg_rules, 'topo': scenario.topo.value }) return jsonify(sorted(ret, key=lambda i: i['id'], reverse=True))
def get(self, id): scenario = Scenario.fetchone(id=id) if scenario is not None: return jsonify(id=scenario.id, name=scenario.name, description=scenario.description, sgRules=scenario.sg_rules, topo=scenario.topo.value, isPublic=scenario.is_public.value) else: return jsonify(message="scenario not found"), 404
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 __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for ScenarioCommand 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 ------- ScenarioCommand - object for processing scenario 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.can_edit = self.user.role == 'Game Master' if self.user and self.scenario else True self.sc = Scene().get_by_id(self.channel.active_scene) if self.channel and self.channel.active_scene 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 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 case(): if request.method == 'POST': data = {} for item in request.json: value = request.json[item] if item != 'data': print item,value data.update({item:value}) #print data s = build_demo7.build_demo7_data(data) if current_user.is_active(): new_scenario = Scenario(s, data['name'], data['income_items'], data['basic_expenses'], data['misc_expenses'], data['debt_accounts'], data['cash_accounts']) if data['isBaseCase']: new_scenario.is_base = True current_user.scenarios.append(new_scenario) db.session.add(current_user) db.session.flush() this_id = new_scenario.id db.session.commit() data.update({'id':this_id,'data':s}) return json.dumps(data),200
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 deploy(self, id): cloudconfig_id = request.get_json()['cloudConfigId'] cloudconfig = CloudConfig.fetchone(id=cloudconfig_id) users = request.get_json()['users'] lab = Lab.fetchone(id=id) lab.update(status='deploying') """Chances are you are redeploying a lab, whose slices are already created""" slices = Slice.fetchall(lab_id=lab.id) """Otherwise, create slices for the lab""" if len(slices) == 0: for index, user in enumerate(users): new_slice = Slice.insert(lab_id=lab.id, status='deploying', user_id=user['id'], name=lab.name + ' / slice_' + str(index), cloud_attrs={}) slices.append(new_slice) scenario = Scenario.fetchone(id=lab.scenario_id) if cloudconfig.provider == 'Openstack': return _deploy_openstack(id, cloudconfig, slices, scenario)
def patch(self, id): scenario = Scenario.fetchone(id=id) if scenario.owner_id != g.user['id']: return jsonify( message="You are not the owner of this scenario"), 405 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'] scenario.name = name scenario.description = description scenario.topo = topo scenario.is_public = isPublic scenario.sg_rules = sgRules scenario.save() return jsonify(id=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 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()
class ScenarioCommand(): """ Handle 'scenario' commands and subcommands Subcommands: help - display a set of instructions on ScenarioCommand usage note - add a note to the scenario say - add dialog to the scene from the scenario story - display the scenario's story new - create new scenarios by name name, n - display scenarios by name description, desc - add/edit the Description in the engeagement select, = - display existing engeagement character, char, c - edit the scenario as a character list, l - display a list of existing scenarios players, player, p - add players to the scenario delete - remove an scenario (archive) """ def __init__(self, parent, ctx, args, guild, user, channel): """ Command handler for ScenarioCommand 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 ------- ScenarioCommand - object for processing scenario 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.can_edit = self.user.role == 'Game Master' if self.user and self.scenario else True self.sc = Scene().get_by_id(self.channel.active_scene) if self.channel and self.channel.active_scene else None self.char = Character().get_by_id(self.user.active_character) if self.user and self.user.active_character else None def run(self): """ Execute the channel commands by validating and finding their respective methods Returns ------- list(str) - a list of messages in response the command validation and execution """ try: # List of subcommands mapped the command methods switcher = { 'help': self.help, 'name': self.select, 'n': self.select, 'select': self.select, '=': self.select, 'note': self.note, 'say': self.say, 'story': self.story, 'description': self.description, 'desc': self.description, 'character': self.character, 'char': self.character, 'c': self.character, 'approaches': self.character, 'approach': self.character, 'apps': self.character, 'app': self.character, 'skills': self.character, 'skill': self.character, 'sks': self.character, 'sk': self.character, 'aspects': self.character, 'aspect': self.character, 'a': self.character, 'stunts': self.character, 'stunt': self.character, 's': self.character, 'custom': self.character, 'stress': self.character, 'st': self.character, 'consequences': self.character, 'consequence':self.character, 'con': self.character, 'players': self.player, 'player': self.player, 'p': self.player, 'list': self.scenario_list, 'l': self.scenario_list, 'delete': self.delete_scenario, 'd': self.delete_scenario } if self.new and not self.user.command or self.user.command and 'new' in self.user.command: func = self.new_scenario elif self.delete: func = self.delete_scenario # Get the function from switcher dictionary elif self.command in switcher: func = switcher.get(self.command, lambda: self.select) else: match = self.search(self.args) if match: self.args = ('select',) + self.args self.command = 'select' func = self.select else: self.args = ('n',) + self.args self.command = 'n' func = self.select if func: # Execute the function messages = func(self.args) # Send messages return messages except Exception as err: traceback.print_exc() # Log every error scenario_svc.log( str(self.scenario.id) if self.scenario else str(self.user.id), self.scenario.name if self.scenario else self.user.name, str(self.user.id), self.guild.name, 'Error', { 'command': self.command, 'args': self.args, 'traceback': traceback.format_exc() }, 'created') return list(err.args) def help(self, args): """Returns the help text for the command""" return [SCENARIO_HELP] def search(self, args): """Search for an existing Scenario using the command string Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ params = {'name__icontains': ' '.join(args[0:]), 'guild': self.guild.name, 'channel_id': str(self.channel.id), 'archived': False} return scenario_svc.search(args, Scenario.filter, params) def get_parent(self, args): messages = [] if (self.user and self.scenario and self.scenario.parent_id): messages.extend(scenario_svc.get_parent_by_id(Scenario.filter, self.user, self.scenario.parent_id)) else: messages.append('No parent found') return messages def note(self, args): """Add a note to the Scenario story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if self.scenario: Log().create_new(str(self.scenario.id), f'Scenario: {self.scenario.name}', str(self.user.id), self.guild.name, 'Scenario', {'by': self.user.name, 'note': ' '.join(args[1:])}, 'created') return ['Log created'] else: return ['No active scenario to log'] def say(self, args): """Add dialog to the Scenario story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if not self.scenario: return ['No active scenario to log'] else: note_text = ' '.join(args[1:]) Log().create_new(str(self.scenario.id), f'Scenario: {self.scenario.name}', str(self.user.id), self.guild.name, 'Scenario', {'by': self.user.name, 'note': f'***Narrator*** says, "{note_text}"'}, 'created') return ['Log created'] def story(self, args): """Disaply the Scenario story Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ messages =[] command = 'scenario ' + (' '.join(args)) def canceler(cancel_args): if cancel_args[0].lower() in ['scenario']: self.args = cancel_args self.command = self.args[0] return self.run() else: self.parent.args = cancel_args self.parent.command = self.parent.args[0] return self.parent.get_messages() response = Dialog({ 'svc': scenario_svc, 'user': self.user, 'title': 'Story', 'type': 'view', 'type_name': 'Scenario Log', 'command': command, 'getter': { 'method': Log.get_by_page, 'params': { 'params': {'parent_id': str(self.scenario.id)}, 'sort': 'created' }, 'parent_method': Scenario.get_by_page, 'parent_params': { 'params': {'category__in': ['Character','Aspect','Stunt']}, 'sort': 'created' } }, 'formatter': lambda log, num, page_num, page_size: log.get_string(self.user), # if log.category == 'Log' else log.get_string() 'cancel': canceler, 'page_size': 10 }).open() messages.extend(response) return messages def dialog(self, dialog_text, char=None): """Display Scenario information and help text Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ char, name, get_string, get_short_string = scenario_svc.get_info('scenario', self.scenario, self.channel) category = 'Scenario' dialog = { 'create_scenario': ''.join([ '**CREATE or SCENARIO**```css\n', '.d new scenario "YOUR SCENARIOR\'S NAME"```' ]), 'active_scenario': ''.join([ '***YOU ARE CURRENTLY EDITING...***\n' if self.can_edit else '', f':point_down:\n\n{get_string}' ]), 'active_scenario_short': ''.join([ f'***YOU ARE CURRENTLY EDITING...:***\n', f':point_down:\n\n{get_short_string}' ]), 'rename_delete': ''.join([ f'\n\n_Is ***{name}*** not the {category.lower()} name you wanted?_', f'```css\n.d scenario rename "NEW NAME"```_Want to remove ***{name}***?_', '```css\n.d scenario delete```' ]), 'go_back_to_parent': ''.join([ f'\n\n***You can GO BACK to the parent scenario, aspect, or stunt***', '```css\n.d scenario parent```' ]) } dialog_string = '' if dialog_text == 'all': if not char: dialog_string += dialog.get('create_scenario', '') dialog_string += dialog.get('rename_delete', '') elif category == 'Scenario': if dialog_text: dialog_string += dialog.get(dialog_text, '') else: dialog_string += dialog.get('active_scenario', '') dialog_string += dialog.get('rename_delete', '') if self.can_edit else '' else: if dialog_text: dialog_string += dialog.get(dialog_text, '') else: dialog_string += dialog.get('active_scenario', '') if self.can_edit else '' dialog_string += dialog.get('rename_delete', '') if self.can_edit else '' dialog_string += dialog.get('go_back_to_parent', '') if self.can_edit else '' return dialog_string 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 select(self, args): """Select an existing 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(self.scenario.get_string()) else: if len(args) == 1 and args[0].lower() == 'short': return [self.dialog('active_scenario_short')] if len(args) == 1 and self.scenario: return [self.dialog('')] scenario_name = ' '.join(args[1:]) 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': '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 }).open()) return messages 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 description(self, args): """Add/edit the description for a Scenario Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if len(args) == 1: return ['No description provided'] if not self.scenario: return ['You don\'t have an active scenario.\nTry this: ".d s name {name}"'] else: description = ' '.join(args[1:]) self.scenario.description = description self.scenario.updated_by = str(self.user.id) self.scenario.updated = T.now() self.scenario.save() return [ f'Description updated to "{description}"', self.scenario.get_string(self.channel) ] def character(self, args): """Edit the Scenario as a character Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ if self.user: self.user.active_character = str(self.scenario.character.id) self.user.updated_by = str(self.user.id) self.user.updated = T.now() self.user.save() command = CharacterCommand(parent=self.parent, ctx=self.ctx, args=args, guild=self.guild, user=self.user, channel=self.channel, char=self.scenario.character) return command.run() def player(self, args): """Add/remove a player from the Scenario Parameters ---------- args : list(str) List of strings with subcommands Returns ------- list(str) - the response messages string array """ return scenario_svc.player(args, self.channel, self.scenario, self.user) 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 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 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 delete(self, id): scenario = Scenario.fetchone(id=id) scenario.delete() return jsonify(message="ok")
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 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))
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 submit_demo3(): names = {0:''} income = {0:{}} basic_expenses = {0:{}} debt_expenses = {0:{}} misc_expenses = {0:{}} debt_balances = {0:{}} cash_balances = {0:{}} rates = {0:{}} print request.form scenarios = [] for item in request.form: print item, request.form[item] if request.form[item] == '' or request.form[item] == None: item_value = 0 else: item_value = request.form[item].replace(",", "") prefix = item[:3] item_name = item[3:-2] scenario = int(item[-1]) if scenario not in scenarios: names.update({scenario:''}) income.update({scenario:{}}) basic_expenses.update({scenario:{}}) debt_expenses.update({scenario:{}}) misc_expenses.update({scenario:{}}) debt_balances.update({scenario:{}}) cash_balances.update({scenario:{}}) rates.update({scenario:{}}) scenarios.append(scenario) if prefix == "na_": names[scenario] = item_value elif prefix == "in_": income[scenario].update({item_name: item_value}) elif prefix == "be_": basic_expenses[scenario].update({item_name: item_value}) elif prefix == "de_": debt_expenses[scenario].update({item_name: item_value}) elif prefix == "me_": misc_expenses[scenario].update({item_name: item_value}) elif prefix == "ba_": debt_balances[scenario].update({item_name: item_value}) elif prefix == "cb_": cash_balances[scenario].update({item_name: item_value}) elif prefix == "ra_": rates[scenario].update({item_name: float(item_value)/100.0}) #print rates #scenario_count = len(scenarios) print 'cash_balances: \n',cash_balances print 'rates: \n',rates d = build_demo3.build_demo3_data(names, income, basic_expenses, debt_expenses, misc_expenses, debt_balances, cash_balances, rates, scenarios) if current_user.is_active(): #remove existing scenarios scenarios_query = current_user.scenarios.all() for scenario in scenarios_query: db.session.delete(scenario) for scenario in range(0,len(scenarios)): #for scenario in range(0,1): new_scenario = Scenario(d[scenario]) if scenario == 0: new_scenario.is_base = True current_user.scenarios.append(new_scenario) #current_user.data = d[0] db.session.add(current_user) db.session.commit() return redirect(url_for('demo3_output_detail'))