def load_gameobject_loot_templates(): gameobject_loot_templates = WorldDatabaseManager.gameobject_get_loot_template( ) length = len(gameobject_loot_templates) count = 0 for loot_template in gameobject_loot_templates: WorldDatabaseManager.GameObjectLootTemplateHolder.load_gameobject_loot_template( loot_template) count += 1 Logger.progress('Loading gameobject loot templates...', count, length) return length
def load_creature_loot_templates(): creature_loot_templates = WorldDatabaseManager.creature_get_loot_template( ) length = len(creature_loot_templates) count = 0 for loot_template in creature_loot_templates: WorldDatabaseManager.CreatureLootTemplateHolder.load_creature_loot_template( loot_template) count += 1 Logger.progress('Loading creature loot templates...', count, length) return length
def load_creature_quests(): creature_quests = WorldDatabaseManager.creature_quest_get_all() length = len(creature_quests) count = 0 for creature_quest in creature_quests: WorldDatabaseManager.QuestRelationHolder.load_creature_quest( creature_quest) count += 1 Logger.progress('Loading creature quest relations...', count, length) return length
def load_quests(self): quest_db_statuses = RealmDatabaseManager.character_get_quests( self.player_mgr.guid) for quest_db_status in quest_db_statuses: if quest_db_status.rewarded > 0: self.completed_quests.add(quest_db_status.quest) elif quest_db_status.state == QuestState.QUEST_ACCEPTED or quest_db_status.state == QuestState.QUEST_REWARD: self.active_quests[quest_db_status.quest] = ActiveQuest( quest_db_status) else: Logger.error( f"Quest database (guid={quest_db_status.guid}, quest_id={quest_db_status.quest}) has state {quest_db_status.state}. No handling." )
def resolve_table_coordinates(casting_spell, target_effect): target_position = WorldDatabaseManager.spell_target_position_get_by_spell( casting_spell.spell_entry.ID) if not target_position: Logger.warning( f'Unimplemented target spell position for spell {casting_spell.spell_entry.ID}.' ) return [] return target_position.target_map, Vector( target_position.target_position_x, target_position.target_position_y, target_position.target_position_z, target_position.target_orientation)
def load_creature_model_info(): creature_model_infos = WorldDatabaseManager.creature_model_info_get_all( ) length = len(creature_model_infos) count = 0 for creature_model_info in creature_model_infos: WorldDatabaseManager.CreatureModelInfoHolder.load_creature_model_info( creature_model_info) count += 1 Logger.progress('Loading creature model info...', count, length) return length
def load_creature_display_info(): creature_display_infos = DbcDatabaseManager.creature_display_info_get_all( ) length = len(creature_display_infos) count = 0 for creature_display_info in creature_display_infos: DbcDatabaseManager.CreatureDisplayInfoHolder.load_creature_display_info( creature_display_info) count += 1 Logger.progress('Loading creature display info...', count, length) return length
def load_creature_equip_templates(): creature_equip_templates = WorldDatabaseManager.creature_equip_template_get_all( ) length = len(creature_equip_templates) count = 0 for creature_equip_template in creature_equip_templates: WorldDatabaseManager.CreatureEquipmentHolder.load_creature_equip_template( creature_equip_template) count += 1 Logger.progress('Loading creature equipment templates...', count, length) return length
def load_items(self): character_inventory = RealmDatabaseManager.character_get_inventory( self.owner.guid) # First load bags for item_instance in character_inventory: item_template = WorldDatabaseManager.item_template_get_by_entry( item_instance.item_template) if item_template and item_template.inventory_type == InventoryTypes.BAG: container_mgr = ContainerManager(owner=self.owner.guid, item_template=item_template, item_instance=item_instance) if self.is_bag_pos(container_mgr.current_slot): self.containers[item_instance.bag].sorted_slots[ container_mgr.current_slot] = container_mgr self.containers[container_mgr.current_slot] = container_mgr # Then load items for item_instance in character_inventory: item_template = WorldDatabaseManager.item_template_get_by_entry( item_instance.item_template) if item_template: if item_template.display_id > MAX_3368_ITEM_DISPLAY_ID and \ self.is_equipment_pos(item_instance.bag, item_instance.slot): Logger.error( 'Character %s has an equipped item (%u - %s) with out of bounds display_id (%u), ' 'deleting in order to prevent crashes.' % (self.owner.player.name, item_template.entry, item_template.name, item_template.display_id)) RealmDatabaseManager.character_inventory_delete( item_instance) continue if item_template.inventory_type == InventoryTypes.BAG: if self.is_bag_pos(item_instance.slot): continue item_mgr = ContainerManager(owner=self.owner.guid, item_template=item_template, item_instance=item_instance) else: item_mgr = ItemManager(item_template=item_template, item_instance=item_instance) if item_instance.bag in self.containers and self.containers[ item_instance.bag]: self.containers[item_instance.bag].sorted_slots[ item_mgr.current_slot] = item_mgr self.set_base_attack_time()
def load_creature_quest_finishers(): creature_quest_finishers = WorldDatabaseManager.creature_quest_finisher_get_all( ) length = len(creature_quest_finishers) count = 0 for creature_quest_finisher in creature_quest_finishers: WorldDatabaseManager.QuestRelationHolder.load_creature_finisher_quest( creature_quest_finisher) count += 1 Logger.progress('Loading creature quest finishers...', count, length) return length
def load_area_trigger_quest_relations(): area_trigger_quest_relations = WorldDatabaseManager.area_trigger_quest_relations_get_all( ) length = len(area_trigger_quest_relations) count = 0 for area_trigger_relation in area_trigger_quest_relations: WorldDatabaseManager.QuestRelationHolder.load_area_trigger_quest_relation( area_trigger_relation) count += 1 Logger.progress('Loading area trigger quest relations...', count, length) return length
def resolve_effect_select(casting_spell, target_effect): if target_effect.effect_type == SpellEffects.SPELL_EFFECT_SCHOOL_DAMAGE: # Hellfire, aura of rot units = EffectTargets.resolve_all_around_caster( casting_spell, target_effect) return EffectTargets.get_enemies_from_unit_list( units, casting_spell.spell_caster) if target_effect.effect_type == SpellEffects.SPELL_EFFECT_SUMMON_WILD or \ target_effect.effect_type == SpellEffects.SPELL_EFFECT_SUMMON or \ target_effect.effect_type == SpellEffects.SPELL_EFFECT_SUMMON_OBJECT_WILD: return [casting_spell.spell_caster] Logger.warning( f'Unimplemented implicit target called for spell {casting_spell.spell_entry.ID}' )
def start(): WorldServerSessionHandler._load_data() Logger.success('World server started.') WorldServerSessionHandler.schedule_updates() ThreadedWorldServer.allow_reuse_address = True ThreadedWorldServer.timeout = 10 with ThreadedWorldServer((config.Server.Connection.RealmServer.host, config.Server.Connection.WorldServer.port), WorldServerSessionHandler) as world_instance: world_session_thread = threading.Thread( target=world_instance.serve_forever()) world_session_thread.daemon = True world_session_thread.start()
def resolve_implicit_targets_reference(self, implicit_target): target = self.simple_targets[ implicit_target] if implicit_target in self.simple_targets else TARGET_RESOLVERS[ implicit_target](self.casting_spell) if target is None and implicit_target != 0: # Avoid crash on unfinished implementation while target resolving isn't finished TODO Logger.warning( f'Implicit target {implicit_target} resolved to None. Falling back to initial target or self.' ) target = self.initial_target if self.casting_spell.initial_target_is_object( ) else self.caster if type(target) is not list: return [target] return target
def load_gameobject_quest_starters(): gameobject_quest_starters = WorldDatabaseManager.gameobject_quest_starter_get_all( ) length = len(gameobject_quest_starters) count = 0 for gameobject_quest_starter in gameobject_quest_starters: WorldDatabaseManager.QuestRelationHolder.load_gameobject_starter_quest( gameobject_quest_starter) count += 1 Logger.progress('Loading gameobject quest starters...', count, length) return length
def do_training(self): self.logger = Logger(self.args, update_frequency=30) self.results = {"val": torch.zeros(self.args.epochs), "test": torch.zeros(self.args.epochs)} for self.current_epoch in range(self.args.epochs): self.logger.new_epoch(self.scheduler.get_lr()) self._do_epoch() self.scheduler.step() val_res = self.results["val"] test_res = self.results["test"] idx_best = val_res.argmax() print("Best val %g, corresponding test %g - best test: %g" % (val_res.max(), test_res[idx_best], test_res.max())) self.logger.save_best(test_res[idx_best], test_res.max()) return self.logger, self.model
def start(): ThreadedLoginServer.allow_reuse_address = True with ThreadedLoginServer((config.Server.Connection.RealmServer.host, config.Server.Connection.RealmServer.port), LoginServerSessionHandler) \ as login_instance: Logger.success( f'Login server started, listening on {login_instance.server_address[0]}:{login_instance.server_address[1]}' ) try: login_session_thread = threading.Thread( target=login_instance.serve_forever()) login_session_thread.daemon = True login_session_thread.start() except KeyboardInterrupt: Logger.info("Login server turned off.")
def get_liquid_information(map_id, x, y, z): try: map_tile_x, map_tile_y, tile_local_x, tile_local_y = MapManager.calculate_tile( x, y, RESOLUTION_LIQUIDS - 1) if not MapManager._check_tile_load(map_id, x, y, map_tile_x, map_tile_y): return None liquids = MAPS[map_id].tiles[map_tile_x][ map_tile_y].liquid_information[tile_local_x][tile_local_y] return liquids if liquids and liquids.height >= z else None except: Logger.error(traceback.format_exc()) return None
def handle(world_session, socket, reader): guid = 0 if len(reader.data ) >= 8: # Avoid handling empty area char delete packet. guid = unpack('<Q', reader.data[:8])[0] res = CharDelete.CHAR_DELETE_SUCCESS if guid == 0 or RealmDatabaseManager.character_delete(guid) != 0: res = CharDelete.CHAR_DELETE_FAILED Logger.error(f'Error deleting character with guid {guid}.') world_session.enqueue_packet( PacketWriter.get_packet(OpCode.SMSG_CHAR_DELETE, pack('<B', res))) return 0
def get_area_information(map_id, x, y): try: resolution = RESOLUTION_AREA_INFO - 1 map_tile_x, map_tile_y, tile_local_x, tile_local_y = MapManager.calculate_tile( x, y, resolution) if not MapManager._check_tile_load(map_id, x, y, map_tile_x, map_tile_y): return None return MAPS[map_id].tiles[map_tile_x][map_tile_y].area_information[ tile_local_x][tile_local_y] except: Logger.error(traceback.format_exc()) return None
def start(): ThreadedProxyServer.allow_reuse_address = True with ThreadedProxyServer((config.Server.Connection.RealmProxy.host, config.Server.Connection.RealmProxy.port), ProxyServerSessionHandler) \ as proxy_instance: Logger.success( f'Proxy server started, listening on {proxy_instance.server_address[0]}:{proxy_instance.server_address[1]}' ) try: proxy_session_thread = threading.Thread( target=proxy_instance.serve_forever()) proxy_session_thread.daemon = True proxy_session_thread.start() except KeyboardInterrupt: Logger.info("Proxy server turned off.")
def handle_summon_mount(casting_spell, effect, caster, target): already_mounted = target.unit_flags & UnitFlags.UNIT_MASK_MOUNTED if already_mounted: # Remove any existing mount auras. target.aura_manager.remove_auras_by_type(AuraTypes.SPELL_AURA_MOUNTED) target.aura_manager.remove_auras_by_type(AuraTypes.SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED) # Force dismount if target is still mounted (like a previous SPELL_EFFECT_SUMMON_MOUNT that doesn't # leave any applied aura). if target.mount_display_id > 0: target.unmount() target.set_dirty() else: creature_entry = effect.misc_value if not target.summon_mount(creature_entry): Logger.error(f'SPELL_EFFECT_SUMMON_MOUNT: Creature template ({creature_entry}) not found in database.')
def handle_aura_effect_change(aura, effect_target, remove=False, is_proc=False): aura_type = aura.spell_effect.aura_type if aura_type not in AURA_EFFECTS: Logger.debug( f'Unimplemented aura effect called: {aura.spell_effect.aura_type}' ) return if not is_proc and aura_type in PROC_AURA_EFFECTS: return # Only call proc effects when a proc happens. AURA_EFFECTS[aura.spell_effect.aura_type](aura, effect_target, remove)
def init_stats(self): if self.unit_mgr.get_type() == ObjectTypes.TYPE_PLAYER: base_stats = WorldDatabaseManager.player_get_class_level_stats( self.unit_mgr.player.class_, self.unit_mgr.level) base_attrs = WorldDatabaseManager.player_get_level_stats( self.unit_mgr.player.class_, self.unit_mgr.level, self.unit_mgr.player.race) if not base_stats or not base_attrs: Logger.error( f'Unsupported level ({self.unit_mgr.level}) from {self.unit_mgr.player.name}.' ) return self.base_stats[UnitStats.HEALTH] = base_stats.basehp self.base_stats[UnitStats.MANA] = base_stats.basemana self.base_stats[UnitStats.STRENGTH] = base_attrs.str self.base_stats[UnitStats.AGILITY] = base_attrs.agi self.base_stats[UnitStats.STAMINA] = base_attrs.sta self.base_stats[UnitStats.INTELLECT] = base_attrs.inte self.base_stats[UnitStats.SPIRIT] = base_attrs.spi self.unit_mgr.base_hp = base_stats.basehp self.unit_mgr.base_mana = base_stats.basemana else: # Creature self.base_stats[UnitStats.HEALTH] = self.unit_mgr.max_health self.base_stats[UnitStats.MANA] = self.unit_mgr.max_power_1 self.base_stats[ UnitStats. DODGE_CHANCE] = BASE_DODGE_CHANCE_CREATURE / 100 # Players don't have a flat dodge/block chance. self.base_stats[ UnitStats. BLOCK_CHANCE] = BASE_BLOCK_PARRY_CHANCE / 100 # Players have block scaling, assign flat 5% to creatures. # Don't overwrite base speed if it has been modified. self.base_stats[UnitStats.SPEED_RUNNING] = self.base_stats.get( UnitStats.SPEED_RUNNING, config.Unit.Defaults.run_speed) # Players and creatures have an unchanging base 5% chance to block and parry (before defense skill differences). # As block chance also scales with strength, the value is calculated in update_base_block_chance. self.base_stats[UnitStats.PARRY_CHANCE] = BASE_BLOCK_PARRY_CHANCE / 100 self.send_attributes() self.update_base_health_regen() self.update_base_mana_regen() self.update_base_proc_chance() self.update_defense_bonuses()
def load_data(): if config.Server.Settings.load_gameobjects: WorldLoader.load_gameobjects() else: Logger.info('Skipped game object loading.') if config.Server.Settings.load_creatures: WorldLoader.load_creatures() else: Logger.info('Skipped creature loading.') WorldLoader.load_spells() WorldLoader.load_skills() WorldLoader.load_skill_line_abilities() WorldLoader.load_taxi_nodes() WorldLoader.load_taxi_path_nodes()
class VMConfigurator(): logger = Logger.getLogger() @staticmethod def __getConfiguratorByNameAndOsType(configurator, os): if configurator and configurator != "": if configurator == MediacatVMConfigurator.getIdentifier(): return MediacatVMConfigurator else: if os.lower() == "debian" or os.lower() == "ubuntu": return OfeliaDebianVMConfigurator raise Exception("Unknown configurator") ##Public methods @staticmethod def configureVmDisk(vm, pathToMountPoint): VMConfigurator.__getConfiguratorByNameAndOsType( vm.xen_configuration.configurator, vm.operating_system_distribution).configureVmDisk( vm, pathToMountPoint) @staticmethod def createVmConfigurationFile(vm): VMConfigurator.__getConfiguratorByNameAndOsType( vm.xen_configuration.configurator, vm.operating_system_distribution).createVmConfigurationFile(vm)
def handle(world_session, socket, reader: PacketReader) -> int: player_mgr = world_session.player_mgr if not player_mgr: return 0 if not player_mgr.is_gm: Logger.anticheat( f'Player {player_mgr.player.name} ({player_mgr.guid}) tried create item.' ) return 0 if len(reader.data) >= 4: # Avoid handling empty create item packet. item_entry = unpack('<I', reader.data[:4])[0] CommandManager.additem(world_session, str(item_entry)) return 0
def __init__(self, **kwargs): # self.img_dir = kwargs['img_dir'] # self.label_dir = kwargs['label_dir'] self.original_dir = kwargs['original_dir'] self.train_dir = kwargs['train_dir'] self.test_dir = kwargs['test_dir'] self.log = kwargs['log'] self.model = kwargs['model'] # self.weight_save_path = kwargs['weight_save_path'] self.img_width = kwargs['img_width'] self.img_height = kwargs['img_height'] self.classes = kwargs['classes'] self.pre_train_weight_dir = kwargs['pre_train_weight_dir'] self.epoch_num = kwargs['epoch_num'] self.loss_list_iter = [] self.loss_list_epoch = [] self.lr_list_epoch = [] self.debug = kwargs['debug'] self.proportion = kwargs['proportion'] self.batch_size = kwargs['batch_size'] self.learning_rate = kwargs['learning_rate'] self.optimizer_mode = kwargs['optimizer_mode'] # self.pre_train_self = kwargs['pre_train_self'] self.weight_decay = kwargs['weight_decay'] self.momentum = kwargs['momentum'] ##### for debug ####### self.log_test = Logger('test/test_logger_1920.log', level='debug')
def add_location_to_user(user): try: if user.profile.place: place = json.loads(user.profile.place) location = Location.create( lat=repr(place['lat']), lng=repr(place['long']), city=place['city'], state=place['state'] if 'state' in place else '', country=place['country'], country_short=place['country_short'], post_code=place['post_code'] if 'post_code' in place else '', city_alias=place['city'] + ',') user.profile.location = location user.profile.latlong = ','.join( [format(place['lat'], '.6f'), format(place['long'], '.6f')]) user.profile.save() except Exception as e: print(Colorizer.Red('###############################')) print(Colorizer.Red('[ERROR Add location error]')) print(Logger.error(e)) print(Colorizer.Red('###############################')) else: print(Colorizer.Green('LOCATION OK: ' + user.email))
def handle(world_session, socket, reader): if len(reader.data) >= 8: # Avoid handling empty quest giver hello packet guid = unpack('<Q', reader.data[:8])[0] quest_giver = GridManager.get_surrounding_unit_by_guid(world_session.player_mgr, guid) if not quest_giver: Logger.error("Error in CMSG_QUESTGIVER_HELLO, could not find quest giver with guid of: %u" % guid) return 0 if world_session.player_mgr.is_enemy_to(quest_giver): return 0 # TODO: Stop the npc if it's moving # TODO: Remove feign death from player (if it even exists in 0.5.3) # TODO: If the gossip menu is already open, do nothing world_session.player_mgr.quest_manager.prepare_quest_giver_gossip_menu(quest_giver, guid) return 0
def main(): logger = Logger(name = "runner_test") service = FDTService(logger) report(service, logger) # number of FDT Java servers to create numServers = 3 ids = ["request-%03d" % i for i in range(numServers)] threads = [] for id in ids: runner = ThreadCaller(id, "FDT caller", service.service, logger) runner.start() threads.append(runner) # wait until all threads finish ... no matter how but must finish logger.info("Waiting for FDT caller threads to terminate ...") for t in threads: t.join() report(service, logger) threads = [] # commenting out this section - cleaning up and restarting the # script should show reliable failure reporting since the ports # occupied from the previous script run for id in ids: wiper = ThreadCaller(id, "FDT wiper", service.cleanUp, logger) wiper.start() threads.append(wiper) # wait until all threads finish ... no matter how but must finish logger.info("Waiting for FDT wiper threads to terminate ...") for t in threads: t.join() report(service, logger)
import logging ''' @author: msune, omoya @organization: i2CAT, OFELIA FP7 Simple Logger wrapper for Libvirt Event Monitoring ''' from utils.Logger import Logger Libvirt = Logger.getLogger() #Libvirt Monitoring Log File LIBVIRT_LOG='/opt/ofelia/oxa/log/libvirtmonitor.log' class LibvirtLogger(): @staticmethod def getLogger(): #Simple wrapper. Ensures logging is always correctly configured (logging.basicConfig is executed) return Libvirt.addHandler(logging.FileHandler(LIBVIRT_LOG))
from monitoring.LibvirtMonitoring import LibvirtMonitor from communications.XmlRpcServer import XmlRpcServer from utils.ServiceThread import ServiceThread from utils.XmlUtils import * from utils.xml.vtRspecInterface import rspec from settings.settingsLoader import OXA_LOG from utils.Logger import Logger """ @author: msune OXA: Ofelia XEN Agent. """ logger = Logger.getLogger() """ Usage message """ def usage(): # return "\nOXA: Ofelia XEN Agent utility. This utility expects as an argument an XML query, and performs\nXEN VM provisioning and monitoring operations. \n\n Usage:\n \t OXA.py xmlQuery" return "TODO" # TODO """ Argument checking """ def checkArgs(): if len(sys.argv) > 2: raise Exception("Illegal number of arguments\n\n" + usage())