code
stringlengths
281
23.7M
class OptionPlotoptionsPackedbubbleSonificationDefaultinstrumentoptionsMappingTremoloDepth(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...
class TestSerializeJson(): def client(self): class SomeResource(): async def on_get(self, req, resp): async def emitter(): (yield SSEvent(json={'foo': 'bar'})) (yield SSEvent(json={'bar': 'baz'})) resp.sse = emitter() ...
class NoAuthenticationClassesTests(TestCase): def test_permission_message_with_no_authentication_classes(self): class DummyPermission(permissions.BasePermission): message = 'Dummy permission message' def has_permission(self, request, view): return False reques...
_os(*metadata.platforms) def main(): masquerade = '/tmp/bash' masquerade2 = '/tmp/testmodify' tmp_file = f'{Path.home()}/Library/LaunchAgents/com.apple.test.plist' if (not Path(tmp_file).exists()): Path(tmp_file).write_text('test') common.copy_file('/bin/bash', masquerade) common.create_...
() ('path-source', type=click.Path(exists=True, file_okay=True)) ('--config', default=None, help='Path to the YAML configuration file (default: PATH_SOURCE/_config.yml)') ('--toc', default=None, help='Path to the Table of Contents YAML file (default: PATH_SOURCE/_toc.yml)') _context def sphinx(ctx, path_source, config,...
def get_notes_by_future_due_date() -> Dict[(str, List[SiacNote])]: conn = _get_connection() res = conn.execute(f"select * from notes where substr(reminder, 21, 10) >= '{utility.date.date_x_days_ago_stamp(DUE_NOTES_BOUNDARY)}'").fetchall() conn.close() res = _to_notes(res) d = dict() today = date...
('/directory', defaults={'path': ''}) ('/directory/<path:path>') def directory(path): sort_property = get_cookie_browse_sorting(path, 'text') (sort_fnc, sort_reverse) = browse_sortkey_reverse(sort_property) try: file = PlayableDirectory.from_urlpath(path) if file.is_directory: re...
def _warn_or_exception(value, cause=None): if (warnings_action == 'ignore'): pass elif (warnings_action == 'error'): if cause: raise MetaDataException(value) from cause else: raise MetaDataException(value) else: logging.warning(value)
class OptionPlotoptionsBarSonificationDefaultinstrumentoptionsMappingPitch(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('y') def mapTo(self, text: str)...
_blueprint.route('/project/new', methods=['GET', 'POST']) _required def new_project(): backend_plugins = anitya_plugins.load_plugins(Session) plg_names = [plugin.name for plugin in backend_plugins] version_plugins = anitya_plugins.load_plugins(Session, family='versions') version_plg_names = [plugin.name...
class SimpleSwitchController(ControllerBase): def __init__(self, req, link, data, **config): super(SimpleSwitchController, self).__init__(req, link, data, **config) self.simple_switch_app = data[simple_switch_instance_name] ('simpleswitch', url, methods=['GET'], requirements={'dpid': dpid_lib.DP...
class AutoscalingClient(NamespacedClient): _rewrite_parameters() def delete_autoscaling_policy(self, *, name: str, error_trace: t.Optional[bool]=None, filter_path: t.Optional[t.Union[(str, t.Sequence[str])]]=None, human: t.Optional[bool]=None, pretty: t.Optional[bool]=None) -> ObjectApiResponse[t.Any]: ...
class OptionSeriesScatter3dSonificationTracks(Options): def activeWhen(self) -> 'OptionSeriesScatter3dSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionSeriesScatter3dSonificationTracksActivewhen) def instrument(self): return self._config_get('piano') def instru...
def doExecutePluginCommand(cmdline): retvalue = False if (len(Settings.Tasks) < 1): return False for s in range(len(Settings.Tasks)): if ((type(Settings.Tasks[s]) != bool) and Settings.Tasks[s].enabled): try: retvalue = Settings.Tasks[s].plugin_write(cmdline) ...
def execmd(cmd, params=None, timeout=None): if (not re.search('^\\.?/', cmd)): cmd = get_cmd_path(cmd) if ((not cmd) or (not os.path.isfile(cmd))): raise Exception('Command not found') cmd = (([cmd] + params) if params else [cmd]) exe = CommandExecutor(cmd, stderr=True) (out, err) = ...
def create_readers(ffrom, patch, to_size): fpatch = BytesIO(patch) (data_pointers_blocks_present, code_pointers_blocks_present, data_pointers_header, code_pointers_header, from_data_offset, from_data_begin, from_data_end, from_code_begin, from_code_end) = unpack_pointers_header(fpatch) call0_header = Blocks...
class RoughViz(MixHtmlState.HtmlOverlayStates, Html.Html): requirements = ('rough-viz',) name = 'rough_viz' tag = 'div' _chart__type = 'Line' _option_cls = OptChartRoughViz.RoughVizLine builder_name = 'RvCharts' def __init__(self, page, width, height, html_code, options, profile): su...
def containerize_code(code_string): code_string = code_string.replace('your_openai_api_key_here', OPENAI_KEY) try: output_buffer = io.StringIO() with contextlib.redirect_stdout(output_buffer): exec(code_string, globals()) except Exception as e: (exc_type, exc_value, exc_t...
class MyGaussianBlur(ImageFilter.GaussianBlur): name = 'GaussianBlur' def __init__(self, size, radius=2, bounds=None): super().__init__() self.radius = radius self.bounds = bounds self.size = size def filter(self, image): print(1) if self.bounds: b...
class Switch(Html.Html): requirements = ('bootstrap', 'jquery') name = 'Switch Buttons' builder_name = 'HtmlSwitch' def __init__(self, page: primitives.PageModel, records: dict, color: str, width: types.SIZE_TYPE, height: types.SIZE_TYPE, html_code: str, options: dict, profile: types.PROFILE_TYPE, verbo...
class BallGroup(StrEnum): REDS = auto() COLORS = auto() def balls(self) -> Tuple[(str, ...)]: return _group_to_balls_dict[self] def get(cls, balls: Tuple[(str, ...)]) -> BallGroup: if (balls in _group_to_balls_dict): return _balls_to_group_dict[balls] if all(((ball in...
class TestActive(util.TestCase): def test_active(self): markup = '\n <div>\n <p>Some text <span id="1" class="foo:bar:foobar"> in a paragraph</span>.\n <a id="2" class="bar" href=" <a id="3">Placeholder text.</a>\n </p>\n </div>\n ' self.assert_select...
class OptionSeriesScatter3dOnpoint(Options): def connectorOptions(self) -> 'OptionSeriesScatter3dOnpointConnectoroptions': return self._config_sub_data('connectorOptions', OptionSeriesScatter3dOnpointConnectoroptions) def id(self): return self._config_get(None) def id(self, text: str): ...
def _extract_base_type(typed): if (hasattr(typed, '__args__') and (not isinstance(typed, _SpockVariadicGenericAlias))): name = _get_name_py_version(typed=typed) bracket_val = f'{name}[{_extract_base_type(typed.__args__[0])}]' return bracket_val else: bracket_value = _get_name_py_...
def ExportModel(sess, model_dir, input, output, assets): if os.path.isdir(model_dir): shutil.rmtree(model_dir) logging.info('Exporting trained model to %s', model_dir) saver = tf.train.Saver() model_exporter = exporter.Exporter(saver) signature = exporter.regression_signature(input_tensor=in...
def add_arguments_to_parser(parser: argparse.ArgumentParser): parser.add_argument('config', help='path to a compatible config .yaml file', nargs='+') parser.add_argument('--modes', nargs='+', default='all') parser.add_argument('--verbose', action='store_true', help='Enable debug logging') parser.add_arg...
('delete') ('--username', '-u', help='The username of the user.') ('--force', '-f', default=False, is_flag=True, help='Removes the user without asking for confirmation.') def delete_user(username, force): if (not username): username = click.prompt(click.style('Username', fg='magenta'), type=str, default=os....
class TestJoinImageName(unittest.TestCase): def test_simple(self): image_name = join_image_name('icons', 'red_ball.jpg') self.assertEqual(image_name, ':red_ball.jpg') def test_extension(self): image_name = join_image_name('icons', 'red_ball.png') self.assertEqual(image_name, ':re...
def download_s3(bucket: str, obj: str, temp_path: str, s3_session: BaseClient, download_config: S3DownloadConfig) -> str: try: extra_options = {k: v for (k, v) in attr.asdict(download_config).items() if (v is not None)} file_size = s3_session.head_object(Bucket=bucket, Key=obj, **extra_options)['Con...
def extractRandnovelstlsamatchateaWordpressCom(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, ...
def test_llm_logs_default_null_handler(nlp: Language, capsys: pytest.CaptureFixture): nlp('This is a test') captured = capsys.readouterr() assert (captured.out == '') assert (captured.err == '') stream_handler = logging.StreamHandler(sys.stdout) spacy_llm.logger.addHandler(stream_handler) sp...
class SimpleVizGroup(lg.Group): INPUT = lg.Topic(HeatMapMessage) HEATMAP: HeatMap COLOR_MAP: ColorMap WINDOW: Window def setup(self) -> None: self.HEATMAP.configure(HeatMapConfig(data='data', channel_map='channel_map', shape=(32, 32), external_timer=True)) self.COLOR_MAP.configure(Co...
class OptionSeriesAreasplineSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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, ...
def check_configs(fips_dir, proj_dir): log.colored(log.YELLOW, '=== configs:') configs = config.load(fips_dir, proj_dir, '*') num_errors = 0 for cfg in configs: log.colored(log.BLUE, cfg['name']) (valid, errors) = config.check_config_valid(fips_dir, proj_dir, cfg) if valid: ...
class DispatchProxyServiceStub(object): def __init__(self, channel): self.GetDispatch = channel.unary_unary('/DispatchProxyService/GetDispatch', request_serializer=koapy_dot_common_dot_DispatchProxyService__pb2.GetDispatchRequest.SerializeToString, response_deserializer=koapy_dot_common_dot_DispatchProxySer...
def test_task_set_ulimits_exclusively(task_definition): assert (len(task_definition.containers[0]['ulimits']) == 1) assert ('memlock' == task_definition.containers[0]['ulimits'][0]['name']) task_definition.set_ulimits(((u'webserver', u'cpu', 80, 85),), exclusive=True) assert (len(task_definition.contain...
def html_template_loader(file_path: str, values: Optional[dict]=None, new_var_format: Optional[str]=None, ref_expr: Optional[str]=None, directives: Optional[dict]=None) -> dict: if ((values is not None) and (new_var_format is not None)): raise ValueError('Both values and var_format cannot be defined') h...
class OptionSeriesPolygonSonificationContexttracksMappingHighpassResonance(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 FormatPTests(unittest.TestCase): def test_escaping(self): assert (util.formatp('[razamba \\[ mabe \\]]') == 'razamba [ mabe ]') def test_numerical(self): assert (util.formatp('[{t} - [schmuh {x}]]', t=1, x=2) == '1 - schmuh 2') assert (util.formatp('[{t} - [schmuh {x}]]', t=1, x=0)...
() ('username') def dump_user(username): user = models.User.query.filter((models.User.username == username)).first() if (not user): print('There is no user named {0}.'.format(username)) return 1 dumper = users_logic.UserDataDumper(user) print(dumper.dumps(pretty=True))
class BackupProcess(FledgeProcess): _MODULE_NAME = 'fledge_backup_sqlite_process' _BACKUP_FILE_NAME_PREFIX = 'fledge_backup_' _MESSAGES_LIST = {'i000001': 'Execution started.', 'i000002': 'Execution completed.', 'e000000': 'general error', 'e000001': 'cannot initialize the logger - error details |{0}|', 'e0...
def validate_fides_key_suitability(names: ResultProxy, table_name: str) -> None: for row in names: name: str = row['name'].strip(' ').replace(' ', '_') try: FidesKey.validate(name) except FidesValidationError as exc: raise Exception(f"Cannot auto-migrate, adjust exist...
def test_providers_with_default_value(config): config.set_default({'a': {'b': {'c': 1, 'd': 2}}}) a = config.a ab = config.a.b abc = config.a.b.c abd = config.a.b.d assert (a() == {'b': {'c': 1, 'd': 2}}) assert (ab() == {'c': 1, 'd': 2}) assert (abc() == 1) assert (abd() == 2)
def load_regulations(): es_client = create_es_client() if es_client.indices.exists(index=AO_ALIAS): eregs_api = env.get_credential('FEC_EREGS_API', '') if (not eregs_api): logger.error('Regulations could not be loaded, environment variable FEC_EREGS_API not set.') return ...
def extractWelcometoashfordWordpressCom(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, t...
.integration class TestLoadDefaultTaxonomy(): async def test_add_to_default_taxonomy(self, monkeypatch: pytest.MonkeyPatch, test_config: FidesConfig, data_category: DataCategory, async_session: AsyncSession) -> None: result = _api.get(test_config.cli.server_url, 'data_category', data_category.fides_key, hea...
def gen_fill_string(out): out.write("\n\n/**\n * The increment to use on values inside a string\n */\n#define OF_TEST_STR_INCR 3\n\n/**\n * Fill in a buffer with incrementing values starting\n * at the given offset with the given value\n * buf The buffer to fill\n * value The value to use for data\n * len The nu...
def test_encode_partial_keywords(): df = pd.DataFrame({'var_A': (((((((['A'] * 5) + (['B'] * 11)) + (['C'] * 4)) + (['D'] * 9)) + (['E'] * 2)) + (['F'] * 2)) + (['G'] * 7)), 'var_B': (((((((['A'] * 11) + (['B'] * 7)) + (['C'] * 4)) + (['D'] * 9)) + (['E'] * 2)) + (['F'] * 2)) + (['G'] * 5)), 'var_C': (((((((['A'] *...
('bodhi.server.models.tag_update_builds_task', mock.Mock()) ('bodhi.server.models.work_on_bugs_task', mock.Mock()) ('bodhi.server.models.fetch_test_cases_task', mock.Mock()) class TestUpdateVersionHash(BasePyTestCase): def test_version_hash(self): update = model.Update.query.first() initial_expected...
.parametrize(('global_size', 'flat_local_size', 'expected_local_size'), vals_find_local_size, ids=[str(x[:2]) for x in vals_find_local_size]) def test_find_local_size(global_size, flat_local_size, expected_local_size): local_size = vsize.find_local_size(global_size, flat_local_size) assert (product(local_size) ...
def get_images(html, url): js_url = re.search('src="([^"]+base64\\.js)"', html).group(1) js_content = grabhtml(urljoin(url, js_url)) data = re.search('(var chapterTree=.+?)</script>', html, re.DOTALL).group(1) match = re.search('window\\["\\\\x65\\\\x76\\\\x61\\\\x6c"\\](.+?)</script>', html, re.DOTALL)...
class OptionPlotoptionsTreegraphSonificationContexttracksMappingTime(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 BigQueryClient(object): def __init__(self, global_configs, **kwargs): (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = Big...
class OptionPlotoptionsArcdiagramSonificationTracks(Options): def activeWhen(self) -> 'OptionPlotoptionsArcdiagramSonificationTracksActivewhen': return self._config_sub_data('activeWhen', OptionPlotoptionsArcdiagramSonificationTracksActivewhen) def instrument(self): return self._config_get('pian...
class zip_longest(zip): __slots__ = ('fillvalue',) __doc__ = getattr(_coconut.zip_longest, '__doc__', 'Version of zip that fills in missing values with fillvalue.') def __new__(cls, *iterables, **kwargs): self = zip.__new__(cls, *iterables, strict=False) self.fillvalue = kwargs.pop('fillvalu...
def test_block_inference_changing_shape(): model = ChangingShapeModel() queries = ([model.K()] + [model.component(j) for j in range(3)]) compositional = bm.CompositionalInference(nnc_compile=False) with pytest.raises(RuntimeError): compositional.infer(queries, {}, num_samples=10, num_chains=1)
_exception def _vm_backup_deleted_last_snapshot_names(data): deleted_last_snapshot_names = data.get('deleted_last_snapshot_names', None) if deleted_last_snapshot_names: bkp_ids = [b[3:] for b in deleted_last_snapshot_names if b.startswith('is-')] Backup.objects.filter(id__in=bkp_ids).update(last...
def test_validate_discount_code_require_same_event_id(db): (discount, tickets) = _create_discount_code(db) discount.event = EventFactoryBasic() db.session.commit() with pytest.raises(UnprocessableEntityError, match='Invalid Discount Code'): discount.validate(event_id='40', tickets=tickets) w...
class TestNXActionResubmitTable(unittest.TestCase): type_ = {'buf': b'\xff\xff', 'val': ofproto.OFPAT_VENDOR} len_ = {'buf': b'\x00\x10', 'val': ofproto.NX_ACTION_RESUBMIT_SIZE} vendor = {'buf': b'\x00\x00# ', 'val': 8992} subtype = {'buf': b'\x00\x0e', 'val': 14} in_port = {'buf': b'\nL', 'val': 26...
def _start_watchdog_for_metafile(app): class Handler(FileSystemEventHandler): def on_any_event(self, event): if (event.event_type == 'modified'): _set_assets_details(app) logger.debug('Assets metadata reloaded') observer = Observer() observer.schedule(Hand...
class OptionPlotoptionsOrganizationSonificationTracksMappingTremoloSpeed(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 construct_graph(number: int) -> (List[BasicBlock], ControlFlowGraph): defined_instructions = [instructions.Phi(expressions.Variable('v', Integer.int32_t(), 0), [expressions.Variable('v', Integer.int32_t(), 1), expressions.Variable('v', Integer.int32_t(), 2)]), instructions.Assignment(expressions.Variable('v', I...
def parse_args(clp): options = clp['ap'].parse_args() if (options.version or options.include_version): print(FULL_NAME) if options.version: sys.exit(0) if ((not options.brief) and (sys.stdout.encoding.lower() != 'utf-8')): print('WARNING: It looks like your environment is...
def generate_header(args): header = 'Auto-generated on {} by {}'.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), sys.argv[0]) args_str = pprint.pformat(vars(args)) arg_lines = args_str.split('\n') lines = [(60 * '='), header, (60 * '-'), *arg_lines, (60 * '=')] return '\n'.join((('# ' ...
.django_db def test_new_awards_failures(client, monkeypatch, add_award_recipients, elasticsearch_award_index): setup_elasticsearch_test(monkeypatch, elasticsearch_award_index) test_payload = {'group': 'quarter', 'filters': {'time_period': [{'start_date': '2008-10-01', 'end_date': '2010-09-30'}], 'recipient_id':...
def extractWwwNovelsluttyverseCom(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 Angular(node.Node): def __init__(self, root_path: str, name: str=None, page=None, app_folder: str=node.APP_FOLDER, assets_folder: str=node.ASSET_FOLDER): super(Angular, self).__init__(root_path, name, page) (self._app_folder, self._app_asset, self.__clis) = (app_folder, assets_folder, None) ...
_blueprint.route('/settings/tokens/new', methods=('POST',)) _required def new_token(): form = anitya.forms.TokenForm() if form.validate_on_submit(): token = models.ApiToken(user=flask.g.user, description=form.description.data) Session.add(token) Session.commit() return flask.redi...
def draw_arrow(box, tip, orientation='right', arrow_type='', style=None, tooltip=None): (x, y, dx, dy) = box if (orientation == 'right'): arrow = ((x, y), (((x + dx) - tip), y), ((x + dx), (y + (dy / 2))), (((x + dx) - tip), (y + dy)), (x, (y + dy))) elif (orientation == 'left'): arrow = ((x...
class OptionSeriesTreemapDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(text, js_...
def _get_new_items() -> List[ItemCode]: new_items = frappe.db.sql(f''' SELECT item.item_code FROM tabItem item LEFT JOIN `tabEcommerce Item` ei ON ei.erpnext_item_code = item.item_code WHERE ei.erpnext_item_code is NULL AND item.{ITEM_SYNC_CHECKBOX} = 1 ''') return [item[0] for item in n...
class OptionSeriesColumnrangeOnpointConnectoroptions(Options): def dashstyle(self): return self._config_get(None) def dashstyle(self, text: str): self._config(text, js_type=False) def stroke(self): return self._config_get(None) def stroke(self, text: str): self._config(te...
def lambda_handler(event, context): sample_words_response = {} all_lists = vocab_list_service.get_vocab_lists() for list in all_lists: sample_words_response[list['list_id']] = [] all_words = list_word_service.get_words_in_list(list['list_id']) for i in range(5): sample_wo...
def _children_from_attrs(cur, n, *args) -> Iterable[Node]: for attr in args: children = getattr(n, attr) if isinstance(children, list): for i in range(len(children)): (yield cur._child_node(attr, i)) else: (yield cur._child_node(attr, None))
def extractShallotnoodleWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('surrounded mob wants to quietly withdraw', 'surrounded mob wants to quietly withdraw', 'tra...
class LoopJS(): integrate = undefined integrate_tornado = undefined integrate_pyqt4 = undefined integrate_pyside = undefined _integrate_qt = undefined _thread_match = undefined def __init__(self): self._active_components = [] self.reset() def _call_soon_func(self, func): ...
class OptionPlotoptionsGaugeLabelStyle(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,...
class Namespace(): __slots__ = ('_attributes', '_arg_shapes', 'default_geometry_name', '_fixed_lengths', '_fallback_length', '_functions') _re_assign = re.compile('^([a-zA-Z--][a-zA-Z--0-9]*)(_[a-z]+)?$') _default_functions = dict(opposite=function.opposite, sin=numpy.sin, cos=numpy.cos, tan=numpy.tan, sinh...
('cuda.reshape.func_call') ('cuda.flatten.func_call') def reshape_gen_function_call(func_attrs, indent=' '): func_name = ('ait_' + func_attrs['name']) input_names = [] if _is_intvar(func_attrs): for (i, inp) in enumerate(func_attrs['inputs']): if (i == 0): continue ...
def test_substitute_loop_node_no_parent(): asgraph = AbstractSyntaxInterface() code_node = asgraph._add_code_node([Assignment(var('a'), const(2))]) loop = asgraph.add_endless_loop_with_body(code_node) replacement_loop = asgraph.factory.create_while_loop_node(condition=LogicCondition.initialize_symbol('a...
((detect_target().name() == 'rocm'), 'Not supported by ROCM.') class SplitGetItemTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(SplitGetItemTestCase, self).__init__(*args, **kwargs) self._test_id = 0 def _test_split_getitem(self, batch_size=(1, 3), X_shape=(16, 32), spli...
class TestDataBox(unittest.TestCase, UnittestTools): def setUp(self): xs = np.arange(0, 5) ys = np.arange(0, 5) index = GridDataSource(xdata=xs, ydata=ys, sort_order=('ascending', 'ascending')) index_mapper = GridMapper(range=DataRange2D(index)) color_source = ImageData(data=...
class Glyph(object): def __init__(self, data=b''): if (not data): self.numberOfContours = 0 return self.data = data def compact(self, glyfTable, recalcBBoxes=True): data = self.compile(glyfTable, recalcBBoxes) self.__dict__.clear() self.data = data...
class OptionPlotoptionsWindbarbSonificationTracksMappingTremoloSpeed(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 get_identity(identity): if isinstance(identity, AnonymousUser): return (identity, None) if isinstance(identity, get_user_model()): return (identity, None) elif isinstance(identity, Group): return (None, identity) else: raise NotUserNorGroup('User/AnonymousUser or Grou...
class ClassificationInstance(Base): __tablename__ = 'cls_classification_instance' status = Column(Text) organization_key = Column(Text) dataset_key = Column(Text) dataset_name = Column(Text) target = Column(Text) type = Column(Text) created_at = Column(DateTime(timezone=True), server_def...
class Constraint(Validator, PhantomType): def __init__(self, for_type, predicates): self.type = for_type self.predicates = predicates def validate_instance(self, inst, sampler=None): self.type.validate_instance(inst, sampler) for p in self.predicates: if (not p(inst))...
class FuncCall(object): def pcall(obj, method_name, *args): tracer.debug('pcall: trying to call [%s]', method_name) if (not hasattr(obj, method_name)): tracer.debug('pcall: method [%s] does not exist.', method_name) return tracer.debug('pcall: calling method [%s]', me...
class Migration(migrations.Migration): dependencies = [('financial_activities', '0003_financialaccountsbyprogramactivityobjectclass_disaster_emergency_fund')] operations = [migrations.RemoveField(model_name='financialaccountsbyprogramactivityobjectclass', name='final_of_fy'), migrations.RunSQL(sql=[f"{Path('usa...
_nx_subtype(ofproto.NXT_PACKET_IN) class NXTPacketIn(NiciraHeader): def __init__(self, datapath, buffer_id, total_len, reason, table_id, cookie, match_len, match, frame): super(NXTPacketIn, self).__init__(datapath, ofproto.NXT_PACKET_IN) self.buffer_id = buffer_id self.total_len = total_len ...
def kinetic3d_41(ax, da, A, bx, db, B): result = numpy.zeros((15, 3), dtype=float) x0 = (2.0 * ax) x1 = (((2.0 * bx) + x0) ** (- 1.0)) x2 = (- ax) x3 = ((ax + bx) ** (- 1.0)) x4 = ((- x3) * ((ax * A[0]) + (bx * B[0]))) x5 = ((- x4) - A[0]) x6 = (x5 ** 2) x7 = (2.0 * (ax ** 2)) x8...
def initialize_encoder(encoder_or_encoder_class: Union[(Type[Encoder], Encoder, str)], schema: AbstractSchemaNode, **kwargs: Any) -> Encoder: if isinstance(encoder_or_encoder_class, str): encoder_name = encoder_or_encoder_class.lower() if (encoder_name not in _ENCODER_REGISTRY): raise Va...
class OptionPlotoptionsPyramid3dPointEvents(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...
class SlowImportWarningMixin(ColorFormatterMixin): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) if (self.import_secs and (self.import_secs > 1) and self._import_secs_warn): self.print_yellow(('Warning: Importing test modules alone took %.1fs! T...
def change_dir(): if (os.path.exists('config.json') or ('init' in sys.argv)): return dir_path_file = '/etc/frappe_bench_dir' if os.path.exists(dir_path_file): with open(dir_path_file) as f: dir_path = f.read().strip() if os.path.exists(dir_path): os.chdir(dir_...
('os.symlink') .object(full_docker.Benchmark, 'run_image') .object(full_docker.Benchmark, 'execute_benchmark') .object(docker_image.DockerImage, 'pull_image') .object(source_manager.SourceManager, 'have_build_options') .object(source_manager.SourceManager, 'get_envoy_hashes_for_benchmark') def test_execute_dockerized_b...
class TestNamespaceAllowedAndDefaultVersion(): def test_no_namespace_without_default(self): class FakeResolverMatch(): namespace = None scheme = versioning.NamespaceVersioning view = AllowedVersionsView.as_view(versioning_class=scheme) request = factory.get('/endpoint/') ...
_test def test_producer_and_consumer() -> None: stream_name = random_string(length=RANDOM_ID_LENGTH) stream_interface = register_stream(name=stream_name, message_type=MyMessage) received_messages = [] with Producer(stream_interface=stream_interface) as producer: def callback(params: LabgraphCall...
class DMLLoss(nn.Layer): def __init__(self, act=None, use_log=False): super().__init__() if (act is not None): assert (act in ['softmax', 'sigmoid']) if (act == 'softmax'): self.act = nn.Softmax(axis=(- 1)) elif (act == 'sigmoid'): self.act = nn.Si...
class DaapConnection(): def __init__(self, name, server, port, user_agent): if ((':' in server) and (server[0] != '[')): server = (('[' + server) + ']') self.all = [] self.session = None self.connected = False self.tracks = None self.server = server ...