code
stringlengths
281
23.7M
class ColumnSharder(FLDataSharder): def __init__(self, **kwargs): init_self_cfg(self, component_class=__class__, config_class=ColumnSharderConfig, **kwargs) super().__init__(**kwargs) def shard_for_row(self, csv_row: Dict[(Any, Any)]) -> List[Any]: unwrapped_colindex = self.cfg.sharding_...
def create_all_dirs(pathinfo, rootpath='.'): try: if (not os.path.exists(rootpath)): os.mkdir(rootpath) for info in pathinfo: d = os.path.join(rootpath, os.path.split(info)[0]) if (not os.path.exists(d)): os.makedirs(d) except: print(sy...
class OptionPlotoptionsLollipopLowmarkerStates(Options): def hover(self) -> 'OptionPlotoptionsLollipopLowmarkerStatesHover': return self._config_sub_data('hover', OptionPlotoptionsLollipopLowmarkerStatesHover) def normal(self) -> 'OptionPlotoptionsLollipopLowmarkerStatesNormal': return self._con...
def make_fproc(func_attrs, layout, dtype='float16'): def fproc(op): (a_layout, b_layout, c_layout) = layout.cutlass_lib_layouts() return default_fproc(op=op, a_layout=a_layout, b_layout=b_layout, c_layout=c_layout, epilogue_name=func_attrs['epilogue'], epilogue2_name=func_attrs['epilogue2'], dtype=d...
def format_username_openldap(model_fields): return '{user_identifier},{search_base}'.format(user_identifier=','.join(('{attribute_name}={field_value}'.format(attribute_name=clean_ldap_name(field_name), field_value=clean_ldap_name(field_value)) for (field_name, field_value) in convert_model_fields_to_ldap_fields(mod...
def convert_version(version, app, repodir): ver = {} if ('added' in version): ver['added'] = convert_datetime(version['added']) else: ver['added'] = 0 ver['file'] = {'name': '/{}'.format(version['apkName']), version['hashType']: version['hash'], 'size': version['size']} ipfsCIDv1 = v...
def extract_yaml(yaml_files): loaded_yaml = [] for yaml_file in yaml_files: try: with open(yaml_file, 'r') as fd: loaded_yaml.append(yaml.safe_load(fd)) except IOError as e: print('Error reading file', yaml_file) raise e except yaml.YAM...
def extractBisugotlWordpressCom(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) ...
class TestComparisonMode(unittest.TestCase): def setUp(self): self.a = Foo(name='a') self.same_as_a = Foo(name='a') self.different_from_a = Foo(name='not a') def bar_changed(self, object, trait, old, new): self.changed_object = object self.changed_trait = trait se...
def call(cmd, input_file=None, input_text=None, encoding=None): process = get_process(cmd) if (input_file is not None): with open(input_file, 'rb') as f: process.stdin.write(f.read()) if (input_text is not None): process.stdin.write(input_text) return get_process_output(proce...
class SigningHandler(Handler): SUPPORTED_PROTOCOL = SigningMessage.protocol_id def setup(self) -> None: def handle(self, message: Message) -> None: signing_msg = cast(SigningMessage, message) signing_dialogues = cast(SigningDialogues, self.context.signing_dialogues) signing_dialogue ...
class BufferedS3Reader(contextlib.AbstractContextManager): def __init__(self, s3_path: pathlib.Path, storage_service: S3StorageService) -> None: self.s3_path = s3_path self.storage_service = storage_service self.data: Optional[str] = None self.cursor = 0 def __enter__(self) -> Bu...
def get_layout_page_with_text_or_graphic_replaced_by_graphic(layout_page: LayoutPage, semantic_graphic: SemanticGraphic, is_only_semantic_graphic_on_page: bool, is_replace_overlapping_text: bool) -> LayoutPage: layout_graphic = semantic_graphic.layout_graphic assert layout_graphic assert layout_graphic.coor...
def test_detect_variables_with_na(df_na): imputer = DropMissingData(missing_only=True, variables=None) X_transformed = imputer.fit_transform(df_na) assert (imputer.missing_only is True) assert (imputer.threshold is None) assert (imputer.variables is None) assert (imputer.variables_ == ['Name', '...
def send_confirmation_msg(doc): if frappe.db.get_single_value('Healthcare Settings', 'send_appointment_confirmation'): message = frappe.db.get_single_value('Healthcare Settings', 'appointment_confirmation_msg') try: send_message(doc, message) except Exception: frappe....
def delegatecall(evm: Evm) -> None: gas = Uint(pop(evm.stack)) code_address = to_address(pop(evm.stack)) memory_input_start_position = pop(evm.stack) memory_input_size = pop(evm.stack) memory_output_start_position = pop(evm.stack) memory_output_size = pop(evm.stack) extend_memory = calculate...
class OptionSeriesHeatmapSonificationContexttracksActivewhen(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: float): ...
def test_display_callback(): def run_callback(): context_value.set(AttributeDict(**{'triggered_inputs': [{'prop_id': 'btn-1-ctx-example.n_clicks'}]})) return display(1, 0, 0) ctx = copy_context() output = ctx.run(run_callback) assert (output == f'You last clicked button with ID btn-1-ctx...
def us_bench_test(freq_min, freq_max, freq_step, vco_freq, bios_filename, bios_timeout=40): import time from litex import RemoteClient bus = RemoteClient() bus.open() ctrl = BenchController(bus) ctrl.load_rom(bios_filename, delay=0.0001) ctrl.reboot() uspll = USPLL(bus) clkout0_clkre...
class TestTopicPollVoteView(BaseClientTestCase): (autouse=True) def setup(self): self.perm_handler = PermissionHandler() self.top_level_forum = create_forum() self.topic = create_topic(forum=self.top_level_forum, poster=self.user) self.post = PostFactory.create(topic=self.topic, ...
def get_regression_quality_metrics(regression_quality_report: Report) -> Dict: metrics = {} report_dict = regression_quality_report.as_dict() metrics['me'] = report_dict['metrics'][0]['result']['current']['mean_error'] metrics['mae'] = report_dict['metrics'][0]['result']['current']['mean_abs_error'] ...
def _clean_args_list(args: List[str]) -> List[str]: ALLOWLIST = ['--disable-logging', '--project-dir', '--profiles-dir', '--defer', '--threads', '--thread', '--state', '--full-refresh', '-s', '--select', '-m', '--models', '--model', '--exclude', '--selector', '--all', 'run', 'dbt', '-v', '--version', '--debug', '--...
def test_unit_status_check_properties(): def no_op(): pass widget = qtile_extras.widget.UnitStatus() widget.draw = no_op assert (widget.state == 'not-found') widget._changed(None, {'OtherProperty': Variant('s', 'active')}, None) assert (widget.state == 'not-found') widget._changed(No...
def test_load_schema_union_names(): ' load_schema_dir = join(abspath(dirname(__file__)), 'load_schema_test_15') schema_path = join(load_schema_dir, 'A.avsc') loaded_schema = fastavro.schema.load_schema(schema_path, _write_hint=False) expected_schema = [{'name': 'B', 'type': 'record', 'fields': [{'na...
.network def test_zenodo_downloader_with_slash_in_fname(): with TemporaryDirectory() as local_store: base_url = (ZENODOURL_W_SLASH + 'santisoler/pooch-test-data-v1.zip') downloader = DOIDownloader() outfile = os.path.join(local_store, 'test-data.zip') downloader(base_url, outfile, No...
.skipif(('WEB3_INFURA_PROJECT_ID' not in os.environ), reason='Infura API key unavailable') def test_registry_uri_backend(backend): valid_uri = 'erc1319://0xDECD360e6d4d979edBcDD59c35feeB:1/.0.0' expected_uri = 'ipfs://QmbeVyFLSuEUxiXKwSsEjef6icpdTdA4kGG9BcrJXKNKUW' assert (backend.can_translate_uri(valid_ur...
def test_file_type_stats(stats_updater, backend_db): assert (stats_updater.get_file_type_stats() == {'file_types': [], 'firmware_container': []}) type_analysis = generate_analysis_entry(analysis_result={'mime': 'fw/image'}) type_analysis_2 = generate_analysis_entry(analysis_result={'mime': 'file/type1'}) ...
class OptionPlotoptionsSplineStatesHover(Options): def animation(self) -> 'OptionPlotoptionsSplineStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsSplineStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
def extractSupermeganetWordpressCom(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_ty...
def check_withings_connection(): if withings_credentials_supplied: if (not withings_connected()): return html.A(className='col-lg-12', children=[dbc.Button('Connect Withings', id='connect-withings-btton', color='primary', className='mb-2', size='sm')], href=connect_withings_link(WithingsAuth(con...
_util.copy_func_kwargs(HttpsOptions) def on_call(**kwargs) -> _typing.Callable[([_C2], _C2)]: options = HttpsOptions(**kwargs) def on_call_inner_decorator(func: _C2): origins: _typing.Any = '*' if ((options.cors is not None) and (options.cors.cors_origins is not None)): origins = opt...
def test_tesseroid_layer_invalid_surface_reference(dummy_layer): (coordinates, surface, reference, _) = dummy_layer surface_invalid = np.arange(20, dtype=float) with pytest.raises(ValueError, match='Invalid surface array with shape'): tesseroid_layer(coordinates, surface_invalid, reference) refe...
class ImageLibrary(HasPrivateTraits): volumes = List(ImageVolume) catalog = Dict(Str, ImageVolume) images = Property(List, observe='volumes.items.images') aliases = Dict() def image_info(self, image_name): volume = self.find_volume(image_name) if (volume is not None): ret...
('config_type', ['strict']) def test_missing_envs_strict_mode(config, json_config_file_3): with open(json_config_file_3, 'w') as file: file.write(json.dumps({'section': {'undefined': '${UNDEFINED}'}})) with raises(ValueError, match='Missing required environment variable "UNDEFINED"'): config.fro...
def enum_values_changed(values, strfunc=str): if isinstance(values, dict): data = [(strfunc(v), n) for (n, v) in values.items()] if (len(data) > 0): data.sort(key=itemgetter(0)) col = (data[0][0].find(':') + 1) if (col > 0): data = [(n[col:], v) fo...
def clusterise_dscalar_input(data_file, arguments, surf_settings, tmpdir): pcluster_dscalar = os.path.join(tmpdir, 'pclusters.dscalar.nii') wb_cifti_clusters(data_file, pcluster_dscalar, surf_settings, arguments['--max-threshold'], arguments['--area-threshold'], less_than=False, starting_label=1) pos_clust_...
.parametrize('log_name, change_from, change_to', [('Poro', 'CONT', 'DISC'), ('Poro', 'CONT', 'CONT'), ('Facies', 'DISC', 'CONT')]) def test_set_log_type(simple_well, log_name, change_from, change_to): mywell = simple_well assert (mywell.get_logtype(log_name) == change_from) mywell.set_logtype(log_name, chan...
def synthetic_attributes(): def decorator(original_class): original_init = original_class.__init__ def __init__(self, *args, **kws): method_list = [func for func in dir(original_class) if callable(getattr(original_class, func))] for method_name in method_list: ...
class YoutubeWidget(Widget): DEFAULT_MIN_SIZE = (100, 100) source = event.StringProp('oHg5SJYRHA0', settable=True, doc='\n The source of the video represented as the Youtube id.\n ') def _create_dom(self): global window node = window.document.createElement('div') self.i...
class Build(Base): __tablename__ = 'builds' __exclude_columns__ = ('id', 'package', 'package_id', 'release', 'testcases', 'update_id', 'update', 'override') __get_by__ = ('nvr',) nvr = Column(Unicode(100), unique=True, nullable=False) signed = Column(Boolean, default=False, nullable=False) overr...
class ColorFormatter(logging.Formatter): 'Logging Formatter to add colors and count warning / errors.\n\n Taken from Stackeverflow user Sergey Pleshakov from this URL\n grey = '\x1b[38;21m' yellow = '\x1b[33;21m' red = '\x1b[31;21m' bold_red = '\x1b[31;1m' reset = '\x1b[0m' format = '...
def run_pcap_to_features(pcap=None, outdir=False): with tempfile.TemporaryDirectory() as tmpdir: testdata = os.path.join(tmpdir, 'test_data') shutil.copytree('./tests/test_data', testdata) if pcap: pcap_path = os.path.join(testdata, pcap) pcap_csv_path = os.path.join(...
class Solution(object): def countSegments(self, s): (n, inchar) = (0, False) for c in s: if (c == ' '): if inchar: n += 1 inchar = False else: inchar = True if inchar: n += 1 retur...
def FQ(lib): if (lib == bn128): return bn128_FQ elif (lib == optimized_bn128): return optimized_bn128_FQ elif (lib == bls12_381): return bls12_381_FQ elif (lib == optimized_bls12_381): return optimized_bls12_381_FQ else: raise Exception('Library Not Found')
class PopupColorItem(ft.PopupMenuItem): def __init__(self, color, name): super().__init__() self.content = ft.Row(controls=[ft.Icon(name=ft.icons.COLOR_LENS_OUTLINED, color=color), ft.Text(name)]) self.on_click = self.seed_color_changed self.data = color async def seed_color_chan...
class InformationFileNotExist(ErsiliaError): def __init__(self, model_id): self.message = 'The eos/dest/{0}/information.json file does not exist.'.format(model_id) self.hints = 'Try fetching and serving the model first, and make sure the model is written correctly.' super().__init__(self.mes...
class OptionSeriesHeatmapDataMarkerStates(Options): def hover(self) -> 'OptionSeriesHeatmapDataMarkerStatesHover': return self._config_sub_data('hover', OptionSeriesHeatmapDataMarkerStatesHover) def normal(self) -> 'OptionSeriesHeatmapDataMarkerStatesNormal': return self._config_sub_data('normal...
class SimpleFormValidator(FancyValidator): __unpackargs__ = ('func',) validate_partial_form = False def __initargs__(self, new_attrs): self.__doc__ = getattr(self.func, '__doc__', None) def to_python(self, value_dict, state): value_dict = value_dict.copy() errors = self.func(valu...
class OptionPlotoptionsPyramidSonificationContexttracksMappingPan(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 OptionSeriesBulletLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._config(text, js_...
class HtaConfigTestCase(unittest.TestCase): def setUp(self) -> None: self.test_config_path = '/tmp/test_config.json' self.test_config = {'a': 1, 'b': ['s', 't'], 'c': {'c1': 2, 'c2': {'c21': 10.0}}} with open(self.test_config_path, 'w+') as fp: json.dump(self.test_config, fp) ...
class Solution(): def isInterleave(self, s1: str, s2: str, s3: str) -> bool: def is_inter(s1, s2, s3, i, j, prev, tr): key = (i, j, prev) if (key in tr): return tr[key] if ((i == len(s1)) and (j == len(s2))): return True elif ((...
class ScrolledMessageDialog(wx.Dialog): def __init__(self, parent, msg, caption, pos=wx.DefaultPosition, size=(500, 300)): wx.Dialog.__init__(self, parent, (- 1), caption, pos, size) (x, y) = pos if ((x == (- 1)) and (y == (- 1))): self.CenterOnScreen(wx.BOTH) text = wx.T...
class TestRelocation(unittest.TestCase): def test_dynamic_segment(self): test_dir = os.path.join('test', 'testfiles_for_unittests') with open(os.path.join(test_dir, 'x64_bad_sections.elf'), 'rb') as f: elff = ELFFile(f) for seg in elff.iter_segments(): if isin...
class HDB(PlatformUtilBase): def __init__(self, device=None, tempdir=None): super(HDB, self).__init__(device, tempdir) def push(self, src, tgt): getLogger().info('push {} to {}'.format(src, tgt)) if (src != tgt): if os.path.isdir(src): if os.path.exists(tgt): ...
class Last(Op): __slots__ = ('_last',) def __init__(self, source=None): Op.__init__(self, source) self._last = NO_VALUE def on_source(self, *args): self._last = args def on_source_done(self, source): self.emit(*self._last) Op.on_source_done(self, source)
class TransonicTemporaryJITMethod(): __transonic__ = 'jit_method' def __init__(self, func, native, xsimd, openmp): self.func = func self.native = native self.xsimd = xsimd self.openmp = openmp def __call__(self, self_bis, *args, **kwargs): raise RuntimeError('Did you ...
class CaretSmartProcessor(util.PatternSequenceProcessor): PATTERNS = [util.PatSeqItem(re.compile(SMART_INS_SUP, (re.DOTALL | re.UNICODE)), 'double', 'ins,sup'), util.PatSeqItem(re.compile(SMART_SUP_INS, (re.DOTALL | re.UNICODE)), 'double', 'sup,ins'), util.PatSeqItem(re.compile(SMART_INS_SUP2, (re.DOTALL | re.UNICO...
def test_required(): example = typesystem.Schema(fields={'field': typesystem.Integer()}) (value, error) = example.validate_or_error({}) assert (dict(error) == {'field': 'This field is required.'}) example = typesystem.Schema(fields={'field': typesystem.Integer(allow_null=True)}) (value, error) = exa...
def ee_xx_impulse(res, aniso, off, time): tau_h = np.sqrt(((mu_0 * (off ** 2)) / (res * time))) t0 = (tau_h / ((2 * time) * np.sqrt(np.pi))) t1 = np.exp(((- (tau_h ** 2)) / 4)) t2 = (((tau_h ** 2) / (2 * (aniso ** 2))) + 1) t3 = np.exp(((- (tau_h ** 2)) / (4 * (aniso ** 2)))) Exx = (((res / ((2 ...
.parametrize('order_status', ['completed', 'placed']) def test_stream_get_attendee(db, client, user, jwt, order_status): (room, stream, session) = get_room_session_stream(db, name='Test Stream') email = '' user._email = email AttendeeOrderSubFactory(event=room.event, order__status=order_status, email=em...
def test_label_to_hash_normalizes_name_using_ensip15(): normalized_name = ENSNormalizedName([Label('test', [TextToken([102, 111, 111])]), Label('test', [TextToken([101, 116, 104])])]) assert (normalized_name.as_text == 'foo.eth') with patch('ens.utils.normalize_name_ensip15') as mock_normalize_name_ensip15:...
def read_endgame_schema(endgame_version: str, warn=False) -> dict: endgame_schema_path = ((ENDGAME_SCHEMA_DIR / endgame_version) / 'endgame_ecs_mapping.json.gz') if (not endgame_schema_path.exists()): if warn: relative_path = endgame_schema_path.relative_to(ENDGAME_SCHEMA_DIR) pr...
def render(results, cmdenv, tdb): from ..formatting import RowFormat, ColumnFormat if ((not results) or (not results.rows)): raise TradeException('No data found') longestNamed = max(results.rows, key=(lambda row: len(row.station.name()))) longestNameLen = len(longestNamed.station.name()) row...
class TestEmptyPubtypes(unittest.TestCase): def test_empty_pubtypes(self): test_dir = os.path.join('test', 'testfiles_for_unittests') with open(os.path.join(test_dir, 'empty_pubtypes', 'main.elf'), 'rb') as f: elf = ELFFile(f) self.assertEqual(len(elf.get_dwarf_info().get_pub...
class DockPaneAction(TaskAction): object = Property(observe='dock_pane') dock_pane = Property(Instance(ITaskPane), observe='task') dock_pane_id = Str() _property def _get_dock_pane(self): if (self.task and (self.task.window is not None)): return self.task.window.get_dock_pane(sel...
class MPOLearner(acme.Learner): def __init__(self, policy_network: networks_lib.FeedForwardNetwork, critic_network: networks_lib.FeedForwardNetwork, dataset: Iterator[reverb.ReplaySample], random_key: jnp.ndarray, policy_optimizer: optax.GradientTransformation, critic_optimizer: optax.GradientTransformation, dual_o...
_group.command('show-latest-compatible') ('--package', '-p', help='Name of package') ('--stack_version', '-s', required=True, help='Rule stack version') def show_latest_compatible_version(package: str, stack_version: str) -> None: packages_manifest = None try: packages_manifest = load_integrations_manif...
class StickBugged(commands.Cog): __version__ = '0.0.1' __author__ = 'flare#0001' def format_help_for_context(self, ctx): pre_processed = super().format_help_for_context(ctx) return f'''{pre_processed} Cog Version: {self.__version__} Author: {self.__author__}''' def __init__(self, bot) ->...
('/url_api/', methods=['GET', 'POST']) _required def url_api(): if (not request.json): js = {'error': True, 'message': 'This endpoint only accepts JSON POST requests.'} resp = jsonify(js) resp.status_code = 200 resp.mimetype = 'application/json' return resp print('API Req...
class TestAWSUtil(unittest.TestCase): def test_convert_dict_to_list(self): expected_list = [{'Name': 'k1', 'Values': ['v1']}, {'Name': 'k2', 'Values': ['v2']}] self.assertEqual(expected_list, convert_dict_to_list(TEST_DICT, 'Name', 'Values')) self.assertEqual([], convert_dict_to_list({}, 'Na...
class Ledger_KeyStore(Hardware_KeyStore): hw_type = 'ledger' device = 'Ledger' handler: Optional['Ledger_Handler'] def __init__(self, data: Dict[(str, Any)], row: 'MasterKeyRow') -> None: Hardware_KeyStore.__init__(self, data, row) self.force_watching_only = False self.signing = ...
def start_north_omf_as_a_service(): def _start_north_omf_as_a_service(fledge_url, pi_host, pi_port, pi_db='Dianomic', auth_method='basic', pi_user=None, pi_pwd=None, north_plugin='OMF', service_name='NorthReadingsToPI_WebAPI', start=True, naming_scheme='Backward compatibility', default_af_location='fledge/room1/mac...
def _get_config_value(key: str, default: str='') -> str: input_path = os.environ.get(('FILE__' + key), None) if (input_path is not None): try: with open(input_path, 'r') as input_file: return input_file.read().strip() except IOError as e: logger.error(f'Un...
class Overrides(): override_choices: Dict[(str, Optional[Union[(str, List[str])]])] override_metadata: Dict[(str, OverrideMetadata)] append_group_defaults: List[GroupDefault] config_overrides: List[Override] known_choices: Dict[(str, Optional[str])] known_choices_per_group: Dict[(str, Set[str])]...
class DoraCheckpointSync(Callback): def __init__(self): self.xp = get_xp() def on_load_checkpoint(self, trainer, pl_module, checkpoint): history = checkpoint['dora_link_history'] self.xp.link.update_history(history) def on_save_checkpoint(self, trainer, pl_module, checkpoint): ...
('\n {{\n __m256 tmp = _mm256_hadd_ps({x_data}, {x_data});\n tmp = _mm256_hadd_ps(tmp, tmp);\n __m256 upper_bits = _mm256_castps128_ps256(_mm256_extractf128_ps(tmp, 1));\n tmp = _mm256_add_ps(tmp, upper_bits);\n *{result} += _mm256_cvtss_f32(tmp);\n }}\n ') def avx2_assoc_red...
def fortios_firewall(data, fos, check_mode): fos.do_member_operation('firewall', 'proxy-addrgrp') if data['firewall_proxy_addrgrp']: resp = firewall_proxy_addrgrp(data, fos, check_mode) else: fos._module.fail_json(msg=('missing task body: %s' % 'firewall_proxy_addrgrp')) if check_mode: ...
def render_matrix(jinja2_env, matrix_dir): logger.debug('Entered directory: %s.', matrix_dir) with open(os.path.join(matrix_dir, 'matrix.yml')) as f: try: matrix = yaml.load(f) except: logger.exception('Failed to load matrix from %s', matrix_dir) return pr...
def counter(): def decorator(func): decorator.count = 0 (func) _synthetic() def decorator_inner(self, *args, **kw): decorator.count = (decorator.count + 1) value = decorator.count return func(self, value) return decorator_inner return d...
class ACES20651(sRGB): BASE = 'xyz-d65' NAME = 'aces2065-1' SERIALIZE = ('--aces2065-1',) WHITE = (0.32168, 0.33767) CHANNELS = (Channel('r', 0.0, 65504.0, bound=True), Channel('g', 0.0, 65504.0, bound=True), Channel('b', 0.0, 65504.0, bound=True)) DYNAMIC_RANGE = 'hdr' def to_base(self, coo...
def extractMoonjellyfishtranslationWordpressCom(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,...
class FileDownloader(): def __init__(self, context: str='default'): self.download_handles = getDownloadHandles() if (context not in self.download_handles): raise RuntimeError(f'No configuration found for {context}') self.downloader = self.download_handles[context]() def downl...
def get_mime_for_text_file(filename: str) -> str: if (filename.lower() in SPECIAL_FILES): return SPECIAL_FILES[filename.lower()] suffix = Path(filename).suffix.lstrip('.').lower() if (not suffix): return 'text/plain' if (suffix in EXTENSION_TO_MIME): return EXTENSION_TO_MIME[suff...
def make_suggester(response_parser: Callable, labels: List[str], prompt_path: Path, prompt_example_class: Optional[PromptExample]=None, model: str='text-davinci-003', **kwargs) -> OpenAISuggester: if (('openai_api_key' not in kwargs) or ('openai_api_org' not in kwargs)): (api_key, api_org) = get_api_credent...
class OptionSeriesScatter3dPointEvents(Options): def click(self): return self._config_get(None) def click(self, value: Any): self._config(value, js_type=False) def drag(self): return self._config_get(None) def drag(self, value: Any): self._config(value, js_type=False) ...
def get_details(session): import json from flask_monitoringdashboard import loc with open((loc() + 'constants.json'), 'r') as f: constants = json.load(f) return {'link': config.link, 'dashboard-version': constants['version'], 'config-version': config.version, 'first-request': get_date_of_first_r...
class DetectWrongState(hass.Hass): def initialize(self): self.listen_state_handle_list = [] self.app_switch = self.args['app_switch'] try: self.entities_on = self.args['entities_on'].split(',') except KeyError: self.entities_on = [] try: se...
class OptionSeriesSunburstLabelStyle(Options): def fontSize(self): return self._config_get('0.8em') def fontSize(self, num: float): self._config(num, js_type=False) def fontWeight(self): return self._config_get('bold') def fontWeight(self, text: str): self._config(text, j...
def calcEholo_vert(image_coords: np.ndarray, tangents: np.ndarray, thresh: float=0.001): nimages = len(image_coords) tangents_perp = [None for _ in range(nimages)] findvertlist = [False for _ in range(nimages)] whileN = 0 while (whileN < 1000): whileN += 1 if all(findvertlist): ...
class BaseAttack(UserAction): def __init__(self, source, target, damage=1): self.source = source self.target = target self.damage = damage def apply_action(self): g = self.game (source, target) = (self.source, self.target) rst = g.process_action(LaunchGraze(target...
def _combine_results(*results, average=True): if (not results): return None elif (len(results) == 1): return results[0] combined = {k: 0 for k in KINDS} for result in results: for kind in KINDS: combined[kind] += result[kind] if average: for kind in KINDS:...
class AppModule(): def from_app(cls, app: App, import_name: str, name: str, template_folder: Optional[str], template_path: Optional[str], static_folder: Optional[str], static_path: Optional[str], url_prefix: Optional[str], hostname: Optional[str], cache: Optional[RouteCacheRule], root_path: Optional[str], pipeline:...
def download_test_datasets(force: bool): datasets_path = os.path.abspath('datasets') logging.info('Check datasets directory %s', datasets_path) if (not os.path.exists(datasets_path)): logging.info('Create datasets directory %s', datasets_path) os.makedirs(datasets_path) else: log...
class DominoesTest(unittest.TestCase): def test_empty_input_empty_output(self): input_dominoes = [] output_chain = can_chain(input_dominoes) self.assert_correct_chain(input_dominoes, output_chain) def test_singleton_input_singleton_output(self): input_dominoes = [(1, 1)] ...
class getOptions_result(): thrift_spec = None thrift_field_annotations = None thrift_struct_annotations = None __init__ = None def isUnion(): return False def read(self, iprot): if ((isinstance(iprot, TBinaryProtocol.TBinaryProtocolAccelerated) or (isinstance(iprot, THeaderProtoc...
class OptionXaxisPlotbandsLabel(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def rotation(self): return self._config_get(0) def rotation(self, num: float): self._config(num, js_type=False) d...
def test_root_mount(): app = Flask(__name__) admin = base.Admin(app, url='/') admin.add_view(MockView()) client = app.test_client() rv = client.get('/mockview/') assert (rv.data == b'Success!') with app.test_request_context('/'): rv = client.get(url_for('admin.static', filename='boot...
.usefixtures('use_tmpdir') def test_that_unicode_decode_error_is_localized_first_line(): with open('test.ert', 'ab') as f: f.write(b'\xff') f.write(bytes(dedent('\n QUEUE_OPTION DOCAL MAX_RUNNING 4\n STOP_LONG_RUNNING flase\n NUM_REALIZATIONS ...
class hello_failed_error_msg(error_msg): version = 4 type = 1 err_type = 0 def __init__(self, xid=None, code=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (code != None): self.code = code else: ...