def test_get_metadata(self): impl = self.mox.CreateMock(SessionImpl_1_7_2) impl.get_metadata().AndReturn('some response') sut = Session(impl) self.mox.ReplayAll() self.assertEqual(sut.get_metadata(), 'some response')
def test_exit_logged_in(self): impl = self.mox.CreateMock(SessionImpl_1_7_2) sut = Session(impl) impl.is_logged_in = True impl.logout() self.mox.ReplayAll() sut.__exit__(None, None, None)
def test_add_children(self): ref = Group() child1 = Session() child2 = Session() ref.add_child(child1) ref.add_child(child2) self.assertEqual([child1, child2], ref.children)
def execute(self, session: Session, args: Dict[str, Any]) -> ExitCode: lookup = args.get('data') if lookup is None: session.get_io().error('The common data store has not been initialized yet!') return ExitCode.FAILURE elif len(lookup) == 0: session.get_io().error('The common data store does not have any elements in it!') return ExitCode.FAILURE else: return self.command.execute(self=self.command, session=session, args=args)
def start_game(self, board_name): Log.debug('Starting game') #### TEMP #### board_path = self.CORE.board_dir + board_name + self.CORE.board_suff self.session = Session(self) board = Board(self.session, board_path) self.session.set_board(board) self.player = Player('Local', 'temp_pwd') self.session.add_player(self.player) ################ self.starting_game = True
def test_load_config(self): # Crash if session has no name in config ref = Session() ref.load_configuration({'path': 'test_path', 'anatomy_path': 'test_anatomy_path', 'name': 'test_name', 'description': 'test_desc', 'plot_settings': 'test_settings'}) self.assertEqual(ref.name, 'test_name') self.assertEqual(ref.description, 'test_desc') self.assertEqual(ref.plot_settings, 'test_settings')
def test_load_config(self): # Crash if session has no name in config ref = Session() ref.load_configuration({ 'path': 'test_path', 'anatomy_path': 'test_anatomy_path', 'name': 'test_name', 'description': 'test_desc', 'plot_settings': 'test_settings' }) self.assertEqual(ref.name, 'test_name') self.assertEqual(ref.description, 'test_desc') self.assertEqual(ref.plot_settings, 'test_settings')
def test_login(self): mock_impl = self.mox.CreateMockAnything('RETS Imlementation') mock_impl.login('some login uri', 'some username', 'some password').AndReturn('some result') sut = Session.create(implementation=mock_impl) self.mox.ReplayAll() result = sut.login('some login uri', 'some username', 'some password') self.assertEqual(result, 'some result')
class SessionTest(unittest.TestCase): def setUp(self): self.scaling_ghi = preprocessing.min_max_scaling_ghi() self.session = Session(mock.Mock()) def test_shi_rmse(self): predicted = tf.constant([950.0]) target = tf.constant([850.0]) expected = self.session.loss_fn(predicted, target).numpy() rescaled_predicted = self.session.scaling_ghi.normalize(predicted) rescaled_target = self.session.scaling_ghi.normalize(target) loss = self.session.loss_fn(rescaled_predicted, rescaled_target) actual = self.session._rescale_loss_ghi(loss).numpy() self.assertAlmostEqual(expected, actual, delta=1e-5)
def test_get_configuration(self): ref = Session() ref.load_sequence('src/tests/test-data/brain.nii') ref.load_anatomy('src/tests/test-data/mask.nii') ref.load_stimuli('src/tests/test-data/stimuli.mat', 0.5) expected = {'path': 'src/tests/test-data/brain.nii', 'stimuli': {'path': 'src/tests/test-data/stimuli.mat', 'tr': 0.5}, 'anatomy_path': 'src/tests/test-data/mask.nii'} self.assertEqual(ref.get_configuration(), expected)
def test_get_configuration(self): ref = Session() ref.load_sequence('src/tests/test-data/brain.nii') ref.load_anatomy('src/tests/test-data/mask.nii') ref.load_stimuli('src/tests/test-data/stimuli.mat', 0.5) expected = { 'path': 'src/tests/test-data/brain.nii', 'stimuli': { 'path': 'src/tests/test-data/stimuli.mat', 'tr': 0.5 }, 'anatomy_path': 'src/tests/test-data/mask.nii' } self.assertEqual(ref.get_configuration(), expected)
def run(args): """Run the model with RMSE Loss. It can train or test with different datasets. """ env.run_local = args.run_local if not args.random_seed: random.seed(args.seed) tf.random.set_seed(args.seed) if args.dry_run: dry_run.run(args.enable_tf_caching, args.skip_non_cached) model = create_model(args.model) session = Session( model=model, batch_size=args.batch_size, skip_non_cached=args.skip_non_cached, ) if args.train: optimizer = optimizers.Adam(args.lr) session.train( optimizer=optimizer, cache_file=args.cache_file, enable_checkpoint=not args.no_checkpoint, epochs=args.epochs, checkpoint=args.checkpoint, ) if args.test is not None: session.test(args.test)
async def get_binary_details(region: str, model: str, firmware: str): """ Gets the binary details such as filename and decrypt key.\n `firmware` is the firmware code of the device that you got from `/latest` endpoint.\n\n `decrypt_key` is used for decrypting the file after downloading. It presents a hex string. Pass it to `/download` endpoint. """ # Create new session. key = Session.from_response( requests.post(Constants.NONCE_URL, headers=Constants.HEADERS())) # Make the request. req = requests.post(url=Constants.BINARY_INFO_URL, data=Constants.BINARY_INFO(firmware, region, model, key.logic_check(firmware)), headers=Constants.HEADERS(key.encrypted_nonce, key.auth), cookies=Constants.COOKIES(key.session_id)) # Read the request. if req.status_code == 200: data = KiesData(req.text) # Return error when binary couldn't be found. if data.status_code != "200": raise HTTPException(400, "Firmware couldn't be found.") # If file extension ends with .enc4 that means it is using version 4 encryption, otherwise 2 (.enc2). ENCRYPT_VERSION = 4 if str( data.body["BINARY_NAME"]).endswith("4") else 2 # Get binary details return { "display_name": data.body["DEVICE_MODEL_DISPLAYNAME"], "size": int(data.body["BINARY_BYTE_SIZE"]), "filename": data.body["BINARY_NAME"], "path": data.body["MODEL_PATH"], "version": data.body["CURRENT_OS_VERSION"].replace("(", " ("), "encrypt_version": ENCRYPT_VERSION, # Convert bytes to GB, so it will be more readable for an end-user. "size_readable": "{:.2f} GB".format(float(data.body["BINARY_BYTE_SIZE"]) / 1024 / 1024 / 1024), # Generate decrypted key for decrypting the file after downloading. # Decrypt key gives a list of bytes, but as it is not possible to send as query parameter, # we are converting it to a single HEX value. "decrypt_key": \ key.getv2key(firmware, model, region).hex() if ENCRYPT_VERSION == 2 else \ key.getv4key(data.body["LATEST_FW_VERSION"], data.body["LOGIC_VALUE_FACTORY"]).hex(), # A URL of samsungmobile that includes release changelogs. # Not available for every device. "firmware_changelog_url": data.body["DESCRIPTION"], "platform": data.body["DEVICE_PLATFORM"] } # Raise HTTPException when status is not 200. raise HTTPException( 500, "Something went wrong when sending request to Kies servers.")
def get_integer_from_user(session: Session, message: str, max_attempts: int = 0, retry_delay: int = 1) -> int: attempt_count = 0 while attempt_count <= max_attempts: session.get_io().output(message, end='') user_input = session.get_io().input() try: return int(user_input) except ValueError: session.get_io().error('Your input must be an integer, instead got "{}"'.format(user_input)) time.sleep(retry_delay) session.clear() if max_attempts > 0: attempt_count += 1 if attempt_count > max_attempts: raise InputAttemptTimeoutException('Exceeded maximum number of input attempts', max_attempts)
def test_settings_changed(self): ref = Session() self.assertFalse(ref.settings_changed(False, False, None, None)) self.assertTrue(ref.settings_changed(True, False, None, None))
def execute(self, session: Session, args: Dict[str, Any]) -> ExitCode: session.get_io().output('Exiting program...') exit() return ExitCode.SUCCESS
def test_load_anatomy(self, mock_brain): ref = Session() ref.load_sequence('src/tests/test-data/brain.nii') mock_brain.assert_called_once_with('src/tests/test-data/brain.nii')
def test_session(self, mock_load): Session('test.json') mock_load.assert_called_once_with('test.json')
def setUp(self): self.scaling_ghi = preprocessing.min_max_scaling_ghi() self.session = Session(mock.Mock())
def test_create_bad_version(self): with self.assertRaises(RETSQueryException) as mgr: Session.create('blah') self.assertEqual(mgr.exception.message, "'blah' is an invalid or unsupported RETS version number.\nValid versions: 1.7.2")
def test_create_1_7_2(self): sut = Session.create('1.7.2') self.assertIsInstance(sut._Session__impl, SessionImpl_1_7_2)
import time, hashlib, hmac from flask import current_app from src.session import Session COINBASE_SESSION = Session() class Client: def __init__(self): pass def _request(self, method, url, data=None, extra_headers=None, **kwargs): headers = { 'Accept': 'application/json', 'CB-ACCESS_KEY': current_app.config['API_KEY'], 'CB-ACCESS-SIGN': self.generate_cb_access_sign(method, url, data), 'CB-ACCESS-TIMESTAMP': str(int(time.time())) } if extra_headers: headers.update(extra_headers) return COINBASE_SESSION.request(method, url, **kwargs) def get(self, url, data=None, headers=None, **kwargs): return self._request('get', url, data, headers, **kwargs) def generate_cb_access_sign(self, method, url, data=''): message = f'{str(int(time.time()))}{method.upper()}{url}{data}' signature = hmac.new(current_app.config['SECRET_KEY'].encode('utf-8'), message.encode('utf-8'),
def add_session(self, name, detail, convener, attendee_capacity): session = Session(name, detail, convener, attendee_capacity) self._sessionList.append(session)
async def download_binary(filename: str, path: str, decrypt_key: str, request: Request): """ Downloads the firmware and decrypts the file during download automatically.\n **Do not try the endpoint in the interactive API docs, because as it returns a file, it doesn't work in OpenAPI.** """ # Create new session. key = Session.from_response( requests.post(Constants.NONCE_URL, headers=Constants.HEADERS())) # Make the request. req = requests.post(url=Constants.BINARY_FILE_URL, data=Constants.BINARY_FILE( filename, key.logic_check(filename.split(".")[0][-16:])), headers=Constants.HEADERS(key.encrypted_nonce, key.auth), cookies=Constants.COOKIES(key.session_id)) # Refresh session. key.refresh_session(req) # Read the request. if req.status_code == 200: data = KiesData(req.text) # Return error when binary couldn't be found. if data.status_code != "200": raise HTTPException( int(data.status_code), f"The service returned {data.status_code}. Maybe parameters are invalid?" ) # Else, make another request to get the binary. else: # Check and parse the range header. START_RANGE, END_RANGE = ( 0, 0 ) if "Range" not in request.headers else Constants.parse_range_header( request.headers["Range"]) # Check if range is invalid. if START_RANGE == -1 or END_RANGE == -1: raise HTTPException( 416, "Range is invalid. If you didn't meant input a 'Range' header, remove it from request." ) # Create headers. _headers = Constants.HEADERS(key.encrypted_nonce, key.auth) # If incoming request contains a Range header, directly pass it to request. if "Range" in _headers: _headers["Range"] = "bytes=" + Constants.make_range_header( START_RANGE, END_RANGE) # Another request for streaming the firmware. req2 = requests.get(url=Constants.BINARY_DOWNLOAD_URL, params="file=" + path + filename, headers=_headers, cookies=Constants.COOKIES(key.session_id), stream=True) # Check if status code is not 200 or 206. if req2.status_code not in [200, 206]: # Raise HTTPException when status is not success. raise HTTPException( req2.status_code, f"The service returned {req2.status_code}. Maybe parameters are invalid?" ) # Get the total size of binary. CONTENT_LENGTH = int(req2.headers["Content-Length"]) # Decrypt bytes while downloading the file. # So this way, we can directly serve the bytes to the client without downloading to the disk. return StreamingResponse( Decryptor(req2, bytes.fromhex(decrypt_key)), media_type="application/zip", headers={ "Content-Disposition": "attachment;filename=" + filename.replace(".enc4", "").replace(".enc2", ""), "Content-Length": str(CONTENT_LENGTH), "Accept-Ranges": "bytes", "Content-Range": f"bytes {Constants.make_range_header(START_RANGE, END_RANGE)}" }, status_code=200 if not START_RANGE else 206) # Raise HTTPException when status is not 200. raise HTTPException( 500, "Something went wrong when sending request to Kies servers.")
class Launcher: def __init__(self, is_debug=False): Log.info('Starting launcher') self.leaving = False self.debug = is_debug self.starting_game = False self.load_config() self.ui_init() self.ui_tk_make_styles() self.ui_tk_make_sframe() self.ui_tk_make_views() self.ui_show_view('app_title') def loop(self): self.root.update() def start_game(self, board_name): Log.debug('Starting game') #### TEMP #### board_path = self.CORE.board_dir + board_name + self.CORE.board_suff self.session = Session(self) board = Board(self.session, board_path) self.session.set_board(board) self.player = Player('Local', 'temp_pwd') self.session.add_player(self.player) ################ self.starting_game = True def load_config(self): '''Loads configuration files''' Log.debug('Loading config files') self.CORE = internal.to_ns(yaml.load(open('cnf/core.yml', 'r'))) self.TEXT = internal.to_ns(yaml.load(open('cnf/text.yml', 'r'))) self.CLRS = internal.to_ns(yaml.load(open('cnf/clrs.yml', 'r'))) self.GAME = internal.to_ns(yaml.load(open('cnf/game.yml', 'r'))) self.LNCH = internal.to_ns(yaml.load(open('cnf/lnch.yml', 'r'))) self.USER = internal.to_ns(yaml.load(open('cnf/user.yml', 'r'))) self.KBDS = internal.to_ns(yaml.load(open('cnf/kbds.yml', 'r'))) def ui_init(self): '''Initializes tkinter UI''' Log.debug('Initializing UI') self.root = tk.Tk() self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.root.title(self.TEXT.window_title) self.root.iconbitmap(self.CORE.icon_path) w, h = self.LNCH.window_size self.root.geometry('{}x{}'.format(w, h)) self.widgets = {} self.root.protocol('WM_DELETE_WINDOW', self.quit) def ui_get_font(self, key): '''Returns font configuration tuple''' Log.debug('Requested font "{}"'.format(key)) font_family = self.CORE.font_family height, is_bold = self.CORE.fonts[key] if is_bold: return (font_family, height, 'bold') else: return (font_family, height) def ui_get_version_text(self): '''Returns version text based on config''' return self.CORE.version_smb + ' | ' + self.CORE.version_txt @staticmethod def ui_rowcol_config(element, col_weights=[1], row_weights=[]): '''Configures rows and columns weights of element''' for col, weight in enumerate(col_weights): element.columnconfigure(col, weight=weight) for row, weight in enumerate(row_weights): element.rowconfigure(row, weight=weight) @staticmethod def ui_get_grid(col, row, cspan=1, rspan=1, sticky=None, padding=2): '''Returns keyword args dictionary for grid method of tk widgets''' if sticky is None: sticky = ALL result = { 'column': col, 'row': row, 'columnspan': cspan, 'rowspan': rspan, 'sticky': sticky } if padding == 2: paddings = {'padx': 30, 'pady': 10, 'ipadx': 20, 'ipady': 10} elif padding == 1: paddings = {'padx': 5, 'pady': 5, 'ipadx': 5, 'ipady': 5} else: paddings = {} result.update(paddings) return result ################################ # Menu pages and related def ui_tk_make_styles(self): '''Creates TTK styles ''' Log.debug('Creating TTK styles') newstyle = ttk.Style() for k, v in self.LNCH.styles.items(): Log.debug('Creating style: {}'.format(k)) if len(v) == 3: newstyle.configure(k, foreground=v[0], background=v[1], font=self.ui_get_font(v[2])) elif len(v) == 2: newstyle.configure(k, foreground=v[0], background=v[1]) else: Log.error('Invalid style format at key {}'.format(k)) self.quit() def ui_tk_make_sframe(self): '''Creates sframe. sframe is present in all menu-like views''' Log.debug('Creating sframe') self.sframe = ttk.Frame(self.root, style='std.TFrame') self.sframe.grid(sticky=ALL) self.widgets['title_label'] = ttk.Label(self.sframe, style='title.TLabel', text=self.TEXT.title_label, anchor=tk.CENTER) self.widgets['versn_label'] = ttk.Label( self.sframe, style='version.TLabel', text=self.ui_get_version_text()) self.widgets['title_label'].grid(**self.ui_get_grid(0, 0, 3, 1)) self.widgets['versn_label'].grid( **self.ui_get_grid(0, 2, 3, 1, 'es', False)) self.ui_rowcol_config(self.sframe, [0, 1, 0], [0, 1, 0]) def ui_tk_make_views(self): '''Creates menu-like views''' Log.debug('Creating views') self.views = {} # App-title view self.views['app_title'] = ttk.Frame(self.sframe, style='std.TFrame') self.widgets['btt_app_title_play'] = el.Button(self.views['app_title'], 'std.TButton', self.TEXT.btt_play, self.ui_show_view, 'pl_single') self.widgets['btt_app_title_quit'] = el.Button(self.views['app_title'], 'std.TButton', self.TEXT.btt_quit, self.quit) self.widgets['btt_app_title_play'].grid(**self.ui_get_grid(0, 0)) self.widgets['btt_app_title_quit'].grid(**self.ui_get_grid(0, 1)) self.ui_rowcol_config(self.views['app_title']) # pl_single view self.views['pl_single'] = ttk.Frame(self.sframe, style='std.TFrame') self.widgets['btt_pl_single_start'] = el.Button( self.views['pl_single'], 'std.TButton', self.TEXT.btt_start, self.start_game, 'first') # TEMP,TODO: This button should be binded to method that checks map # choice of user self.widgets['btt_pl_single_back'] = el.Button(self.views['pl_single'], 'std.TButton', self.TEXT.btt_back, self.ui_show_view, 'app_title') self.widgets['btt_pl_single_start'].grid(**self.ui_get_grid(0, 0)) self.widgets['btt_pl_single_back'].grid(**self.ui_get_grid(0, 1)) self.ui_rowcol_config(self.views['pl_single']) def ui_show_view(self, page_key): '''Shows chosen view from views dictionary''' try: for key, view in self.views.items(): view.grid_forget() self.views[page_key].grid(**self.ui_get_grid(1, 1)) except KeyError: Log.error('Invalid page key "{}"'.format(page_key)) self.quit() def quit(self): '''Application quit method''' Log.info('Leaving app') self.leaving = True self.root.destroy()