def levy(self): char = Char(self.char_id).mc if self.counter.remained_value <= 0: if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.LEVY_NO_TIMES, self.char_id, "Levy", "no times. but can get additional times by increase vip level. current: {0}, max: {1}" .format(char.vip, VIP_MAX_LEVEL)) raise SanguoException( errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy", "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL)) resource = Resource(self.char_id, "Levy") cost_cyess = self.get_cost_sycee() with resource.check(sycee=-cost_cyess): drop = self.get_levy_drop() self.counter.incr() standard_drop = resource.add(**drop) t = Task(self.char_id) t.trig(4) self.send_notify() return standard_drop
def trigger_run(self, funcs, single, *args, **kwargs): if not funcs: return [] if self.threaded: tasks = [] for name, func in funcs: task = Task(func, *args, **kwargs) tasks.append(task) task.spawn('sync.%s.%s' % (self.key, name)) # Wait until everything is complete results = [] for task in tasks: task.wait() results.append(task.result) return results # Run each task and collect results results = [func(*args, **kwargs) for (_, func) in funcs] if not single: return results return results[0]
def levy(self): char = Char(self.char_id).mc if self.counter.remained_value <= 0: if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.LEVY_NO_TIMES, self.char_id, "Levy", "no times. but can get additional times by increase vip level. current: {0}, max: {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy", "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL) ) resource = Resource(self.char_id, "Levy") cost_cyess = self.get_cost_sycee() with resource.check(sycee=-cost_cyess): drop = self.get_levy_drop() self.counter.incr() standard_drop = resource.add(**drop) t = Task(self.char_id) t.trig(4) self.send_notify() return standard_drop
def plunder(self): if not self.mongo_plunder.char_id: raise SanguoException(errormsg.PLUNDER_NO_RIVAL, self.char_id, "Plunder Battle", "no rival target") if self.mongo_plunder.current_times <= 0: raise SanguoException(errormsg.PLUNDER_NO_TIMES, self.char_id, "Plunder Battle", "no times") self.change_current_plunder_times(change_value=-1) rival_battle_heros = dill.loads( base64.b64decode(self.mongo_plunder.battle_heros)) msg = MsgBattle() pvp = PlunderBattle( self.char_id, self.mongo_plunder.char_id, msg, self.mongo_plunder.char_name, rival_battle_heros, ) pvp.start() t = Task(self.char_id) t.trig(3) to_char_id = self.mongo_plunder.char_id target_server_url = self.mongo_plunder.server_url if msg.self_win: standard_drop = self._get_plunder_reward( self.mongo_plunder.char_city_id, self.mongo_plunder.char_gold, self.mongo_plunder.char_hero_original_ids) self.clean_plunder_target() achievement = Achievement(self.char_id) achievement.trig(12, 1) PlunderLeaderboardWeekly.incr(self.char_id) TimesLogPlunder(self.char_id).inc() else: standard_drop = make_standard_drop_from_template() self.mongo_plunder.plunder_times += 1 self.mongo_plunder.save() self.send_notify() plunder_finished_signal.send( sender=None, from_char_id=self.char_id, from_char_name=Char(self.char_id).mc.name, to_char_id=to_char_id, from_win=msg.self_win, standard_drop=standard_drop, target_server_url=target_server_url, ) return (msg, standard_drop)
def battle(self): need_sycee = 0 counter = Counter(self.char_id, 'arena') if counter.remained_value <= 0: counter = Counter(self.char_id, 'arena_buy') if counter.remained_value <= 0: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle", "arena no times. vip current: {0}, max {1}".format( char.vip, VIP_MAX_LEVEL)) raise SanguoException( errormsg.ARENA_NO_TIMES_FINAL, self.char_id, "Arena Battle", "arena no times. vip reach max level {0}".format( VIP_MAX_LEVEL)) else: need_sycee = ARENA_COST_SYCEE rival_id = self.choose_rival() if not rival_id: raise SanguoException(errormsg.ARENA_NO_RIVAL, self.char_id, "Arena Battle", "no rival.") if need_sycee: resource = Resource(self.char_id, "Arena Battle", "battle for no free times") resource.check_and_remove(sycee=-need_sycee) counter.incr() # set battle cd redis_client.setex(REDIS_ARENA_BATTLE_CD_KEY(rival_id), 1, ARENA_CD) msg = protomsg.Battle() b = PVP(self.char_id, rival_id, msg) b.start() if msg.self_win: achievement = Achievement(self.char_id) achievement.trig(11, 1) self_score = self.score rival_arena = Arena(rival_id) rival_score = rival_arena.score new_score = calculate_score(self_score, rival_score, msg.self_win) self.set_score(new_score) t = Task(self.char_id) t.trig(2) self.send_notify(score=new_score) rival_arena.be_beaten(rival_score, self_score, not msg.self_win, self.char_id) return msg
def levy(self): char = Char(self.char_id).mc if self.counter.remained_value <= 0: if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.LEVY_NO_TIMES, self.char_id, "Levy", "no times. but can get additional times by increase vip level. current: {0}, max: {1}" .format(char.vip, VIP_MAX_LEVEL)) raise SanguoException( errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy", "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL)) resource = Resource(self.char_id, "Levy") cost_cyess = self.get_cost_sycee() with resource.check(sycee=-cost_cyess): got_gold = LEVY_GOT_GOLD_FUNCTION(char.level) prob = random.randint(1, 100) for k, v in LEVY_CRIT_PROB_TABLE: if prob <= k: break got_gold *= v self.counter.incr() resource.add(gold=got_gold) t = Task(self.char_id) t.trig(4) self.send_notify() return got_gold
def get_attachment(self, prize_id, param=0): # prizie_id == 1 挂机不在这里 if prize_id == 4: # 成就 from core.achievement import Achievement ach = Achievement(self.char_id) att_msg = ach.get_reward(param) if ach.has_prizes(): prize_id = None elif prize_id == 5: # 任务 from core.task import Task task = Task(self.char_id) att_msg = task.get_reward(param) if task.has_prizes(): prize_id = None elif prize_id == 6: # 官职每日登录 # from core.daily import OfficialDailyReward # od = OfficialDailyReward(self.char_id) # att_msg = od.get_reward() att_msg = None elif prize_id == 7: # 团队本 att_msg = None else: try: attachment = self.attachment.attachments[str(prize_id)] except KeyError: raise SanguoException( errormsg.ATTACHMENT_NOT_EXIST, self.char_id, "Attachment Get", "{0} not exist".format(prize_id) ) attachment = json.loads(attachment) resource = Resource(self.char_id, "Prize {0}".format(prize_id)) standard_drop = resource.add(**attachment) self.attachment.attachments.pop(str(prize_id)) self.attachment.save() att_msg = standard_drop_to_attachment_protomsg(standard_drop) # 删除此prize_id if prize_id: if prize_id in self.attachment.prize_ids: self.attachment.prize_ids.remove(prize_id) if str(prize_id) in self.attachment.attachments: self.attachment.attachments.pop(str(prize_id)) self.attachment.save() self.send_notify() return att_msg
def battle(self): counter = Counter(self.char_id, 'arena') try: # 免费次数 counter.incr() except CounterOverFlow: counter = Counter(self.char_id, 'arena_buy') try: # 花费元宝次数 counter.incr() except CounterOverFlow: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle", "arena no times. vip current: {0}, max {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.ARENA_NO_TIMES_FINAL, self.char_id, "Arena Battle", "arena no times. vip reach max level {0}".format(VIP_MAX_LEVEL) ) else: resource = Resource(self.char_id, "Arena Battle", "battle for no free times") resource.check_and_remove(sycee=-ARENA_COST_SYCEE) rival_id = self.choose_rival() msg = protomsg.Battle() b = PVP(self.char_id, rival_id, msg) b.start() achievement = Achievement(self.char_id) if msg.self_win: score = ARENA_GET_SCORE_WHEN_WIN achievement.trig(11, 1) self.mongo_arena.continues_win += 1 else: score = ARENA_GET_SCORE_WHEN_LOST self.mongo_arena.continues_win = 0 self.mongo_arena.save() if score: self.mongo_day.score += score self.mongo_day.save() t = Task(self.char_id) t.trig(2) self.send_notify() return msg
def battle(self): counter = Counter(self.char_id, 'arena') try: # 免费次数 counter.incr() except CounterOverFlow: counter = Counter(self.char_id, 'arena_buy') try: # 花费元宝次数 counter.incr() except CounterOverFlow: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle", "arena no times. vip current: {0}, max {1}".format( char.vip, VIP_MAX_LEVEL)) raise SanguoException( errormsg.ARENA_NO_TIMES_FINAL, self.char_id, "Arena Battle", "arena no times. vip reach max level {0}".format( VIP_MAX_LEVEL)) else: resource = Resource(self.char_id, "Arena Battle", "battle for no free times") resource.check_and_remove(sycee=-ARENA_COST_SYCEE) rival_id = self.choose_rival() msg = protomsg.Battle() b = PVP(self.char_id, rival_id, msg) b.start() achievement = Achievement(self.char_id) if msg.self_win: score = ARENA_GET_SCORE_WHEN_WIN achievement.trig(11, 1) self.mongo_arena.continues_win += 1 else: score = ARENA_GET_SCORE_WHEN_LOST self.mongo_arena.continues_win = 0 self.mongo_arena.save() if score: self.mongo_day.score += score self.mongo_day.save() t = Task(self.char_id) t.trig(2) self.send_notify() return msg
def prisoner_get(self, _id, treasures): str_id = str(_id) if str_id not in self.p.prisoners: raise SanguoException(errormsg.PRISONER_NOT_EXIST, self.char_id, "Prisoner Get", "{0} not exist".format(_id)) if not self.p.prisoners[str_id].active: raise SanguoException(errormsg.PRISONER_NOT_ACTIVE, self.char_id, "Prisoner Get", "{0} not active".format(_id)) treasures_prob = 0 for tid in treasures: try: treasures_prob += TREASURES[tid].value except KeyError: raise SanguoException(errormsg.STUFF_NOT_EXIST, self.char_id, "Prisoner Get", "treasure {0} not exist".format(tid)) using_stuffs = [(tid, 1) for tid in treasures] resource = Resource(self.char_id, "Prisoner Get") with resource.check(stuffs=using_stuffs): got = False prob = self.p.prisoners[str_id].prob + treasures_prob char = Char(self.char_id).mc vip_plus = VIP_FUNCTION[char.vip].prisoner_get prob += vip_plus if prob >= random.randint(1, 100): # got it save_hero(self.char_id, self.p.prisoners[str_id].oid) got = True self.p.prisoners.pop(str_id) msg = protomsg.RemovePrisonerNotify() msg.ids.append(_id) publish_to_char(self.char_id, pack_msg(msg)) else: self.p.prisoners[str_id].active = False msg = protomsg.UpdatePrisonerNotify() p = msg.prisoner.add() p_obj = self.p.prisoners[str_id] self._fill_up_prisoner_msg(p, _id, p_obj.oid, p_obj.prob, p_obj.active) publish_to_char(self.char_id, pack_msg(msg)) self.p.save() t = Task(self.char_id) t.trig(5) return got
def pve_finish(char_id, stage_id, win, star, **kwargs): achievement = Achievement(char_id) if win: achievement.trig(7, stage_id) if star: achievement.trig(9, 1) t = Task(char_id) t.trig(1) else: achievement.trig(8, 1)
def plunder(self): if not self.mongo_plunder.char_id: raise SanguoException(errormsg.PLUNDER_NO_RIVAL, self.char_id, "Plunder Battle", "no rival target") if self.mongo_plunder.current_times <= 0: raise SanguoException(errormsg.PLUNDER_NO_TIMES, self.char_id, "Plunder Battle", "no times") self.change_current_plunder_times(change_value=-1) rival_battle_heros = dill.loads(base64.b64decode(self.mongo_plunder.battle_heros)) msg = MsgBattle() pvp = PlunderBattle( self.char_id, self.mongo_plunder.char_id, msg, self.mongo_plunder.char_name, rival_battle_heros ) pvp.start() t = Task(self.char_id) t.trig(3) to_char_id = self.mongo_plunder.char_id target_server_url = self.mongo_plunder.server_url if msg.self_win: standard_drop = self._get_plunder_reward( self.mongo_plunder.char_city_id, self.mongo_plunder.char_gold, self.mongo_plunder.char_hero_original_ids ) self.clean_plunder_target() achievement = Achievement(self.char_id) achievement.trig(12, 1) PlunderLeaderboardWeekly.incr(self.char_id) else: standard_drop = make_standard_drop_from_template() self.mongo_plunder.plunder_times += 1 self.mongo_plunder.save() self.send_notify() plunder_finished_signal.send( sender=None, from_char_id=self.char_id, from_char_name=Char(self.char_id).mc.name, to_char_id=to_char_id, from_win=msg.self_win, standard_drop=standard_drop, target_server_url=target_server_url, ) return (msg, standard_drop)
def setUp(self): p = Project(name='Test Project') self.task = Task(p) p.append_task(self.task) props = getProperties(self.task) self.props = [ 'project_name' , 'id' , 'name' 'description' , 'path' , 'taskobject_name' , 'taskobject_help', 'command_name' , 'setting' , 'config' , 'config_view' , 'state_name' , 'inputs' , 'outputs' , ] self.methods = [ 'save' , 'load' , 'copy' , 'delete' , 'tail' , ] self.requests = [ 'defineTaskObject' , 'invokeConvert' , 'invokeSend' , 'invokeSubmit' , 'invokeStop' , 'invokeAbort' , 'invokeReceive' , ] self.event = self.task.getEvent('none_object') self.event = self.task.getEvent('init')
def queue_task(task: Task): task.data_model.save() for i in task.jobs: i.task = task.data_model i.save() task.id = task.data_model.id return task.data_model.id
def example(cluster, scheduler, filepath_input, filepath_output): all_batch_tasks = FileIo(filepath_input).readAllBatchLines() # 调度器初始化 if scheduler == "random": my_scheduler = Random_scheduler(len(cluster.machines)) elif scheduler == "earliest": my_scheduler = Earliest_scheduler(len(cluster.machines)) elif scheduler == "rr": my_scheduler = Round_robin_scheduler(len(cluster.machines)) for batch_tasks in all_batch_tasks: tasks_list = [] for task in batch_tasks: tasks_list.append(Task(task[0], task[1], task[2], task[3])) # 构建任务 if scheduler == "random": machines_id = my_scheduler.scheduler(len(tasks_list)) elif scheduler == "earliest": machines_id = my_scheduler.scheduler_o(len(tasks_list), tasks_list[0].start_time, cluster.machines) elif scheduler == "rr": machines_id = my_scheduler.scheduler(len(tasks_list)) cluster.submit_tasks(tasks_list, machines_id) # 提交任务到集群,并调度到虚拟机进行计算 finished_tasks = [] for task in cluster.finished_tasks: finished_tasks.append(task.feature) FileIo(filepath_output).twoListToFile(finished_tasks, "w")
def command(message, time, project, category, links): """ Use this command to start a new task, this command will track when the task started and this information as a metadata of your task. $ trackmywork start -m "Starting my task" -p "trackmywork" -c "personal" -t 2h You successfully started the task 1 - "Starting my task" # Adding links to a task $ trackmywork start -m "Task with links" -l "http://google.com" -t 2h The task 2 - "Task with links" was started with success. """ task = Task.create( message=message, time=time, category=category, links=links, project=project ) task.start() task = storage.save(task) click.echo(f'The task {task.id} - "{task.message}" was started with success.')
def create_uninstall_task(products: ProductCollection): """ фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UNINSTALL сохранить в базе данных зхапустить воркер :param requested_products: :param products: :param parameter_manager: :return: """ job_array = [] settings = json_encode(Core.get_instance().settings.get_state()) task_object = TaskDataModel(command="uninstall", settings=settings) for product in products: state = { 'products': [product.name], } job = JobDataModel(command=JobDataModel.COMMAND_UNINSTALL, title=product.title, params=json_encode(state), settings=settings) job_array.append(job) task = Task(task_model=task_object, jobs=job_array) return task
def create_install_task(products: ProductCollection, parameter_manager: ParametersManager): """ фабричный метод: создать такс с переданными параметрами, с типом COMMAND_INSTALL сохранить в базе данных зхапустить воркер :param products: продукты для установки (продукты которые выбрал пользователь + зависимости) :param parameter_manager: :return: номер таска """ settings = json_encode(Core.get_instance().settings.get_state()) job_array = [] task_object = TaskDataModel(command="install", settings=settings) for product in products: title = product.title state = { 'products': [product.to_dict()], 'parameters': parameter_manager.get_state() } state2save = json_encode(state) job = JobDataModel(command=JobDataModel.COMMAND_INSTALL, title=title, params=state2save, task=task_object, settings=settings) job_array.append(job) task = Task(task_model=task_object, jobs=job_array) return task
def battle(self, _id): try: self.this_stage = STAGE_ACTIVITY[_id] except KeyError: raise SanguoException(errormsg.STAGE_ACTIVITY_NOT_EXIST, self.char_id, "StageActivity Battle", "StageActivity {0} not exist".format(_id)) if _id not in self.stage.activities: raise SanguoException(errormsg.STAGE_ACTIVITY_NOT_OPEN, self.char_id, "StageActivity Battle", "StageActivity {0} not open".format(_id)) counter = ActivityStageCount(self.char_id) counter.make_func_name(self.this_stage.tp) if counter.remained_value <= 0: raise SanguoException( errormsg.STAGE_ACTIVITY_TOTAL_NO_TIMES, self.char_id, "StageActivity Battle", "StageActivity no total times. battle {0}".format(_id)) battle_msg = protomsg.Battle() b = ActivityPVE(self.char_id, _id, battle_msg) b.start() if battle_msg.self_win: counter.incr() self.send_remained_times_notify() Task(self.char_id).trig(9) return battle_msg
def create_upgrade_task(products: ProductCollection, parameter_manager: ParametersManager): """ фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UPGRADE сохранить в базе данных зхапустить воркер :param products: :param parameter_manager: :return: """ settings = json_encode(Core.get_instance().settings.get_state()) job_array = [] task_object = TaskDataModel(command="upgrade", settings=settings) for product in products: title = product.title state = { 'products': [product.to_dict()], 'parameters': parameter_manager.get_state() } state2save = json_encode(state) job = JobDataModel(command=JobDataModel.COMMAND_UPGRADE, title=title, params=state2save, task=task_object, settings=settings) job_array.append(job) task = Task(task_model=task_object, jobs=job_array) return task
def run(config): # load backends backends = core.backend.load_backends(config["backends"]) for task in config["tasks"]: # load task effects effects = [] for effect_config in task["effects"]: effect = core.effect.load_effect(effect_config, backends) effects.append(effect) # load the source source = core.source.load_source(task["source"]) # create a new thread for the task task = Task(task["interval"], source, effects) task.start()
def run(self): while 1: # sleep for decrease cpu usage sleep(0.01) QCoreApplication.processEvents() from_db = False if self.running_tasks.__len__() >= self.limit(): continue try: if self.items: from_db = True item = self.items.pop() else: item = self.queue.get() # type: RequestObject if item: if not from_db: task_model = TaskModel() task_model.route = item.route task_model.process_id = item.process_id task_model.status = constants.STATUS_RUNNING task_model.data = item.data task_model.call_back = item.call_back task_model.token = item.token task_model.module_version = item.module_version task_model.queue_name = self.queue_name task_model.save() else: task_model = item task = Task(task_model) if task.instance_module: task.instance_module.task_finished.connect(self.__task_finished) task.setAutoDelete(True) self.running_tasks.update({item.process_id: task}) # check cancel or pause request before start self.apply_action_by_pid(task, item.process_id) self.pool.start(task) else: # TODO: set error alarm ApiLogging.error('problem running task') except Exception as e: ApiLogging.error('process exception' + str(e)) # TODO: set error alarm continue
def on_add_task(self, event): if self.project is None: return task = Task(project=self.project) selected_index = self.project.selected_task_index command = AddTaskCommand(True, 'Add Task', task, selected_index, self.project) self.command_processor.Submit(command)
def pve_finish(char_id, stage_id, win, star, **kwargs): achievement = Achievement(char_id) if win: achievement.trig(7, stage_id) if star: achievement.trig(9, 1) t = Task(char_id) t.trig(1) else: achievement.trig(8, 1) # 城镇 # 自动开启第一个城镇,并且自动开始挂机 if win: if STAGES[stage_id].battle_end: affairs = Affairs(char_id) new_opened = affairs.open_city(STAGES[stage_id].battle) if STAGES[stage_id].battle == FIRST_CITY_ID and new_opened: affairs.start_hang(FIRST_CITY_ID)
def pve_finish(char_id, stage_id, win, star, **kwargs): achievement = Achievement(char_id) if win: achievement.trig(7, stage_id) if star: achievement.trig(9, 1) t = Task(char_id) t.trig(1) else: achievement.trig(8, 1) # 开启城镇 if win: if STAGES[stage_id].battle_open: affairs = Affairs(char_id) affairs.open_city(STAGES[stage_id].battle) # 判断活动 if win: ActivityStatic(char_id).trig(3001)
def test_connectionList(self): fl1 = Task(departure=DayWeekDay(a_date=datetime.datetime(2016, 1, 1), a_time=datetime.time(8, 0, 0)), origin="LPA", destination="TFN", task_number="101", duration=timedelta(minutes=30)) fl2 = Task(departure=DayWeekDay(a_date=datetime.datetime(2016, 1, 1), a_time=datetime.time(10, 0, 0)), origin="TFN", destination="LPA", task_number="102", duration=timedelta(minutes=30)) fl3 = Task(departure=DayWeekDay(a_date=datetime.datetime(2016, 1, 1), a_time=datetime.time(11, 0, 0)), origin="TFN", destination="LPA", task_number="104", duration=timedelta(minutes=60)) connect1 = connection([fl1, fl2]) connect2 = connection([fl1, fl3]) cl = connectionList(best_connection=False) cl.add(connect1) cl.add(connect2) self.assertEqual(2, len(cl.getList())) connection_list = connectionList(best_connection=True) connection_list.add(connect1) connection_list.add(connect2) self.assertEqual(1, len(connection_list.getList())) self.assertEqual(connection_list.getList()[0].get_duration(), connect1.get_duration())
def login_notify(char_id): hero_objs = char_heros_obj(char_id) Char(char_id).send_notify() hero_notify(char_id, hero_objs) Item(char_id).send_notify() f = Formation(char_id) f.send_socket_notify() f.send_formation_notify() hang = Hang(char_id) hang.send_notify() Plunder(char_id).send_notify() p = Prison(char_id) p.send_prisoners_notify() Arena(char_id).send_notify() f = Friend(char_id) f.send_friends_notify() f.send_friends_amount_notify() m = Mail(char_id) m.send_mail_notify() CheckIn(char_id).send_notify() stage = Stage(char_id) stage.send_already_stage_notify() stage.send_new_stage_notify() stage_elite = EliteStage(char_id) stage_elite.send_notify() stage_elite.send_remained_times_notify() stage_activity = ActivityStage(char_id) stage_activity.send_notify() stage_activity.send_remained_times_notify() HeroPanel(char_id).send_notify() Task(char_id).send_notify() Achievement(char_id).send_notify() HeroSoul(char_id).send_notify() FunctionOpen(char_id).send_notify() Levy(char_id).send_notify() Attachment(char_id).send_notify()
def levy(self): char = Char(self.char_id).mc if self.counter.remained_value <= 0: if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.LEVY_NO_TIMES, self.char_id, "Levy", "no times. but can get additional times by increase vip level. current: {0}, max: {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.LEVY_NO_TIMES_FINAL, self.char_id, "Levy", "no times. vip reach the max level {0}".format(VIP_MAX_LEVEL) ) resource = Resource(self.char_id, "Levy") cost_cyess = self.get_cost_sycee() with resource.check(sycee=-cost_cyess): got_gold = LEVY_GOT_GOLD_FUNCTION(char.level) prob = random.randint(1, 100) for k, v in LEVY_CRIT_PROB_TABLE: if prob <= k: break got_gold *= v self.counter.incr() resource.add(gold=got_gold) t = Task(self.char_id) t.trig(4) self.send_notify() return got_gold
def gem_merge(self, _id): this_gem_amount = self.item.gems.get(str(_id), 0) if this_gem_amount == 0: raise SanguoException( errormsg.GEM_NOT_EXIST, self.char_id, "Gem Merge", "Gem {0} not exist".format(_id) ) elif this_gem_amount < 4: raise SanguoException( errormsg.GEM_NOT_ENOUGH, self.char_id, "Gem Merge", "Gem {0} not enough. {1} < 4".format(_id, this_gem_amount) ) to_id = GEMS[_id].merge_to if not to_id: raise SanguoException( errormsg.GEM_CAN_NOT_MERGE, self.char_id, "Gem Merge", "Gem {0} can not merge".format(_id) ) self.gem_remove(_id, 4) self.gem_add([(to_id, 1)]) to_gem_obj = GEMS[to_id] achievement = Achievement(self.char_id) achievement.trig(25, 1) achievement.trig(26, to_gem_obj.level) t = Task(self.char_id) t.trig(4)
def main(taskDim, vmDim, cluster, filepath_input, filepath_output): vmsNum = len(cluster.machines) all_batch_tasks = FileIo(filepath_input).readAllBatchLines() print("环境创建成功!") state_all = [] # 存储所有的状态 [None,2+2*20] action_all = [] # 存储所有的动作 [None,1] reward_all = [] # 存储所有的奖励 [None,1] DRL = DQN(taskDim, vmsNum, vmDim) print("网络初始化成功!") for step, batch_tasks in enumerate(all_batch_tasks): tasks_list = [] for task in batch_tasks: tasks_list.append(Task(task[0], task[1], task[2], task[3])) # 构建任务 states = get_state(tasks_list, cluster.machines) state_all += states machines_id = DRL.choose_action(np.array(states)) # 通过调度算法得到分配 id machines_id = machines_id.astype(int).tolist() cluster.submit_tasks(tasks_list, machines_id) # 提交任务到集群,并调度到虚拟机进行计算 for i, task in enumerate(cluster.finished_tasks[-len(tasks_list):] ): # 便历新提交的一批任务,记录动作和奖励 action_all.append([task.task_machine_id]) reward_all.append([task.mi / task.task_response_time / 100 ]) # 计算奖励 # 减少存储数据量 if len(state_all) > 20000: state_all = state_all[-10000:] action_all = action_all[-10000:] reward_all = reward_all[-10000:] # 先学习一些经验,再学习 if step > 400: # 截取最后10000条记录 new_state = np.array(state_all, dtype=np.float32)[-10000:-1] new_action = np.array(action_all, dtype=np.float32)[-10000:-1] new_reward = np.array(reward_all, dtype=np.float32)[-10000:-1] DRL.store_memory(new_state, new_action, new_reward) DRL.step = step loss = DRL.learn() print("step:", step, ", loss:", loss) finished_tasks = [] for task in cluster.finished_tasks: finished_tasks.append(task.feature) FileIo(filepath_output).twoListToFile(finished_tasks, "w")
def save(task: Task) -> Task: """ Insert or update a task into the storage. Args: task a task to be inserted or updated Return The task after saving it into the storage """ if not task.id: task.id = _get_next_id() _insert_new_task(task) else: _update_task(task) return task
def _func_opened(char_id, func_ids, **kwargs): need_task_notify = False task_related_func_ids = [t.func for t in TASKS.values() if t.func] for _id in func_ids: if _id in task_related_func_ids: need_task_notify = True break if need_task_notify: Task(char_id).send_notify() # dirty fix... # 比武功能没开放的时候,没有初始化 # 所以在这里要初始化以便自动进入竞技场 from core.arena import Arena for _id in func_ids: if _id == Arena.FUNC_ID: Arena(char_id).send_notify()
def command(message, time, project, category, links): """ Use this command to register a task without tracking the start and finish time. $ trackmywork register -m "Starting my task" -p "trackmywork" -c "personal" -t 2h The task 1 - "Starting my task" was registered with success. """ task = Task.create(message=message, time=time, category=category, links=links, project=project) task.start() task.finish() task = storage.save(task) click.echo( f'The task {task.id} - "{task.message}" was registered with success.')
def battle(self): need_sycee = 0 counter = Counter(self.char_id, 'arena') if counter.remained_value <= 0: counter = Counter(self.char_id, 'arena_buy') if counter.remained_value <= 0: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle", "arena no times. vip current: {0}, max {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.ARENA_NO_TIMES_FINAL, self.char_id, "Arena Battle", "arena no times. vip reach max level {0}".format(VIP_MAX_LEVEL) ) else: need_sycee = ARENA_COST_SYCEE rival_id = self.choose_rival() if not rival_id: raise SanguoException( errormsg.ARENA_NO_RIVAL, self.char_id, "Arena Battle", "no rival." ) if need_sycee: resource = Resource(self.char_id, "Arena Battle", "battle for no free times") resource.check_and_remove(sycee=-need_sycee) counter.incr() # set battle cd redis_client.setex(REDIS_ARENA_BATTLE_CD_KEY(rival_id), 1, ARENA_CD) msg = protomsg.Battle() b = PVP(self.char_id, rival_id, msg) b.start() t = Task(self.char_id) t.trig(2) drop = make_standard_drop_from_template() adding_score = 0 if msg.self_win: achievement = Achievement(self.char_id) achievement.trig(11, 1) # 只有打赢才设置积分 self_score = self.score rival_arena = Arena(rival_id) rival_score = rival_arena.score new_score = calculate_score(self_score, rival_score, msg.self_win) self.set_score(new_score) adding_score = new_score - self_score rival_arena.be_beaten(rival_score, self_score, not msg.self_win, self.char_id) TimesLogArenaWin(self.char_id).inc() ae = ActivityEntry(self.char_id, 50004) if ae and ae.is_valid(): drop = ae.get_additional_drop() Resource(self.char_id, "Arena Win").add(**drop) TimesLogArena(self.char_id).inc() ae = ActivityEntry(self.char_id, 40006) if ae: ae.trig() self.send_notify() drop['stuffs'].append((1001, adding_score)) return msg, drop
def get_queue(self): task_id = 0 for resource in self.payload: if self.uppercase: resource = resource.upper() task_id += 1 # Useful when looking for files without extension instead of directories if self.remove_slash and resource.endswith("/"): resource = resource[:-1] for extension in self.extensions: # If resource is a whole word and user didnt provide a extension # put a final / if not extension and not _has_extension(resource) and not self.remove_slash: resource += '/' # Put a . before extension if the users didnt do it if extension and not '.' in extension: extension = '.' + extension task = Task(task_id, self.target, resource, extension) task.set_payload_filename(self.payload_filename) task.set_payload_length(self.length) task.set_banned_response_codes(self.banned_response_codes) task.set_unbanned_response_codes(self.unbanned_response_codes) task.set_content(self.content) self.queue.put(task) return self.queue
def _feed_queue(self): for resource in self.payload: if self.only_alpha: if not resource.isalnum(): continue if self.uppercase: resource = resource.upper() if self.capitalize: resource = resource.capitalize() if self.strip_extension: resource = resource.split('.')[0] # Useful when looking for files without extension instead of directories if self.remove_slash and resource.endswith("/"): resource = resource[:-1] for extension in self.extensions: # If resource is a whole word and user didnt provide a extension # put a final / if not extension and not _has_extension(resource) and not self.remove_slash: resource += '/' # Put a . before extension if the users didnt do it if extension and not '.' in extension: extension = '.' + extension self.task_id += 1 task = Task(self.task_id, self.target, resource, extension) task.set_payload_filename(self.payload_filename) task.set_payload_length(self.get_total_requests()) task.set_banned_response_codes(self.banned_response_codes) task.set_unbanned_response_codes(self.unbanned_response_codes) task.set_content(self.content) self.queue.put(task) self.number_of_tasks += 1
class TestNoneObjectState: def setUp(self): p = Project(name='Test Project') self.task = Task(p) p.append_task(self.task) props = getProperties(self.task) self.props = [ 'project_name' , 'id' , 'name' 'description' , 'path' , 'taskobject_name' , 'taskobject_help', 'command_name' , 'setting' , 'config' , 'config_view' , 'state_name' , 'inputs' , 'outputs' , ] self.methods = [ 'save' , 'load' , 'copy' , 'delete' , 'tail' , ] self.requests = [ 'defineTaskObject' , 'invokeConvert' , 'invokeSend' , 'invokeSubmit' , 'invokeStop' , 'invokeAbort' , 'invokeReceive' , ] self.event = self.task.getEvent('none_object') self.event = self.task.getEvent('init') def tearDown(self): pass def testInit(self): assert_equal(self.task.project_name , 'Test Project' ) assert_equal(self.task.id , 1 ) assert_equal(self.task.name , 'task 1' ) assert_equal(self.task.description , '' ) assert_equal(self.task.path , 'path' ) assert_equal(self.task.state_name , 'NoneObject' ) assert_equal(self.task.taskobject_name , 'None' ) assert_equal(self.task.taskobject_help , 'None' ) assert_equal(self.task.command_name , None ) # assert_equal(self.task.setting, None) # assert_equal(self.task.config, None) # assert_equal(self.task.config_view, None) # assert_equal(self.task.inputs, None) def testSetProperies(self): task = self.task task.name = 'Test Task' assert_equal(task.name, 'Test Task') task.description = 'This is a task note' assert_equal(task.description, 'This is a task note') def testDefineTaskObject(self): self.task.defineTaskObject('optimize') assert_equal(self.task.state_name, 'Init') def testOtherRequests(self): ec = EventCatcher(self.task.getEvent('init')) assertRequests(self.task, ['defineTaskObject'], 'NoneObject', ec) assertProperties(self.task, {})
def plunder(self, _id): if str(_id) not in self.mongo_plunder.chars: raise SanguoException( errormsg.PLUNDER_NOT_IN_LIST, self.char_id, "Plunder Plunder", "Plunder, {0} not in plunder list".format(_id) ) counter = Counter(self.char_id, 'plunder') if counter.remained_value <= 0: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.PLUNDER_NO_TIMES, self.char_id, "Plunder Battle", "Plunder no times. vip current: {0}, max: {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.PLUNDER_NO_TIMES_FINAL, self.char_id, "Plunder Battle", "Plunder no times. vip reach max level {0}".format(VIP_MAX_LEVEL) ) msg = MsgBattle() pvp = PVP(self.char_id, _id, msg) pvp.start() if not self.mongo_plunder.chars[str(_id)].is_robot: char = Char(self.char_id) h = Hang(_id) h.plundered(char.cacheobj.name, not msg.self_win) t = Task(self.char_id) t.trig(3) ground_win_times = 0 if msg.first_ground.self_win: ground_win_times += 1 if msg.second_ground.self_win: ground_win_times += 1 if msg.third_ground.self_win: ground_win_times += 1 got_point = PLUNDER_POINT.get(ground_win_times, 0) if got_point: self.mongo_plunder.points += got_point if msg.self_win: counter.incr() self.mongo_plunder.target_char = _id drop_official_exp = PLUNDER_GET_OFFICIAL_EXP_WHEN_WIN drop_gold = PLUNDER_DEFENSE_FAILURE_GOLD resource = Resource(self.char_id, "Plunder") resource.add(gold=drop_gold, official_exp=drop_official_exp) else: self.mongo_plunder.target_char = 0 self.mongo_plunder.got_reward = [] self.mongo_plunder.save() self.send_notify() return msg
def plunder(self): if not self.mongo_plunder.char_id: raise SanguoException( errormsg.PLUNDER_NO_RIVAL, self.char_id, "Plunder Battle", "no rival target" ) if self.mongo_plunder.current_times <= 0: raise SanguoException( errormsg.PLUNDER_NO_TIMES, self.char_id, "Plunder Battle", "no times" ) self.change_current_plunder_times(change_value=-1) msg = MsgBattle() pvp = PVPFromRivalCache( self.char_id, self.mongo_plunder.char_id, msg, self.mongo_plunder.char_name, self.mongo_plunder.char_formation ) pvp.start() t = Task(self.char_id) t.trig(3) to_char_id = self.mongo_plunder.char_id if msg.self_win: standard_drop = self._get_plunder_reward( self.mongo_plunder.char_city_id, self.mongo_plunder.char_gold, self.mongo_plunder.char_hero_original_ids ) self.clean_plunder_target() achievement = Achievement(self.char_id) achievement.trig(12, 1) else: standard_drop = make_standard_drop_from_template() self.mongo_plunder.save() self.send_notify() plunder_finished_signal.send( sender=None, from_char_id=self.char_id, to_char_id=to_char_id, from_win=msg.self_win, standard_drop=standard_drop ) return (msg, standard_drop)
def prisoner_get(self, _id, treasures): str_id = str(_id) if str_id not in self.p.prisoners: raise SanguoException( errormsg.PRISONER_NOT_EXIST, self.char_id, "Prisoner Get", "{0} not exist".format(_id) ) if not self.p.prisoners[str_id].active: raise SanguoException( errormsg.PRISONER_NOT_ACTIVE, self.char_id, "Prisoner Get", "{0} not active".format(_id) ) treasures_prob = 0 for tid in treasures: try: treasures_prob += TREASURES[tid].value except KeyError: raise SanguoException( errormsg.STUFF_NOT_EXIST, self.char_id, "Prisoner Get", "treasure {0} not exist".format(tid) ) def _get(): got = False prob = self.p.prisoners[str_id].prob + treasures_prob ae = ActivityEntry(self.char_id, 40008) if ae and ae.is_ok(): prob += 80 ae = ActivityEntry(self.char_id, 50005) if ae and ae.is_valid(): _vip = ae.get_current_value(self.char_id) if _vip == 4: prob += 30 elif _vip == 5: prob += 50 elif _vip == 6: prob += 60 elif _vip >= 7: prob += 100 if prob >= random.randint(1, 100): # got it save_hero(self.char_id, self.p.prisoners[str_id].oid) got = True self.p.prisoners.pop(str_id) msg = protomsg.RemovePrisonerNotify() msg.ids.append(_id) publish_to_char(self.char_id, pack_msg(msg)) else: self.p.prisoners[str_id].active = False msg = protomsg.UpdatePrisonerNotify() p = msg.prisoner.add() p_obj = self.p.prisoners[str_id] self._fill_up_prisoner_msg(p, _id, p_obj.oid, p_obj.prob, p_obj.active) publish_to_char(self.char_id, pack_msg(msg)) self.p.save() return got using_stuffs = [(tid, 1) for tid in treasures] if using_stuffs: resource = Resource(self.char_id, "Prisoner Get") with resource.check(stuffs=using_stuffs): got = _get() else: got = _get() t = Task(self.char_id) t.trig(5) if got: achievement = Achievement(self.char_id) achievement.trig(14, 1) TimesLogPrisonGetSuccess(self.char_id).inc() return got
def battle(self): need_sycee = 0 counter = Counter(self.char_id, 'arena') if counter.remained_value <= 0: counter = Counter(self.char_id, 'arena_buy') if counter.remained_value <= 0: char = Char(self.char_id).mc if char.vip < VIP_MAX_LEVEL: raise SanguoException( errormsg.ARENA_NO_TIMES, self.char_id, "Arena Battle", "arena no times. vip current: {0}, max {1}".format(char.vip, VIP_MAX_LEVEL) ) raise SanguoException( errormsg.ARENA_NO_TIMES_FINAL, self.char_id, "Arena Battle", "arena no times. vip reach max level {0}".format(VIP_MAX_LEVEL) ) else: need_sycee = ARENA_COST_SYCEE rival_id = self.choose_rival() if not rival_id: raise SanguoException( errormsg.ARENA_NO_RIVAL, self.char_id, "Arena Battle", "no rival." ) if need_sycee: resource = Resource(self.char_id, "Arena Battle", "battle for no free times") resource.check_and_remove(sycee=-need_sycee) counter.incr() # set battle cd redis_client.setex(REDIS_ARENA_BATTLE_CD_KEY(rival_id), 1, ARENA_CD) msg = protomsg.Battle() b = PVP(self.char_id, rival_id, msg) b.start() if msg.self_win: achievement = Achievement(self.char_id) achievement.trig(11, 1) self_score = self.score rival_arena = Arena(rival_id) rival_score = rival_arena.score new_score = calculate_score(self_score, rival_score, msg.self_win) self.set_score(new_score) t = Task(self.char_id) t.trig(2) self.send_notify(score=new_score) rival_arena.be_beaten(rival_score, self_score, not msg.self_win, self.char_id) return msg
def prisoner_get(self, _id, treasures): str_id = str(_id) if str_id not in self.p.prisoners: raise SanguoException( errormsg.PRISONER_NOT_EXIST, self.char_id, "Prisoner Get", "{0} not exist".format(_id) ) if not self.p.prisoners[str_id].active: raise SanguoException( errormsg.PRISONER_NOT_ACTIVE, self.char_id, "Prisoner Get", "{0} not active".format(_id) ) treasures_prob = 0 for tid in treasures: try: treasures_prob += TREASURES[tid].value except KeyError: raise SanguoException( errormsg.STUFF_NOT_EXIST, self.char_id, "Prisoner Get", "treasure {0} not exist".format(tid) ) using_stuffs = [(tid, 1) for tid in treasures] resource = Resource(self.char_id, "Prisoner Get") with resource.check(stuffs=using_stuffs): got = False prob = self.p.prisoners[str_id].prob + treasures_prob char = Char(self.char_id).mc vip_plus = VIP_FUNCTION[char.vip].prisoner_get prob += vip_plus if prob >= random.randint(1, 100): # got it save_hero(self.char_id, self.p.prisoners[str_id].oid) got = True self.p.prisoners.pop(str_id) msg = protomsg.RemovePrisonerNotify() msg.ids.append(_id) publish_to_char(self.char_id, pack_msg(msg)) else: self.p.prisoners[str_id].active = False msg = protomsg.UpdatePrisonerNotify() p = msg.prisoner.add() p_obj = self.p.prisoners[str_id] self._fill_up_prisoner_msg(p, _id, p_obj.oid, p_obj.prob, p_obj.active) publish_to_char(self.char_id, pack_msg(msg)) self.p.save() t = Task(self.char_id) t.trig(5) return got