def get(self): res = Result() names = {} sex = self.get_argument("sex") if sex == "0": # male for i in range(8): # 一次返回8个名字 index = random.randint(0, len(self.application.maleNames) - 1) while index in names.keys(): index = random.randint(0, len(self.application.maleNames) - 1) names[index] = self.application.maleNames[index] elif sex == "1": # female for i in range(8): # 一次返回8个名字 index = random.randint(0, len(self.application.femaleNames) - 1) while index in names.keys(): index = random.randint( 0, len(self.application.femaleNames) - 1) names[index] = self.application.femaleNames[index] res.setData(names) self.write(res.getRes())
def decrypt(self, from_path, to_path, encryption_data): if encryption_data["algorithm"] == SecurityAlgorithm.none: shutil.copyfile(from_path, to_path) return Result.success(True) cipher = self.get_cipher(encryption_data) if not cipher.is_ok(): return cipher cipher = cipher.result() decryptor = cipher.decryptor() block_size = cipher.algorithm.block_size padder = padding.PKCS7(block_size).unpadder() with open(from_path, "rb") as file: data = file.read() crypted = decryptor.update(data) padded_data = padder.update(crypted) padded_data += padder.finalize() with open(to_path, "wb") as file: file.write(padded_data) return Result.success(True)
def response(self): res = Result() data = dict() data["sender"] = self.sender data["type"] = self.type data["content"] = self.content data["time"] = self.time res.setData(data) return res.getRes()
def set_media_folder(self, path): logger.info("set media folder %s" % path) if not self.disk.exists(path): return Result.failed("Media path '%s' doesn't exists" % path) if not self.disk.is_dir(path): return Result.failed("Media path '%s' isn't directory" % path) self.media_folder = path return Result.success()
def create_room(context): print('create room entered') new_room = Room(id=context.room_id, host=context.user) success = context.room_manager.add_room(new_room) if success == Room_Status.CREATE_SUCCESS: print("Create Room Success") return Result.DEFAULT_SUCCESS() else: print("Create Room Failure, Code:" + str(success)) return Result.DEFAULT_FAILURE()
def leave_room(context): requested_room_id = context.args[0] interested_room = context.room_manager.get_room(requested_room_id) if interested_room != None: result = interested_room.remove_member(context.user) if result == Room_Status.LEAVE_SUCCESS: return Result.DEFAULT_SUCCESS() else: return Result.DEFAULT_FAILURE() else: Result.DEFAULT_FAILURE()
def get_listdir(self, url): if self.check_url(url): if self.disk.is_public_dir(url): listdir = list(self.disk.public_listdir(url)) listdir.sort(key=lambda x: x.type == "dir", reverse=True) names = [self.header, ] for i in listdir: names.append(self.get_info(i)) return Result.success((names, url)) else: return Result.failed("Url isn't public") return Result.failed("Url doesnt't exist")
def check_media(self, crypto_data): key_type = crypto_data["key_type"] media_path = crypto_data["media_path"] take_file_from_yadisk = crypto_data["take_file_from_yadisk"] if key_type in (KeyType.new_media, KeyType.existing_media): if take_file_from_yadisk: result = self.yadisk_model.download_media( media_path, self.temp_dir.name) #result = self.yadisk_model.download_media(media_path, "D:/yanileda/trash") return result else: return Result.success(media_path) else: return Result.success(media_path)
def __init__(self): """ 游戏初始化 """ pygame.init() self.screen = pygame.display.set_mode(WIN_SIZE) pygame.display.set_caption("飞机大战") self.img_bg = pygame.image.load(IMG_BG) self.hero = Hero(self.screen) self.enemies = self.get_enemies(5) self.result = Result() self.btn_enter = [Button(BTN_ENTER1), Button(BTN_ENTER2)] self.font = pygame.font.Font(FONT, 45)
def check_url(self, url): logger.info("check url " + url) try: result = self.disk.public_exists(url) except NotFoundError: result = False return Result.success(result)
def join_room(context): print('join room entered') requested_room_id = context.room_id interested_room = context.room_manager.get_room(requested_room_id) if interested_room != None: result = interested_room.add_member(context.user) if result == Room_Status.JOIN_SUCCESS: return Result.DEFAULT_SUCCESS() elif result == Room_Status.JOIN_FAILURE_NAME_TAKEN: return Result(Status.FAILURE, "Name already taken") else: return Result.DEFAULT_FAILURE() else: print("Join Room Failure, Code: " + str(Room_Status.JOIN_FAILURE_INVALID_ROOM)) return Result(Status.FAILURE, "Room not found")
def get_listdir(self, path=None): logger.info("Open path %s" % path) if path is None: path = magic_const.YADISK_PREFIX if not self.disk.is_dir(path): return Result.failed("Path doesn't exist") names = [ self.header, ] listdir = list(self.disk.listdir(path)) listdir.sort(key=lambda x: x.type == "dir", reverse=True) for i in listdir: names.append(self.get_info(i)) return Result.success((names, path))
def set_verification_code(self, code): logger.info("Checking ver.code %s" % code) # time.sleep(5) try: response = self.disk.get_token(code) except yadisk.exceptions.BadRequestError: return Result.success(False) self.disk.token = response.access_token result = self.disk.check_token() if result: logger.info("Connected to Yadisk") else: logger.error("Cannot connect to Yadisk") return Result.success(result)
def download_media(self, media_name, dir_name): # check media media_path = Path(self.media_folder) / media_name logger.info("Check path %s" % media_path.as_posix()) if not self.disk.exists(media_path.as_posix()): return Result.failed("Media path isn't found") temp_path = Path(dir_name) / media_name download_result = self.download(media_path.as_posix(), temp_path.as_posix()) if download_result.is_ok(): if download_result.result(): return Result.success(temp_path.as_posix()) else: return Result.failed("Something has gone wrong") else: return download_result
def set_batch(self, idx): """ Loads a batch of data of a specific data type and then stores it for later retrieval. Pads ragged track and PFO arrays to make them rectilinear and reshapes arrays into correct shape for training. The clip option in ak.pad_none will truncate/extend each array so that they are all of a specific length- here we limit nested arrays to 20 items :param idx: The index of the batch to be processed """ batch, sig_bkg_labels_np_array = self.next_batch() track_np_arrays = self.pad_and_reshape_nested_arrays(batch, "TauTracks", max_items=20) conv_track_np_arrays = self.pad_and_reshape_nested_arrays(batch, "ConvTrack", max_items=20) shot_pfo_np_arrays = self.pad_and_reshape_nested_arrays(batch, "ShotPFO", max_items=20) neutral_pfo_np_arrays = self.pad_and_reshape_nested_arrays( batch, "NeutralPFO", max_items=20) jet_np_arrays = self.reshape_arrays(batch, "TauJets") # Compute labels labels_np_array = np.zeros((len(sig_bkg_labels_np_array), 4)) if sig_bkg_labels_np_array[0] == 0: labels_np_array[:, 0] = 1 else: truth_decay_mode_np_array = ak.to_numpy( batch[self._variables_dict["DecayMode"]]).astype(np.int64) labels_np_array = labeler(truth_decay_mode_np_array, labels_np_array) # Apply pT re-weighting weight_np_array = np.ones(len(labels_np_array)) if self.class_label == 0: weight_np_array = pt_reweight( ak.to_numpy( batch[self._variables_dict["Weight"]]).astype("float32")) result = Result(track_np_arrays, neutral_pfo_np_arrays, shot_pfo_np_arrays, conv_track_np_arrays, jet_np_arrays, labels_np_array, weight_np_array) # logger.log(f"Tracks Max = {np.amax(result.tracks)}") # logger.log(f"NeutralPFOs Max = {np.amax(result.neutral_PFOs)}") # logger.log(f"ShotPFOs Max = {np.amax(result.shot_PFOs)}") # logger.log(f"ConvTracks Max = {np.amax(result.conv_tracks)}") # logger.log(f"Jets Max = {np.amax(result.jets)}") return result
def get_lag(self, parser): partitions = self.consumer.assignment() partition_messages = self._get_messages_per_partition(partitions) lags = {} positions = self.consumer.position(partitions) if len(positions) == 0: return Result.Fail( LagCalculatorException( f"No offsets found for topics {self.topics}")) for pos in positions: if pos.offset == -1001: lags[f"part_{pos.partition}"] = 0 else: lags[f"part_{pos.partition}"] = ( partition_messages[f"part_{pos.partition}"] - pos.offset + 1) return parser.to_report(lags)
def get(self): id = self.get_argument("id") res = Result() if id in chattingList.keys(): if id == chattingList[id].person1.id: self.write( json.dumps({ 'other': chattingList[id].person2.name, 'mine': chattingList[id].person1.name, 'status': 1 })) elif id == chattingList[id].person2.id: self.write( json.dumps({ 'other': chattingList[id].person1.name, 'mine': chattingList[id].person2.name, 'status': 1 }))
def get_cipher(self, crypto_data): #assert len(encryption_data) == 4 algorithm_type = crypto_data["algorithm"] key_type = crypto_data["key_type"] media_path = crypto_data["media_path"] key = crypto_data["key"] media_type = crypto_data["media_type"] # get key from media if need it key = self.get_key(algorithm_type, key_type, key, media_path, media_type) if not key.is_ok(): return key else: key = key.result() algorithm = self.get_algorithm(algorithm_type, key) cipher = Cipher(algorithm, mode=modes.ECB(), backend=default_backend()) # print(cipher.algorithm.block_size) # print(cipher.block_size) return Result.success(cipher)
def upload(self, from_path, to_path): logger.info("upload {} to {}".format(from_path, to_path)) self.disk.upload(from_path, to_path, overwrite=True) return Result.success()
def download(self, from_path, to_path): logger.info("download {} to {}".format(from_path, to_path)) self.disk.download(from_path, to_path) return Result.success()
from fabric.api import env from fabric.api import execute from fabric.api import prefix from fabric.api import run from fabric.api import runs_once from fabric.api import task from fabric.contrib.files import exists from utils import Jenkins, Result state.output['running'] = False state.output['stderr'] = False state.output['warnings'] = False env.result = Result() env.warn_only = True # Virtualenv support @_contextmanager def venv(): venv_path = "/home/jenkins/venv-nailgun-tests/" with cd(venv_path): with prefix("source " + venv_path + "bin/activate"): yield @_contextmanager def venv29():
def download(self, from_path, to_path): if self.check_url(from_path): self.disk.download_public(from_path, to_path) return Result.success()
def get_meta(self, url): logger.info("get meta " + url) info = self.disk.get_public_meta(url) return Result.success(([self.header, (info.type, info.name, info.public_url, info.created.strftime(magic_const.DATETIME_FORMAT))], url))
def main(): np.seterr(all='raise') # always raise error, no runtime warnings parser = argparse.ArgumentParser( description= 'Ejecuta los experimentos de la primera práctica de Metaheurísticas') parser.add_argument('-i, --interactive', action='store_true', dest='interactive') parser.add_argument('-o, --output', dest='output_filename', default=None) args = parser.parse_args() databases = ['sonar', 'spambase', 'wdbc'] algorithms = [ ReliefAlgorithm, LocalSearchAlgorithm, BLXEGeneticAlgorithm, MemeticAlgorithmC, SimulatedAnnealingAlgorithm, IteratedLocalSearchAlgorithm, DifferentialEvolutionRandomAlgorithm, DifferentialEvolutionCTBAlgorithm ] results = {} for alg in algorithms: collector = ResultsCollector() if args.interactive: print('{emph} {alg} {emph}'.format(emph='=' * 20, alg=alg.__name__)) for db in databases: np.random.seed(0) # reset NumPy PRNG seed dataset = ArffReader.read(db) partitions = dataset.kfoldcv(K=5) if args.interactive: print('{emph} {db} {emph}'.format(emph='*' * 10, db=db)) for i, partition in enumerate(partitions): name = '{db} - {i}'.format(db=db, i=i) res = Result(name=name) res.indices = { name: array.tolist() # cast np arrays to normal lists (JSON) for name, array in partition.indices.iteritems() } res.start_timer() learner = alg(partition.training_set) learner.train() res.end_timer() # calculate errors and scores res.train_score = learner.classifier.evaluate_solution( learner.solution) res.train_error = learner.solution.error res.test_error = learner.classifier.test_error( test_dataset=partition.testing_set, w=learner.solution.w) res.test_score = np.mean( [1 - res.test_error, learner.solution.redux]) # set up Result res.solution = learner.solution.w.tolist( ) # cast np array to list if args.interactive: print(res) collector.append_result(res) results[alg.__name__] = collector # transform to something JSON can work with results = { alg: collector.serialize() for alg, collector in results.iteritems() } if args.output_filename is None: print json.dumps(results) else: f = open(args.output_filename, 'wb') f.write(json.dumps(results)) f.close()
def get_key(self, algorithm_type, key_type, key, media_path, media_type): logger.info("Key-file path %s" % media_path) if key_type == KeyType.new_symbols: if not key: return Result.failed("Why have you deleted the key?") return Result.success(key) elif key_type == KeyType.existing_symbols: if not key: return Result.failed("Write down password") return Result.success(key) elif key_type == KeyType.new_binary: if not media_path: return Result.failed("Select file for key") key = self.generate_key(algorithm_type) with open(media_path, "wb") as f: f.write(key) return Result.success(key) elif key_type == KeyType.existing_binary: if not media_path: return Result.failed("Select file with key") with open(media_path, "rb") as f: key = f.read() return Result.success(key) elif key_type == KeyType.new_media: if not key: return Result.failed("Write down password") if not media_path: return Result.failed("Select media file") if media_type == MediaType.f5steganography: key_key = self.generate_key(algorithm_type) embed_into_image(media_path, key_key.decode("utf-8"), key) elif media_type == MediaType.fractals: key_size = magic_const.KEY_LENGTH[algorithm_type] key_key = fractals.generate_key(media_path, key.decode("utf-8"), key_size) elif media_type == MediaType.dct: key_size = magic_const.KEY_LENGTH[algorithm_type] key_key = dct_algorithm.generate_key(media_path, key.decode("utf-8"), key_size) else: logger.error("Bad media type %s" % media_type) return Result.success(key_key) elif key_type == KeyType.existing_media: if not key: return Result.failed("Write down password") if not media_path: return Result.failed("Select media file") if media_type == MediaType.f5steganography: key_key = extract_from_image(media_path, key.decode("utf-8")) key_key = key_key.encode("utf-8") logger.info("Key len %d" % len(key_key)) elif media_type == MediaType.fractals: key_size = magic_const.KEY_LENGTH[algorithm_type] key_key = fractals.generate_key(media_path, key.decode("utf-8"), key_size) elif media_type == MediaType.dct: key_size = magic_const.KEY_LENGTH[algorithm_type] key_key = dct_algorithm.generate_key(media_path, key.decode("utf-8"), key_size) else: logger.error("Bad media type %s" % media_type) return Result.success(key_key)
class Game: """ 游戏运行主类 """ # 状态变量 READY = 0 START = 1 OVER = -1 status = READY btn_start_index = 0 frame = 0 clock = pygame.time.Clock() def __init__(self): """ 游戏初始化 """ pygame.init() self.screen = pygame.display.set_mode(WIN_SIZE) pygame.display.set_caption("飞机大战") self.img_bg = pygame.image.load(IMG_BG) self.hero = Hero(self.screen) self.enemies = self.get_enemies(5) self.result = Result() self.btn_enter = [Button(BTN_ENTER1), Button(BTN_ENTER2)] self.font = pygame.font.Font(FONT, 45) def get_enemies(self, num): """ 获取敌人精灵组 :return: 敌人精灵组 """ Enemies = pygame.sprite.Group() for i in range(num): enemy = Enemy(self.screen) Enemies.add(enemy) return Enemies def event_listen(self): """ 事件监听 """ for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if self.status == self.START and event.key == pygame.K_SPACE: self.hero.shoot() if self.status == self.OVER and event.key == pygame.K_SPACE: self.status = self.READY if event.type == pygame.MOUSEBUTTONDOWN: mouse = pygame.mouse.get_pos() if self.status == self.READY and self.btn_enter[0].judge_mouse( mouse): self.btn_start_index = 1 self.status = self.START if event.type == pygame.MOUSEMOTION: mouse = pygame.mouse.get_pos() if self.status == self.READY and self.btn_enter[0].judge_mouse( mouse): self.btn_start_index = 1 else: self.btn_start_index = 0 keys = pygame.key.get_pressed() if keys[pygame.K_a]: self.hero.move("left") if keys[pygame.K_d]: self.hero.move("right") if keys[pygame.K_w]: self.hero.move("top") if keys[pygame.K_s]: self.hero.move("down") def run_game(self): """ 游戏主循环 """ while True: self.clock.tick(40) self.frame += 1 if self.frame >= 200: self.frame = 0 enemy = Enemy(self.screen) self.enemies.add(enemy) self.event_listen() if self.status == self.READY: self.screen.blit(self.img_bg, self.img_bg.get_rect()) self.screen.blit(self.btn_enter[self.btn_start_index].image, self.btn_enter[0].rect) max_score_text = self.font.render( 'Max scores:{0}'.format(self.result.get_max_score()), True, RED) self.screen.blit(max_score_text, [0, 0]) elif self.status == self.START: self.screen.blit(self.img_bg, self.img_bg.get_rect()) score_text = self.font.render( 'Scores:{0}'.format(self.result.score), True, RED) blood_text = self.font.render( 'Blood:{}'.format(self.result.blood), True, RED) self.screen.blit(score_text, [0, 5]) self.screen.blit(blood_text, [0, 45]) self.hero.update() self.hero.bullets.update(self.enemies, self.result) self.enemies.update(self.result) if pygame.sprite.spritecollide( self.hero, self.enemies, False) or self.result.blood <= 0: self.enemies.empty() self.hero.broken() self.result.set_max_score() self.status = self.OVER elif self.status == self.OVER: self.screen.blit(self.img_bg, self.img_bg.get_rect()) score_text = self.font.render( 'Scores:{0}'.format(self.result.score), True, RED) max_score_text = self.font.render( 'Max scores:{0}'.format(self.result.get_max_score()), True, RED) tip_text = self.font.render('Press the Space to continue!', True, RED) self.screen.blit(score_text, (WIN_SIZE[0] / 2 - 70, WIN_SIZE[1] / 2 - 40)) self.screen.blit(max_score_text, (WIN_SIZE[0] / 2 - 100, WIN_SIZE[1] / 2 - 90)) self.screen.blit( tip_text, (WIN_SIZE[0] / 2 - 200, WIN_SIZE[1] / 2 - 135)) # 刷新屏幕 pygame.display.update()