def test_definitions(self): e1 = Equation(full_name="Jon's Law") e1.save(no_wiki=True) v1 = Variable(full_name="Jon's Constant") v1.save(no_wiki=True) e1.add_defined_var(v1.full_name) self.assertEqual(e1.defined_var.full_name, v1.full_name)
def test_infobase_add_SearchTerm(self): """ test linking a search term to an infobase or creating it if it doesn't exist. """ v1 = Variable(full_name="acceleration") v1.save(no_wiki=True) # creating a search term for the first time v1.add_SearchTerm("acc") try: s1 = SearchTerm.objects.get(term="acc") except (ObjectDoesNotExist, MultipleObjectsReturned), e: raise AssertionError
def generate_edit_call_form(product, call, call_id): count = 1 if len(call.variables) > 1: count = len(call.variables) form = add_fields_to_form(count) if len(call.variables) > 0: for i in range(count): temp = getattr(form, 'variable_%i' % i) temp_variable = Variable(call.variables[i]) temp.form.field_type.data = temp_variable.field_type temp.form.required.data = temp_variable.required temp.form.description.data = temp_variable.description temp.form.variable_name.data = temp_variable.variable_name temp.form.field_display.data = temp_variable.field_display temp.form.field_display_data.data = ( temp_variable.field_display_data) temp.form.id_value.data = temp_variable.id_value for key, value in call.__dict__.iteritems(): if key != 'variables': setattr(getattr(form, key), 'data', value) form.id.data = call_id return form, count
def on_now_command(self, event): """Displays numbers about the current players and servers.""" answer = [ 'There\'s currently **{total_players}** player{total_players_plural} in total. **{online_players}** of them {online_players_plural} playing multiplayer online.', 'There\'s also **{total_servers}** online multiplayer servers, **{active_servers}** of which {active_servers_plural} active :wink:', '', 'Talking about these numbers, here\'s some peaks:', '', ' - Total players peak: **{total_players_peak_count}** ({total_players_peak_date})', ' - Online players peak: **{online_players_peak_count}** ({online_players_peak_date})', ' - Online servers peak: **{online_servers_peak_count}** ({online_servers_peak_date})', ' - Active servers peak: **{active_servers_peak_count}** ({active_servers_peak_date})' ] total_players = self.steam_api_client.get_current_players_count_for_app( app.config['RWR_STEAM_APP_ID']) online_players, active_servers, total_servers = self.rwr_scraper.get_counters( ) peaks = Variable.get_peaks_for_display() event.msg.reply('\n'.join(answer).format( total_players=total_players, total_players_plural='s' if total_players > 1 else '', online_players=online_players, online_players_plural='are' if online_players > 1 else 'is', total_servers=total_servers, total_servers_plural='s' if total_servers > 1 else '', active_servers=active_servers, active_servers_plural='are' if active_servers > 1 else 'is', **peaks))
def test_infobase_add_from_sequence(self): v1 = Variable(full_name="acceleration") v1.save(no_wiki=True) u1 = Unit(full_name="ms") u1.save(no_wiki=True) u2 = Unit(full_name="meter") u2.save(no_wiki=True) u3 = Unit(full_name="second") u3.save(no_wiki=True) u1.make_composition_links("meter,second") v1.add_units_links("meter,second") try: uget1 = u1.composition_links.get(full_name="meter") uget2 = u1.composition_links.get(full_name="second") uget3 = v1.units_links.get(full_name="meter") uget4 = v1.units_links.get(full_name="second") except (ObjectDoesNotExist, MultipleObjectsReturned), e: raise AssertionError
def test_equation_add_variables(self): e1 = Equation(full_name="Jon's Law") e1.save(no_wiki=True) v1 = Variable(full_name="Jon's Constant") v1.save(no_wiki=True) v2 = Variable(full_name="Jon's Operator") v2.save(no_wiki=True) v3 = Variable(full_name="Jon's Plus Sign") v3.save(no_wiki=True) e1.add_defined_var("Jon's Constant") e1.add_variables("Jon's Constant,Jon's Operator,Jon's Plus Sign") self.assertEqual(e1.defined_var.full_name, v1.full_name) self.assertTrue(v2 in e1.variables.all()) self.assertTrue(v3 in e1.variables.all()) self.assertFalse(v1 in e1.variables.all())
def __on_var_created(self, expression, frame, data): # Created variable info try: type = Type.parse(data.type) numchild = int(data.numchild) name = data.name value = [] if numchild else data.value # Update the model and notify self.vars.add(name, Variable(name, expression, type, children=numchild, data=value, frame=frame)) self.post_event(GDBEvent(EVT_GDB_UPDATE_VARS, self, data=[name])) except Exception, e: print "Exception creating variable: %s" % e print data
def online_multiplayer_status(): is_everything_ok, servers_statuses = RwrRootServer.get_data_for_display() last_root_rwr_servers_check = Variable.get_value( 'last_root_rwr_servers_check') next_root_rwr_servers_check = last_root_rwr_servers_check.shift( minutes=app.config['ROOT_RWR_SERVERS_CHECK_INTERVAL'] ) if last_root_rwr_servers_check else None return render_template( 'online_multiplayer_status.html', is_everything_ok=is_everything_ok, servers_statuses=servers_statuses, next_root_rwr_servers_check=next_root_rwr_servers_check)
def home(): total_players_data = SteamPlayerCount.players_data() online_players_data = ServerPlayerCount.server_players_data() servers_online_data = ServerPlayerCount.servers_data() servers_active_data = ServerPlayerCount.servers_data(active_only=True) players_data = [total_players_data, online_players_data] servers_data = [servers_online_data, servers_active_data] peaks = Variable.get_peaks_for_display() return render_template('home.html', players_data=players_data, servers_data=servers_data, peaks=peaks)
def set(self, name, value, group=None, host=None): if group: item = self.session.query(Group).filter(Group.name == group).one() elif host: item = self.session.query(Host).filter(Host.name == host).one() # find or create the variable found = False for var in item.variables: if var.name == name: var.value = value self.session.add(var) found = True break if not found: var = Variable(name=name, value=value) item.variables.append(var) self.session.add(item) self.session.commit()
def __on_var_list_children(self, data): kids = [] updated_kids =[] for item in data.children: child = item['child'] numchild = int(child['numchild']) value = [] if numchild else child['value'] type = Type.parse(child['type']) expression = child['exp'] name = child['name'] parent = GDBVarModel.parent_name(name) if name not in self.vars: self.vars.add(name, Variable(name, expression, type, children=numchild, data=value)) updated_kids.append(name) kids.append(name) if parent: self.vars[parent].data = kids if updated_kids: self.post_event(GDBEvent(EVT_GDB_UPDATE_VARS, self, data=kids))
def get_vars_for_call(submissions): data, count = [], [] for key, value in submissions: temp = re.search('variable_(\d+?)-(\w.*)', key) if temp: if count: if not int(temp.group(1)) in count: count.append(int(temp.group(1))) else: count.append(int(temp.group(1))) for placeholder in range(len(count)): data.append({'ignore': 'placeholder'}) for key, value in submissions: temp = re.search('variable_(\d+?)-(\w.*)', key) if temp: if temp.group(2) != 'csrf_token': if str(temp.group(2)) == 'required': if value[0]: data[int(temp.group(1))][str(temp.group(2))] = bool( value[0] ) elif str(temp.group(2)) == 'id_value': if value[0]: data[int(temp.group(1))][str(temp.group(2))] = int( value[0] ) else: data[int(temp.group(1))][str(temp.group(2))] = value[0] return_data = [] for variable in data: if variable.get('variable_name'): temp_var = Variable(variable) return_data.append(temp_var.__dict__) return return_data
def test_infobase_save(self): """ the save function is automated to add displaystyle to the latex, add a description and link from wikipedia, and full_name and quick_name as search terms. """ v1 = Variable(full_name="Newton's Second Law", quick_name="F=ma", representation="F=ma") v1.save() self.assertEqual(v1.representation, "$\\displaystyle{F=ma}$") self.assertEqual(v1.description_url, u"http://en.wikipedia.org/wiki/Newton%27s_laws_of_motion") # NOTE: The above represents a case where the description returned by # wikipedia is NOT what we want, so we need to revise it. try: s1 = SearchTerm.objects.get(term=v1.full_name) s2 = SearchTerm.objects.get(term=v1.quick_name) except ObjectDoesNotExist: raise AssertionError self.assertTrue(s1 in v1.search_terms.all()) self.assertTrue(s2 in v1.search_terms.all()) # test save method on existing object v1.description = "something else" v1.save() self.assertEqual(v1.description, "something else")
u1 = Unit(full_name="ms") u1.save(no_wiki=True) u2 = Unit(full_name="meter") u2.save(no_wiki=True) u3 = Unit(full_name="second") u3.save(no_wiki=True) u1.make_composition_links("meter,second") v1.add_units_links("meter,second") try: uget1 = u1.composition_links.get(full_name="meter") uget2 = u1.composition_links.get(full_name="second") uget3 = v1.units_links.get(full_name="meter") uget4 = v1.units_links.get(full_name="second") except (ObjectDoesNotExist, MultipleObjectsReturned), e: raise AssertionError v2 = Variable(full_name="Jon's Constant") v2.save(no_wiki=True) u4 = Unit(full_name="kilogram") u4.save(no_wiki=True) u4.make_composition_links("base") self.assertFalse(bool(u4.composition_links.all())) def test_definitions(self): e1 = Equation(full_name="Jon's Law") e1.save(no_wiki=True) v1 = Variable(full_name="Jon's Constant") v1.save(no_wiki=True) e1.add_defined_var(v1.full_name) self.assertEqual(e1.defined_var.full_name, v1.full_name) def test_equation_add_variables(self):
def get_players_count(): """Store the number of players.""" from models import ServerPlayerCount, SteamPlayerCount, Variable from rwrs import cache, db import rwr.scraper import steam_api import arrow scraper = rwr.scraper.DataScraper() click.echo('Clearing cache') cache.delete_memoized(rwr.scraper.DataScraper.get_servers) cache.delete_memoized(ServerPlayerCount.server_players_data) cache.delete_memoized(ServerPlayerCount.servers_data) cache.delete_memoized(steam_api.Client.get_current_players_count_for_app) cache.delete_memoized(SteamPlayerCount.players_data) click.echo('Getting current players on Steam') steam_api_client = steam_api.Client(app.config['STEAM_API_KEY']) steam_player_count = SteamPlayerCount() steam_player_count.count = steam_api_client.get_current_players_count_for_app(app.config['RWR_STEAM_APP_ID']) current_total_players_count = steam_player_count.count db.session.add(steam_player_count) click.echo('Getting current players on servers') servers = scraper.get_servers() current_online_players_count = 0 current_online_servers_count = 0 current_active_servers_count = 0 for server in servers: click.echo(' {} ({}, {})'.format(server.name, server.players.current, server.ip_and_port)) server_player_count = ServerPlayerCount() server_player_count.ip = server.ip server_player_count.port = server.port server_player_count.count = server.players.current current_online_players_count += server.players.current current_online_servers_count += 1 if server.players.current > 0: current_active_servers_count += 1 db.session.add(server_player_count) click.echo('Getting peaks') peak_refs = { 'total_players_peak': current_total_players_count, 'online_players_peak': current_online_players_count, 'online_servers_peak': current_online_servers_count, 'active_servers_peak': current_active_servers_count } peak_values = Variable.get_many_values([name + '_count' for name in peak_refs.keys()]) vars_to_update = {} for name in peak_refs.keys(): click.echo(' ' + name) name_count = name + '_count' name_date = name + '_date' peak_value = peak_values[name_count] if name_count in peak_values else 0 if peak_refs[name] >= peak_value: vars_to_update[name_count] = peak_refs[name] vars_to_update[name_date] = arrow.utcnow().floor('minute') Variable.set_many_values(vars_to_update) click.echo('Persisting to database') db.session.commit() click.secho('Done', fg='green')
def get_root_rwr_servers_status(): """Check the status of the RWR root servers.""" from models import RwrRootServer, RwrRootServerStatus, Variable from disco.api.client import APIClient as DiscordAPIClient from flask import url_for from rwrs import db import rwr.constants import helpers import arrow click.echo('Pinging servers') hosts_to_ping = [server['host'] for group in rwr.constants.ROOT_RWR_SERVERS for server in group['servers']] rwr_root_servers = RwrRootServer.query.filter(RwrRootServer.host.in_(hosts_to_ping)).all() rwr_root_servers_by_host = {rwr_root_server.host: rwr_root_server for rwr_root_server in rwr_root_servers} servers_down_count_then = sum([1 for rwr_root_server in rwr_root_servers if rwr_root_server.status == RwrRootServerStatus.DOWN]) servers_down_count_now = 0 for host in hosts_to_ping: click.echo(host, nl=False) is_server_up = helpers.ping(host) if is_server_up: click.secho(' Up', fg='green') else: click.secho(' Down', fg='red') servers_down_count_now += 1 if host not in rwr_root_servers_by_host: rwr_root_server = RwrRootServer() rwr_root_server.host = host else: rwr_root_server = rwr_root_servers_by_host[host] rwr_root_server.status = RwrRootServerStatus.UP if is_server_up else RwrRootServerStatus.DOWN db.session.add(rwr_root_server) Variable.set_value('last_root_rwr_servers_check', arrow.utcnow().floor('minute')) click.echo('Persisting to database') db.session.commit() message = None if servers_down_count_then == 0 and servers_down_count_now > 0: with app.app_context(): message = ':warning: Online multiplayer is having issues right now. Are the devs aware? If not, poke **pasik** or **JackMayol**. Some details here: {}'.format(url_for('online_multiplayer_status', _external=True)) elif servers_down_count_then > 0 and servers_down_count_now == 0: message = ':white_check_mark: Outage update: online multiplayer is back up and running!' if message: click.echo('Sending Discord bot message') discord_api_client = DiscordAPIClient(app.config['DISCORD_BOT_TOKEN']) discord_api_client.channels_messages_create(app.config['DISCORD_BOT_CHANNEL_ID'], message) click.secho('Done', fg='green')
def variable_set(key, value): ''' this looks pretty worthless. ''' return Variable.set(key, value)
def variable_get(key, default): ''' this looks pretty worthless. ''' return Variable.get(key, default)
def test_infobase_strings(self): """ check representation with $ removed and confirm latex is valid """ v1 = Variable(representation=r'$a$') v1.save(no_wiki=True) self.assertEqual(v1.rep_without_dollars(), r'\displaystyle{a}')
def parse_argument(arg: Element) -> InstructionArgument: """ Zpracovani parametru instrukce. Parameters ---------- arg: Element XML element parametru. Returns ------- InstructionArgument Zpracovany parametr. """ if len(list(arg)) > 0: exit_app(exitCodes.INVALID_XML_STRUCT, 'Argument contains unexpected elements.', True) arg_type = arg.attrib.get('type') arg_value = arg.text if arg.text is not None else '' if arg_type == ArgumentTypes.LABEL.value: InstructionsParser.validate_variable_name(arg_value, True) return Label(arg_value) elif arg_type == ArgumentTypes.VARIABLE.value: variable_parts = arg_value.split('@', 1) if len(variable_parts) == 2: InstructionsParser.validate_scope(variable_parts[0]) InstructionsParser.validate_variable_name(variable_parts[1]) if variable_parts[0] == 'GF': return Variable(Frames.GLOBAL, variable_parts[1]) elif variable_parts[0] == 'TF': return Variable(Frames.TEMPORARY, variable_parts[1]) elif variable_parts[0] == 'LF': return Variable(Frames.LOCAL, variable_parts[1]) else: exit_app(exitCodes.INVALID_XML_STRUCT, 'Invalid variable. ({})'.format(arg_value), True) elif arg_type == 'nil': if arg_value != 'nil': exit_app(exitCodes.INVALID_XML_STRUCT, 'Invalid value of nil. ({})'.format(arg_value), True) return Symbol(DataTypes.NIL, None) elif arg_type == 'int': try: return Symbol(DataTypes.INT, int(arg_value)) except ValueError: exit_app(exitCodes.INVALID_XML_STRUCT, 'Invalid int value. ({})'.format(arg_value), True) elif arg_type == 'bool': if arg_value == 'true': return Symbol(DataTypes.BOOL, True) elif arg_value == 'false': return Symbol(DataTypes.BOOL, False) else: exit_app(exitCodes.INVALID_XML_STRUCT, 'Invalid boolean value. ({})'.format(arg_value), True) elif arg_type == 'string': if re.compile('.*#.*').match(arg_value): exit_app(exitCodes.INVALID_XML_STRUCT, 'Text cannot contains #.', True) fixed_string = InstructionsParser.fix_string(arg_value) return Symbol(DataTypes.STRING, fixed_string) elif arg_type == 'type': if arg_value == 'int': return Type(int) elif arg_value == 'string': return Type(str) elif arg_value == 'bool': return Type(bool) elif arg_value == 'float': return Type(float) else: exit_app(exitCodes.INVALID_XML_STRUCT, 'Unknown type value. ({})'.format(arg_value), True) elif arg_type == 'float': try: return Symbol(DataTypes.FLOAT, float.fromhex(arg_value)) except Exception: exit_app(exitCodes.INVALID_XML_STRUCT, 'Invalid format of operand.') else: exit_app(exitCodes.INVALID_XML_STRUCT, 'Unknown argument type. ({})'.format(arg_type), True)