code
stringlengths
281
23.7M
class PokerGame(): TIMEOUT_TOLERANCE = 2 BET_TIMEOUT = 30 WAIT_AFTER_CARDS_ASSIGNMENT = 1 WAIT_AFTER_BET_ROUND = 1 WAIT_AFTER_SHOWDOWN = 2 WAIT_AFTER_WINNER_DESIGNATION = 5 def __init__(self, id: str, game_players: GamePlayers, event_dispatcher: GameEventDispatcher, deck_factory: DeckFactory...
def encode_data(primary_type, types, data): encoded_types = ['bytes32'] encoded_values = [hash_struct_type(primary_type, types)] for field in types[primary_type]: (type, value) = encode_field(types, field['name'], field['type'], data[field['name']]) encoded_types.append(type) encoded...
class UpdateOtherFieldHook(UpdateGenericHook): def __init__(self, other_field: str, update_function: Callable[([T], Any)], update_condition: Optional[Callable[([T], bool)]]=None, only_trigger_on_change: bool=True, triggers: Optional[Iterable[HookEventType]]=None) -> None: super().__init__(update_function=(l...
class FinancialInformationSubCategoryType(SubCategoryBase, Enum): CreditCard = 'CreditCard' CardExpiry = 'CardExpiry' BankAccountNumber = 'BankAccountNumber' BankRoutingNumber = 'BankRoutingNumber' SwiftCode = 'SwiftCode' TaxIdentificationNumber = 'TaxIdentificationNumber' def list_choices(c...
def test_dualperm_wg_fractured_sgas_property(dual_poro_dual_perm_wg_run): sgas = dual_poro_dual_perm_wg_run.get_property_from_restart('SGAS', date=, fracture=True) assert (sgas.values[(3, 0, 0)] == pytest.approx(0.0)) assert (sgas.values[(0, 1, 0)] == pytest.approx(0.)) assert (sgas.values[(4, 2, 0)] ==...
def comment_mismatches_in_file(to_comment_lines, fqp): with open(fqp) as fp: conts = fp.readlines() changed = False for (idx, line) in enumerate(conts): if any([(tmp in line) for tmp in to_comment_lines]): if (not line.strip().startswith('#')): changed = True ...
class OptionSeriesAreasplineSonificationTracksMappingFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): s...
def _get_twistd_cmdline(pprofiler, sprofiler): portal_cmd = [TWISTED_BINARY, f'--python={PORTAL_PY_FILE}', '--logger=evennia.utils.logger.GetPortalLogObserver'] server_cmd = [TWISTED_BINARY, f'--python={SERVER_PY_FILE}', '--logger=evennia.utils.logger.GetServerLogObserver'] if (os.name != 'nt'): por...
def information_based_similarity(x, y, n): Wordlist = [] Space = [[0, 0], [0, 1], [1, 0], [1, 1]] Sample = [0, 1] if (n == 1): Wordlist = Sample if (n == 2): Wordlist = Space elif (n > 1): Wordlist = Space Buff = [] for k in range(0, (n - 2)): ...
class ClientInformation(): def __init__(self, parent): builder = Gtk.Builder() builder.add_from_file(locate_resource('client_information.ui')) builder.connect_signals(self) self.dialog = builder.get_object('dlg_client_information') self.dialog.set_transient_for(parent) ...
class Cpu_interface(Peripherical_interface, metaclass=ABCMeta): vendor: str _model: str info: str def model(self) -> str: return self._model def model(self, value: str): raise NotImplementedError def temp(self) -> float: try: self._temp = self.get_temp() ...
class OptionPlotoptionsWaterfallSonificationDefaultinstrumentoptionsMappingLowpassFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapT...
def debug_server_general(args, settings): (prb, pwb) = os.pipe() tmpin = os.fdopen(prb, 'rb') tmpout = os.fdopen(pwb, 'wb') s = LangServer(conn=JSONRPC2Connection(ReadWriter(tmpin, tmpout)), settings=settings) if args.debug_rootpath: dir_exists = os.path.isdir(args.debug_rootpath) if...
def extractBrniWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in t...
def _branch_highlights(coverage_eval, coverage_map): results = dict(((i, []) for i in coverage_map)) for (path, fn) in [(k, x) for (k, v) in coverage_map.items() for x in v]: results[path].extend([(list(offset[:2]) + [_branch_color(int(i), coverage_eval, path, offset[2]), '']) for (i, offset) in coverag...
class Kaptan(object): HANDLER_MAP = {'json': JsonHandler, 'dict': DictHandler, 'yaml': YamlHandler, 'file': PyFileHandler, 'ini': IniHandler} def __init__(self, handler=None): self.configuration_data = dict() self.handler = None if handler: self.handler = self.HANDLER_MAP[han...
def test_async_ens_strict_bytes_type_checking_is_distinct_from_w3_instance(local_async_w3): ns = AsyncENS.from_web3(local_async_w3) assert (ns.w3 != local_async_w3) assert (ns.w3 == ns._resolver_contract.w3) assert local_async_w3.strict_bytes_type_checking assert ns.strict_bytes_type_checking lo...
class EventHandler(object): pdf_lock = threading.Lock() def __init__(self, browser, tab): self.browser = browser self.tab = tab self.start_frame = None def frame_started_loading(self, frameId): if (not self.start_frame): self.start_frame = frameId def frame_st...
class ErrStyle(Style): background_color = '#ffffcc' default_style = '' styles = {Whitespace: '#3e4349', Comment: '#3f6b5b', Keyword: 'bold #f06f00', Operator: '#3e4349', Name: '#3e4349', Name.Builtin: '#007020', Name.Function: 'bold #3e4349', Name.Class: 'bold #3e4349', Name.Variable: 'underline #8a2be2', N...
(scope='class', autouse=True) def setup(request, tmp_path_factory): cls = request.cls cls.local_remote_name = 'remote_repo' cls.local_branch = 'rally-unit-test-local-only-branch' cls.remote_branch = 'rally-unit-test-remote-only-branch' cls.rebase_branch = 'rally-unit-test-rebase-branch' cls.loca...
def kernel_tensorized(, x, , y, blur=0.05, kernel=None, name=None, potentials=False, **kwargs): (B, N, D) = x.shape (_, M, _) = y.shape if (kernel is None): kernel = kernel_routines[name] K_xx = kernel(double_grad(x), x.detach(), blur=blur) K_yy = kernel(double_grad(y), y.detach(), blur=blur...
def ovlp3d_13(ax, da, A, bx, db, B): result = numpy.zeros((3, 10), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + B[0]) x4 = (x3 ** 2) x5 = (3.0 * x0) x6 = (x2 + A[0]) x7 = (x3 * x6) x8 = ((x0 * ((((- 2.0) * x1) + A[0]) + B...
def is_program_info(name, f): name_underscore = (os.path.basename(strip_ngs_extensions(name)) + '_') name_dot = (os.path.basename(utils.rootname(name)) + '.') if (f.endswith('.programs') and (f.startswith(name_dot) or f.startswith(name_underscore))): return True else: return False
class Config(): template = None def __init__(self, **kwargs): self.max_error = kwargs.pop('max_error', (1 / (2 ** 63))) self.n_word_max = kwargs.pop('n_word_max', 64) self.overflow = kwargs.pop('overflow', 'saturate') self.rounding = kwargs.pop('rounding', 'trunc') self.s...
def test_read_request_stream_in_dispatch_after_app_calls_body(test_client_factory: Callable[([ASGIApp], TestClient)]) -> None: async def homepage(request: Request): assert ((await request.body()) == b'a') return PlainTextResponse('Homepage') class ConsumingMiddleware(BaseHTTPMiddleware): ...
def test_staticfiles_unhandled_os_error_returns_500(tmpdir, test_client_factory, monkeypatch): def mock_timeout(*args, **kwargs): raise TimeoutError path = os.path.join(tmpdir, 'example.txt') with open(path, 'w') as file: file.write('<file content>') routes = [Mount('/', app=StaticFiles(...
def test_namespace_collision(tester, build): build['abi'].append({'constant': False, 'inputs': [{'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}, {'name': '_test', 'type': 'uint256'}], 'name': 'bytecode', 'outputs': [{'name': '', 'type': 'bool'}], 'payable': False, 'stateMutability': 'nonpa...
class Requester(object): protocol = ' host = '' method = '' action = '' headers = {} data = {} def __init__(self, path, uagent, ssl, proxies): try: with open(path, 'r') as f: content = f.read().strip() except IOError as e: logging.error...
def extractNightbreeze(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) releases = ['Transcending The Nine Heavens', 'Stellar Transformation', 'Stellar Transformations'] for release in releases: if (release in item['tags']): return buildReleaseMessageWit...
def read_raw_node_data(pool, root_dir): (_, nodes) = lib.read_root_csv(root_dir) raw_node_data = [] with progressbar.ProgressBar(max_value=len(nodes)) as bar: for (idx, node) in enumerate(pool.imap_unordered(read_json5, nodes, chunksize=20)): bar.update(idx) raw_node_data.app...
def test_certification_nulls(client, setup_test_data): resp = client.get((url.format(agency='222', fy=2020, period=12) + '?sort=certification_date&order=desc')) assert (resp.status_code == status.HTTP_200_OK) response = resp.json() assert (len(response['results']) == 4) assert (response['results'] =...
def create_recipient_object(db_row_dict: dict) -> OrderedDict: return OrderedDict([('recipient_hash', obtain_recipient_uri(db_row_dict['_recipient_name'], db_row_dict['_recipient_uei'], db_row_dict['_parent_recipient_uei'], db_row_dict['_recipient_unique_id'], db_row_dict['_parent_recipient_unique_id'])), ('recipie...
('cuda.fused_elementwise.gen_function') def fused_elementwise_gen_function(func_attrs: Dict[(str, Any)]) -> str: custom_libs = Target.current().get_custom_libs(os.path.dirname(__file__), 'custom_math.cuh') return elementwise_common.fused_elementwise_gen_function(func_attrs=func_attrs, custom_libs=custom_libs, h...
class PeerID(Struct): def build(identifier: str, name: str, flags: int=6) -> PeerID: peer_id = PeerID() peer_id._identifier = identifier peer_id._name = name peer_id._cfields['flags'] = flags peer_id._cfields['length'] = len(peer_id.peer_string()) return peer_id d...
def make_pausing_beam_chain(vm_config: VMConfiguration, chain_id: int, consensus_context_class: Type[ConsensusContextAPI], db: AtomicDatabaseAPI, event_bus: EndpointAPI, metrics_registry: MetricsRegistry, loop: asyncio.AbstractEventLoop, urgent: bool=True) -> BeamChain: pausing_vm_config = tuple(((starting_block, p...
class OptionSeriesVariablepieSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesVariablepieSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesVariablepieSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesVariablepieSonifi...
def make_clean(fips_dir, proj_dir, cfg_name): proj_name = util.get_project_name_from_dir(proj_dir) configs = config.load(fips_dir, proj_dir, cfg_name) num_valid_configs = 0 if configs: for cfg in configs: (config_valid, _) = config.check_config_valid(fips_dir, proj_dir, cfg, print_er...
class OptionSeriesGaugeSonificationDefaultinstrumentoptionsActivewhen(Options): def crossingDown(self): return self._config_get(None) def crossingDown(self, num: float): self._config(num, js_type=False) def crossingUp(self): return self._config_get(None) def crossingUp(self, num:...
class ResourceRulesEngine(base_rules_engine.BaseRulesEngine): def __init__(self, rules_file_path, snapshot_timestamp=None): super(ResourceRulesEngine, self).__init__(rules_file_path=rules_file_path) self.rule_book = None def build_rule_book(self, global_configs=None): self.rule_book = Re...
class CommitteeDetail(BaseConcreteCommittee): __table_args__ = {'extend_existing': True} __tablename__ = 'ofec_committee_detail_mv' email = db.Column(db.String(50), doc=docs.COMMITTEE_EMAIL) fax = db.Column(db.String(10), doc=docs.COMMITTEE_FAX) website = db.Column(db.String(50), doc=docs.COMMITTEE_...
def mockproject(newproject, mocker): with newproject._path.joinpath('contracts/Foo.sol').open('w') as fp: fp.write(CONTRACT) with newproject._path.joinpath('contracts/BaseFoo.sol').open('w') as fp: fp.write(BASE_CONTRACT) with newproject._path.joinpath('contracts/FooLib.sol').open('w') as fp...
class OptionSeriesTreegraphSonificationContexttracksMappingRate(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class OptionSeriesPictorialData(Options): def accessibility(self) -> 'OptionSeriesPictorialDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesPictorialDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): self...
class OptionPlotoptionsTreegraphSonificationTracksMappingPlaydelay(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def test_group(): report_data = get_report_data() assert ({'node_id': 'model.elementary_integration_tests.error_model', 'resource_type': 'model'} in report_data['groups']['dbt']['elementary_integration_tests']['models']['__files__']) assert ({'node_id': 'model.elementary_integration_tests.nested', 'resource...
class EODRetriever(FileSource): sphinxdoc = '\n EODRetriever\n ' def __init__(self, source='ecmwf', *args, **kwargs): if len(args): assert (len(args) == 1) assert isinstance(args[0], dict) assert (not kwargs) kwargs = args[0] self.source_kwar...
def setup_authentication(app, get_pw_callback): auth = HTTPDigestAuth() _required def _assert_auth_before_request(): app.logger.info(f'User: {auth.username()}') return None app.logger.info(f'Setting up {app} to require login...') auth.get_password(get_pw_callback) app.before_requ...
def _migrate_gen_kw(ensemble: EnsembleAccessor, data_file: DataFile, ens_config: EnsembleConfig) -> None: for block in data_file.blocks(Kind.GEN_KW): config = ens_config[block.name] assert isinstance(config, GenKwConfig) priors = config.get_priors() array = data_file.load(block, len(...
def download_datasets(data_dir): if (not os.path.isdir(data_dir)): os.mkdir(data_dir) datasets_dir = os.path.join(data_dir, 'datasets') if (not os.path.isdir(datasets_dir)): os.mkdir(datasets_dir) datasets = ['roxford5k', 'rparis6k'] for di in range(len(datasets)): dataset = ...
def _patch_info_in_place(fsize, patch_size, compression, compression_info, memory_size, segment_size, from_shift_size, from_size, to_size, segments): patch_to_ratio = _format_ratio(patch_size, to_size) compression = _format_compression(compression, compression_info) print('Type: in-place') ...
def fetch_exchange(zone_key1: str, zone_key2: str, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> dict: if target_datetime: raise NotImplementedError('This parser is not yet able to parse past dates') sorted_zones = '->'.join(sorted([zone_...
class Bug(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) body = db.Column(db.Text, nullable=False) link = db.Column(db.String(100), nullable=False) owner_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) reviewed = db....
class FBPrintCountersCommand(fb.FBCommand): def name(self): return 'printcounters' def description(self): return 'Prints all the counters sorted by the keys.' def run(self, arguments, options): keys = sorted(counters.keys()) for key in keys: print(((key + ': ') + ...
class MegaDB(): def __init__(self): if Common().is_atlas: self.db_client = pymongo.MongoClient(Common().db_host) else: self.db_client = pymongo.MongoClient(Common().db_host, username=Common().db_username, password=Common().db_password) self.db = self.db_client[Common(...
def test_app_middleware_argument(test_client_factory): def homepage(request): return PlainTextResponse('Homepage') app = Starlette(routes=[Route('/', homepage)], middleware=[Middleware(CustomMiddleware)]) client = test_client_factory(app) response = client.get('/') assert (response.headers['...
def rotate_island(island, uv_layer=None, angle=0, center_x=0, center_y=0): if (uv_layer is None): me = bpy.context.active_object.data bm = bmesh.from_edit_mesh(me) uv_layer = bm.loops.layers.uv.verify() for face in island: for loop in face.loops: (x, y) = loop[uv_laye...
def get_next_ball_pocket_collision(shot: System, solver: QuarticSolver=QuarticSolver.HYBRID) -> Event: dtau_E = np.inf agent_ids = [] collision_coeffs = [] for ball in shot.balls.values(): if (ball.state.s in const.nontranslating): continue state = ball.state params =...
class OptionSeriesVectorStatesHoverMarker(Options): def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config(flag, js_type=False) def enabledThreshold(self): return self._config_get(2) def enabledThreshold(self, num: float): self._confi...
def exposed_test_all_rss(): print('fetching and debugging RSS feeds') rules = WebMirror.rules.load_rules() feeds = [item['feedurls'] for item in rules] feeds = [item for sublist in feeds for item in sublist] flags.RSS_DEBUG = True with ThreadPoolExecutor(max_workers=8) as executor: for u...
def test_serialize_deserialize(): key_hash = b'key_hash' key_data = b'key_data' value_data = b'value_data' item = StorageItem.build_from(key_hash, key_data, value_data) serialized = item.serialize() deserialized = StorageItem.deserialize(serialized) assert (deserialized.key_hash == item.key_...
class UNet2DConditionModel(nn.Module): def __init__(self, sample_size: Optional[int]=None, in_channels: int=4, out_channels: int=4, center_input_sample: bool=False, flip_sin_to_cos: bool=True, freq_shift: int=0, down_block_types: Tuple[str]=('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'D...
def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('beacon', metavar='BEACON', help='beacon to use as configuration') comms = parser.add_argument_group('beacon communication') comms.add_argument('-d'...
def GetPythonDependencies(): _ForceLazyModulesToLoad() module_paths = (m.__file__ for m in sys.modules.values() if ((m is not None) and hasattr(m, '__file__'))) abs_module_paths = map(os.path.abspath, filter((lambda p: (p is not None)), module_paths)) assert os.path.isabs(DIR_SOURCE_ROOT) non_system...
def dircmp_recursive(dircmp_obj: filecmp.dircmp) -> Tuple[(Set[str], Set[str], Set[str])]: def _dircmp_recursive(dircmp_obj: filecmp.dircmp, prefix: str='') -> Tuple[(Set[str], Set[str], Set[str])]: def join_with_prefix(suffix: str) -> str: return os.path.join(prefix, suffix) left_only: ...
def parse(code='', mode='sys', state=False, keep_internal_state=None): if (keep_internal_state is None): keep_internal_state = bool(state) command = get_state(state) if (command.comp is None): command.setup() if (mode not in PARSERS): raise CoconutException(('invalid parse mode '...
('cuda.gemm_rrr_small_nk.func_call') def gen_function_call(func_attrs, indent=' '): a = func_attrs['inputs'][0] ashape = a._attrs['shape'] adims = [('&' + dim._attrs['name']) for dim in ashape] b = func_attrs['inputs'][1] bshape = b._attrs['shape'] bdims = [('&' + dim._attrs['name']) for dim in...
class CustomerTypeTests(unittest.TestCase): def test_unicode(self): customer_type = CustomerType() customer_type.Name = 'test' self.assertEqual(str(customer_type), 'test') def test_valid_object_name(self): obj = CustomerType() client = QuickBooks() result = client...
def _unicorn_hook_block(uc: Uc, address: int, _size: int, user_data: Tuple[(ProcessController, int)]) -> None: (process_controller, stop_on_ret_addr) = user_data ptr_size = process_controller.pointer_size arch = process_controller.architecture if (arch == Architecture.X86_32): pc_register = UC_X...
(help={'serve': 'Build the docs watching for changes', 'open_browser': 'Open the docs in the web browser'}) def docs(c, serve=False, open_browser=False): _run(c, f'sphinx-apidoc -o {DOCS_DIR} {SOURCE_DIR}') build_docs = f'sphinx-build -b html {DOCS_DIR} {DOCS_BUILD_DIR}' _run(c, build_docs) if open_brow...
def find_config_path(path: Path) -> Tuple[(Path, bool)]: if path.is_dir(): current_dir = path else: current_dir = path.parent if (current_dir / '_config.yml').is_file(): return (current_dir, True) while (current_dir != current_dir.parent): if (current_dir / '_config.yml')...
(tags=['electioneering'], description=docs.ELECTIONEERING_AGGREGATE_BY_CANDIDATE) class ElectioneeringByCandidateView(CandidateAggregateResource): model = models.ElectioneeringByCandidate schema = schemas.ElectioneeringByCandidateSchema page_schema = schemas.ElectioneeringByCandidatePageSchema query_arg...
.parallel(nprocs=2) def test_assign_with_valid_halo_and_subset_sets_halo_values(cg1): u = Function(cg1) assert u.dat.halo_valid subset = make_subset(cg1) u.assign(1, subset=subset) expected = ([0] * u.dat.dataset.total_size) expected[0] = 1 expected[u.dat.dataset.size] = 1 assert u.dat.h...
class TestUserUtilitiesHelper(OpenEventTestCase): def test_modify_email_for_user_to_be_deleted(self): with self.app.test_request_context(): user = create_user(email='test_', password='testpass') save_to_db(user) modified_user = modify_email_for_user_to_be_deleted(user) ...
class S7LPDDR5PHY(LPDDR5PHY, S7Common): def __init__(self, pads, *, iodelay_clk_freq, with_odelay, ddr_clk=None, csr_cdc=None, **kwargs): self.iodelay_clk_freq = iodelay_clk_freq super().__init__(pads, ser_latency=Latency(sys=1), des_latency=Latency(sys=2), phytype=self.__class__.__name__, **kwargs)...
class Attribute(): _attribute_type_to_pb = {bool: models_pb2.Query.Attribute.BOOL, int: models_pb2.Query.Attribute.INT, float: models_pb2.Query.Attribute.DOUBLE, str: models_pb2.Query.Attribute.STRING, Location: models_pb2.Query.Attribute.LOCATION} __slots__ = ('name', 'type', 'is_required', 'description') ...
class ViewManager(GObject.Object): __gsignals__ = {'new-view': (GObject.SIGNAL_RUN_LAST, None, (str,))} view_name = GObject.property(type=str, default=CoverIconView.name) def __init__(self, source, window): super(ViewManager, self).__init__() self.source = source self.window = window...
class AutoPausePlugin(plugin.Plugin): _errors (Events.SESSION_END) def on_session_end(self, **_): self.pause() def pause(self) -> None: try: for player in Playerctl.list_players(): instance = Playerctl.Player.new_from_name(player) if (instance....
def add_args(subparsers): parser = subparsers.add_parser('subscribe', formatter_class=argparse.ArgumentDefaultsHelpFormatter, description=__doc__, help='Listen to a stream of messages') parser.add_argument('-c', '--clientid', default=('beem.listr-%d' % os.getpid()), help='Set the client id of the listner, can b...
def strOfSize(size): def strofsize(integer, remainder, level): if (integer >= 1024): remainder = (integer % 1024) integer //= 1024 level += 1 return strofsize(integer, remainder, level) else: return (integer, remainder, level) units = [...
class OptionPlotoptionsAreasplinerangeLowmarkerStates(Options): def hover(self) -> 'OptionPlotoptionsAreasplinerangeLowmarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsAreasplinerangeLowmarkerStatesHover) def normal(self) -> 'OptionPlotoptionsAreasplinerangeLowmarkerStatesNorma...
def log_task(task): logger.info('Received Task:') task_dt = datetime.datetime.fromtimestamp(task.epoch, tz=datetime.timezone.utc) data_r = reprlib.repr(task.data) logger.info(f' - stamp: {task_dt} ({task.epoch:#04x})') logger.info(f' - task: {task.command} ({task.command.value}, {task.command.valu...
def speed_test_no_column(): remap = remap_ids_v2(mapper) premap = premap_ids(mapper) keys = np.random.randint(0, N_symbols, N_tokens) with time_context() as elapsed: for i in range(100): remap(keys, False) remaptime = elapsed.elapsed with time_context() as elapsed: fo...
def generate_random_factored_numbers_with_multiplicative_group(bits, procs, count): count_per_proc = (count // procs) processes = [mp.Process(target=generate_random_factored_numbers_with_multiplicative_group_mp, args=(gmpy2.mpz((2 ** bits)), random.randint(1, (10 ** 10)), count_per_proc)) for x in range(procs)]...
def extractAshialafineWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('The Daughter of the Albert House Wishes for Ruin', 'The Daughter of the Albert House Wishes f...
def test_param_convention_mars_2(): ('parameter', 'variable-list(mars)') def values_mars(parameter): return parameter assert (values_mars(parameter='tp') == ['tp']) assert (values_mars(parameter='2t') == ['2t']) assert (values_mars(parameter='t2m') == ['2t']) assert (values_mars(paramete...
class OptionSeriesStreamgraphSonificationContexttracksMappingFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class TypeGraph(DiGraph): class EdgeType(Enum): assignment = 0 subexpression = 1 def __init__(self, **attr): super().__init__(**attr) self._usages: DefaultDict[(Expression, Set)] = defaultdict(set) def from_cfg(cls, cfg: ControlFlowGraph) -> TypeGraph: graph = cls() ...
class Crunchyroll(): def __init__(self, channel=False): if channel: self.channel = channel.replace(' '') self.channel_url = ' self.channel_folder = self.channel.split('/')[(- 1)] self.last_episode_file = '{}/{}/{}.{}'.format(media_folder, sanitize('{}'.format(...
class Solution(object): def uniqueMorseRepresentations(self, words): mos = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..'] trans = set() for word in word...
def preprocess_jap(text): 'Reference text = symbols_to_japanese(text) sentences = re.split(_japanese_marks, text) marks = re.findall(_japanese_marks, text) text = [] for (i, sentence) in enumerate(sentences): if re.match(_japanese_characters, sentence): p = pyopenjtalk.g2p(s...
class Invalid(Exception): def __init__(self, msg, value, state, error_list=None, error_dict=None): Exception.__init__(self, msg, value, state, error_list, error_dict) self.msg = msg self.value = value self.state = state self.error_list = error_list self.error_dict = e...
def main(): parser = argparse.ArgumentParser(description='LiteDRAM Bench on XCU1525') parser.add_argument('--uart', default='crossover', help='Selected UART: crossover (default) or serial') parser.add_argument('--build', action='store_true', help='Build bitstream') parser.add_argument('--channel', defau...
class RandomResizeCrop(): def __init__(self, jitter=10, ratio=0.5): self.jitter = jitter self.ratio = ratio def __call__(self, img): (w, h) = img.size img = transforms.functional.pad(img, self.jitter, fill=255) x = (self.jitter + random.randint((- self.jitter), self.jitte...
class DefaultOverride(EditorFactory): _overrides = Dict() def __init__(self, *args, **overrides): EditorFactory.__init__(self, *args) self._overrides = overrides def _customise_default(self, editor_kind, ui, object, name, description, parent): trait = object.trait(name) edito...
def write_render(ints_Ls, args, name, doc_func, out_dir, comment='', py_kwargs=None, c=True, c_kwargs=None): if (py_kwargs is None): py_kwargs = {} if (c_kwargs is None): c_kwargs = {} ints_Ls = list(ints_Ls) py_rendered = render_py_funcs(ints_Ls, args, name, doc_func, comment=comment, *...
(frozen=True) class CompilationState(object): prefix: str mode: int = 1 task_resolver: Optional[TaskResolverMixin] = None nodes: List = field(default_factory=list) def add_node(self, n: Node): self.nodes.append(n) def with_params(self, prefix: str, mode: Optional[int]=None, resolver: Opt...
def trace_and_save_torchscript(model: nn.Module, inputs: Optional[Tuple[Any]], output_path: str, torchscript_filename: str='model.jit', mobile_optimization: Optional[MobileOptimizationConfig]=None, _extra_files: Optional[Dict[(str, bytes)]]=None): return export_optimize_and_save_torchscript(model, inputs, output_pa...
def add_name(font, string, nameID): nameTable = font.get('name') if (nameTable is None): nameTable = font['name'] = table__n_a_m_e() nameTable.names = [] namerec = NameRecord() namerec.nameID = nameID namerec.string = string.encode('mac_roman') (namerec.platformID, namerec.platEn...
class TabsExtraDocCommand(sublime_plugin.WindowCommand): re_pkgs = re.compile('^Packages') def on_navigate(self, href): if href.startswith('sub://Packages'): sublime.run_command('open_file', {'file': self.re_pkgs.sub('${packages}', href[6:])}) else: webbrowser.open_new_ta...
class VideoUploader(object): def __init__(self): self._session = None def upload(self, video, wait_for_encoding=False): if self._session: raise FacebookError('There is already an upload session for this video uploader') self._session = VideoUploadSession(video, wait_for_encod...