code
stringlengths
281
23.7M
def test_serendipity_biharmonic(): sp = {'snes_type': 'ksponly', 'ksp_type': 'preonly', 'pc_type': 'lu', 'pc_factor_mat_solver_type': 'mumps', 'mat_mumps_icntl_14': 200} def error(N): mesh = UnitSquareMesh(N, N, quadrilateral=True) degree = 2 V = FunctionSpace(mesh, 'S', degree) ...
class Image(HasTraits): filename = File(exists=True) sample_id = Str() operator = Str('N/A') date_acquired = Date() scan_size = Tuple(Float, Float) scan_width = Property(Float, depends_on='scan_size') scan_height = Property(Float, depends_on='scan_size') image = Array(shape=(None, None),...
def test_preserve_remembers_exception(app, client): app.debug = True errors = [] ('/fail') def fail_func(): (1 // 0) ('/success') def success_func(): return 'Okay' _request def teardown_handler(exc): errors.append(exc) with pytest.raises(ZeroDivisionError): ...
class PrometheusSerializer(Serializer): def encode(msg: Message) -> bytes: msg = cast(PrometheusMessage, msg) message_pb = ProtobufMessage() dialogue_message_pb = DialogueMessage() prometheus_msg = prometheus_pb2.PrometheusMessage() dialogue_message_pb.message_id = msg.messag...
class EvAdventureRollEngineTest(BaseEvenniaTest): def setUp(self): super().setUp() self.roll_engine = rules.EvAdventureRollEngine() ('evennia.contrib.tutorials.evadventure.rules.randint') def test_roll(self, mock_randint): mock_randint.return_value = 8 self.assertEqual(self.r...
class Comment(BaseObject): def __init__(self, api=None, author_id=None, body=None, created_at=None, html_url=None, id=None, locale=None, source_id=None, source_type=None, updated_at=None, url=None, vote_count=None, vote_sum=None, **kwargs): self.api = api self.author_id = author_id self.body...
def be_distance(t1, t2, support, attr1, attr2): def _get_leaves_paths(t, attr, support): leaves = list(t.leaves()) leave_branches = set() for n in leaves: if n.is_root: continue movingnode = n length = 0 while (not movingnode.is...
class TestOFPQueuePropMinRate(unittest.TestCase): rate = {'buf': b'\x00\x01', 'val': ofproto.OFPQT_MIN_RATE} len = {'buf': b'\x00\x10', 'val': ofproto.OFP_QUEUE_PROP_MIN_RATE_SIZE} zfill = (b'\x00' * 6) buf = (rate['buf'] + zfill) c = OFPQueuePropMinRate(rate['val']) def setUp(self): pas...
class ThreadedCamera(): def __init__(self, api_key, host, port): self.active = True self.results = [] self.capture = cv2.VideoCapture(0) self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 2) compre_face: CompreFace = CompreFace(host, port, {'limit': 0, 'det_prob_threshold': 0.8, 'pred...
class AS4C128M16(DDR3Module): nbanks = 8 nrows = 16384 ncols = 1024 technology_timings = _TechnologyTimings(tREFI=(.0 / 8192), tWTR=(4, 7.5), tCCD=(4, None), tRRD=(4, 6), tZQCS=(64, 80)) speedgrade_timings = {'1600': _SpeedgradeTimings(tRP=13.75, tRCD=13.75, tWR=13.75, tRFC=(160, None), tFAW=(None, ...
def test_complex(create_very_broken_file, tmpdir): path = os.path.join(str(tmpdir), 'complex.dlis') create_very_broken_file(path) errorhandler = ErrorHandler() with pytest.raises(RuntimeError): with dlis.load(path, error_handler=errorhandler) as (f, *_): pass errorhandler.critica...
def recon_handler(user_name=None, email=None): if user_name: startTime = time.time() ghuser = github_recon(user_name) print('git', (startTime - time.time())) startTime = time.time() twit = twitter_recon(user_name) print('twit', (startTime - time.time())) start...
class MemoryAnalysisTestCase(unittest.TestCase): memory_analyzer: MemoryAnalysis def setUpClass(cls) -> None: memory_events_path: str = 'tests/data/memory_analysis/memory_timeline.raw.gz' cls.memory_analyzer = MemoryAnalysis(path=memory_events_path) def test_process_raw_events(self): ...
def get_activation_context(editor: sublime.View, pos: int) -> Config: if editor.match_selector(pos, 'meta.attribute-with-value.style string'): return create_activation_context(editor, pos, {'name': CSSAbbreviationScope.Property}, True) syntax_name = syntax.from_pos(editor, pos) if syntax.is_css(synt...
class CubicGlyfTest(): def test_cubic_simple(self): spen = TTGlyphPen(None) spen.moveTo((0, 0)) spen.curveTo((0, 1), (1, 1), (1, 0)) spen.closePath() ppen = TTGlyphPointPen(None) ppen.beginPath() ppen.addPoint((0, 0), 'line') ppen.addPoint((0, 1)) ...
class Measurement(BasicObject): attributes = {'PHASE': utils.scalar, 'MEASUREMENT-SOURCE': utils.scalar, 'TYPE': utils.scalar, 'DIMENSION': utils.reverse, 'AXIS': utils.reverse, 'MEASUREMENT': utils.vector, 'SAMPLE-COUNT': utils.scalar, 'MAXIMUM-DEVIATION': utils.vector, 'STANDARD-DEVIATION': utils.vector, 'BEGIN-T...
_production class Term(ASTNode): implicit_pushdown = inherited(implicit_pushdown=True) depth = inherited() index = inherited() index2 = synthesized() value = synthesized() type = synthesized() subtree_depth = synthesized() string = synthesized() summary = synthesized() def summar...
def merge_subsets(a: Dict[(str, Any)], b: Dict[(str, Any)]) -> None: for key in b: if (key not in a): a[key] = b[key] elif (('fields' in a[key]) and ('fields' in b[key])): if (b[key]['fields'] == '*'): a[key]['fields'] = '*' elif (isinstance(a[key]...
def test_export_incompatible_runtime_config(kubeflow_pipelines_runtime_instance, airflow_runtime_instance): runner = CliRunner() pipeline_file = 'kubeflow_pipelines.pipeline' p = (((Path(__file__).parent / 'resources') / 'pipelines') / f'{pipeline_file}') assert p.is_file() result = runner.invoke(pi...
class ShutterReleaseLever(): def __init__(self, exposure_control_system=None): self.exposure_control_system = exposure_control_system def depress(self): if (not self.exposure_control_system): return self.exposure_control_system.exposure_level_lever.activate() self.exp...
() def flask_app(): app = Flask(__name__) ('/an-error/', methods=['GET', 'POST']) def an_error(): raise ValueError('hello world') ('/users/', methods=['GET', 'POST']) def users(): response = make_response(render_template('users.html', users=['Ron', 'Rasmus'])) response.header...
def naics_data(db): baker.make(NAICS, code='212113', description='Anthracite Mining') baker.make(NAICS, code='212112', description='Bituminous Coal Underground Mining') baker.make(NAICS, code='213111', description='Drilling Oil and Gas Wells') baker.make(NAICS, code='111331', description='Apple Orchards...
class BasePlaylistPanelMixin(GObject.GObject): _gsignals_ = {'playlist-selected': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'tracks-selected': (GObject.SignalFlags.RUN_LAST, None, (object,)), 'append-items': (GObject.SignalFlags.RUN_LAST, None, (object, bool)), 'replace-items': (GObject.SignalFlags.RUN_LAST,...
class SplineCV(BaseGridder): def __init__(self, mindists=None, dampings=(1e-10, 1e-05, 0.1), force_coords=None, engine='auto', cv=None, client=None, delayed=False, scoring=None): super().__init__() self.dampings = dampings if (mindists is None): self.mindists = [0] else: ...
def _write_tf_record(tasks, output_file, reverse_class_mapping_dict): writer = tf.python_io.TFRecordWriter(output_file) counter = 0 for task in tasks: if (task['answer'] == 'accept'): tf_example = create_a_tf_example(task, reverse_class_mapping_dict) writer.write(tf_example.S...
def lang_emoji(lang): if (lang == 'en'): emoji = '' elif (lang == 'de'): emoji = '' elif (lang == 'es'): emoji = '' elif (lang == 'se'): emoji = '' elif (lang == 'no'): emoji = '' elif (lang == 'ru'): emoji = '' elif (lang == 'ua'): emo...
('thermoanalysis') .parametrize('id_, dG_ref', ((24, 0.), (63, 0.), (84, 0.))) def test_irc_h5(this_dir, id_, dG_ref): h5 = (this_dir / f'irc_000.0{id_}.orca.h5') geom = geom_from_hessian(h5) thermo = geom.get_thermoanalysis() print_thermoanalysis(thermo) assert (thermo.dG == pytest.approx(dG_ref, a...
class AggregatedExceptions(Exception): def __init__(self) -> None: super(AggregatedExceptions, self).__init__() self.exceptions: List[BaseException] = [] def append_exception(self, exception: BaseException) -> None: if isinstance(exception, AggregatedExceptions): self.excepti...
class QCEngine(Calculator): def __init__(self, program, model, keywords=None, connectivity=None, bond_order=1, **kwargs): super().__init__(**kwargs) self.program = program self.model = model if (keywords is None): keywords = dict() self.keywords = dict(keywords) ...
_on_exception class TestMain(): def test_should_fail_if_no_files_were_found(self, tmp_path: Path, sample_layout_document: SampleLayoutDocument, fulltext_models_mock: MockFullTextModels): configure_fulltext_models_mock_with_sample_document(fulltext_models_mock, sample_layout_document) output_path = (...
class ListenerFactory(): def load_all(cls, ir: 'IR', aconf: Config) -> None: amod = ir.ambassador_module listeners = aconf.get_config('listeners') if listeners: for config in listeners.values(): ir.logger.debug(('ListenerFactory: creating Listener for %s' % repr(c...
class OptionPlotoptionsColumnStatesHover(Options): def animation(self) -> 'OptionPlotoptionsColumnStatesHoverAnimation': return self._config_sub_data('animation', OptionPlotoptionsColumnStatesHoverAnimation) def borderColor(self): return self._config_get(None) def borderColor(self, text: str...
def redox_result_to_qcdata(redox_result): geom = redox_result.geom_gas H = geom.eckart_projection(geom.mass_weigh_hessian(redox_result.hessian_gas)) (w, v) = np.linalg.eigh(H) nus = eigval_to_wavenumber(w) thermo_dict = {'masses': geom.masses, 'vibfreqs': nus, 'coords3d': geom.coords3d, 'energy': re...
def _map_privacy_request(privacy_request: PrivacyRequest) -> Dict[(str, Any)]: request_data = {} request_data['id'] = privacy_request.id action_type: Optional[ActionType] = privacy_request.policy.get_action_type() if action_type: request_data['type'] = action_type.value identity: Identity = ...
class OptionSeriesVariwideLabelStyle(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...
class DockLayout(LayoutItem): left = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter)) right = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter)) top = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter)) bottom = Union(Instance(PaneItem), Instance(Tabbed), Instance...
def create_embed_relu_relu_softmax(depth, width, vector_length): with Model.define_operators({'>>': chain}): model = (strings2arrays() >> with_array(((((HashEmbed(width, vector_length, column=0) >> expand_window(window_size=1)) >> Relu(width, (width * 3))) >> Relu(width, width)) >> Softmax(17, width)))) ...
def extractYuukouUs(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 tagmap: ...
def test_default_integer_argument(): integer = IntegerArgument() validation_status = integer.validate('45') assert validation_status assert (validation_status.value() == '45') assert (validation_status.message() == '') validation_status = integer.validate('-45') assert validation_status ...
() def patch_module_device(monkeypatch, calibration_raw, capture_factory): class ColorControl(): mode: int value: int class DeviceHandle(): def __init__(self, device_id: int): self._meta: DeviceMeta = DEVICE_METAS[device_id] self._opened = True self._c...
(eq=False) class OSMNode(Tagged): id_: int coordinates: np.ndarray visible: Optional[str] = None changeset: Optional[str] = None timestamp: Optional[datetime] = None user: Optional[str] = None uid: Optional[str] = None def from_xml_structure(cls, element: Element) -> 'OSMNode': a...
def config_get_value(args): with open(get_configuration_file_path(), 'r') as f: yaml_config = yaml.load(f, Loader=yaml.FullLoader) if (args.option not in yaml_config): raise SystemExit(f'The option [{args.option}] is not found in config.') value = yaml_config[args.option] ...
class CubeTable(QWidget): ps_color_changed = pyqtSignal(bool) ps_history_backup = pyqtSignal(bool) def __init__(self, wget, args): super().__init__(wget) self.setAttribute(Qt.WA_AcceptTouchEvents) self._args = args self._updated_colors = False self.setMinimumSize(120,...
def get_tracks(server, username, fromuts, touts, startpage=1, sleep_func=time.sleep, tracktype='recenttracks'): page = startpage response = connect_server(server, username, page, fromuts, touts, sleep_func, tracktype) totalpages = get_pageinfo(response, tracktype) if (startpage > totalpages): ra...
def test(): from instakit.utils.static import asset from instakit.utils.mode import Mode from clu.predicates import isslotted image_paths = list(map((lambda image_file: asset.path('img', image_file)), asset.listfiles('img'))) image_inputs = list(map((lambda image_path: Mode.RGB.open(image_path)), im...
class OptionSeriesPyramidSonificationTracksMappingTremoloDepth(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...
class OptionPlotoptionsOrganizationLevels(Options): def borderColor(self): return self._config_get(None) def borderColor(self, text: str): self._config(text, js_type=False) def borderWidth(self): return self._config_get(None) def borderWidth(self, num: float): self._confi...
def test_proxy_object_is_returned_from_calls(accounts, tester): addr = accounts[1] value = ['blahblah', addr, ['yesyesyes', '0x1234']] tester.setTuple(value) with brownie.multicall: ret_val = tester.getTuple(addr) assert (inspect.getattr_static(ret_val, '__wrapped__') != value) a...
def create_osmocore_logging_header(timestamp=datetime.datetime.now(), process_name='', pid=0, level=0, subsys_name='', filename='', line_number=0): if (type(process_name) == str): process_name = process_name.encode('utf-8') if (type(subsys_name) == str): subsys_name = subsys_name.encode('utf-8')...
class Border(): def __init__(self, leaf): self.file = Projection.leaf_to_string(leaf, 'File') self.filetype = str.upper(Projection.leaf_to_string(leaf, 'Type', 'shp')) self.draw = Projection.leaf_to_bool(leaf, 'Draw', False) self.encoding = Projection.leaf_to_string(leaf, 'Encoding',...
def fortios_log_fortianalyzer_cloud(data, fos): fos.do_member_operation('log.fortianalyzer-cloud', 'override-filter') if data['log_fortianalyzer_cloud_override_filter']: resp = log_fortianalyzer_cloud_override_filter(data, fos) else: fos._module.fail_json(msg=('missing task body: %s' % 'log_...
def fixReleasePacket(data): expect = ['srcname', 'series', 'vol', 'chp', 'published', 'itemurl', 'postfix', 'author', 'tl_type'] maybe = ['match_author', 'loose_match', 'prefix_match'] assert (len(expect) <= len(data)), ("Invalid number of items in release packet! Expected: '%s', received '%s'" % (expect, l...
class AttachableTest(QuickbooksTestCase): def setUp(self): super(AttachableTest, self).setUp() self.time = datetime.now() def test_create_note(self): attachable = Attachable() vendor = Vendor.all(max_results=1, qb=self.qb_client)[0] attachable_ref = AttachableRef() ...
def test_reward_monitoring(): env = build_dummy_maze_env() env = MazeEnvMonitoringWrapper.wrap(env, observation_logging=False, action_logging=False, reward_logging=True) env = LogStatsWrapper.wrap(env) env.reset() env.step(env.action_space.sample()) for ii in range(2): env.step(env.actio...
def test_unknown_language(): with pytest.raises(UnsupportedLanguage): compiler.generate_input_json({'foo': ''}, language='Bar') with pytest.raises(UnsupportedLanguage): compiler.compile_from_input_json({'language': 'FooBar'}) with pytest.raises(UnsupportedLanguage): compiler.generate...
class HStack(Stack): def __init__(self, workspace_name: str, params: List[Any]): super().__init__(LayoutName.HSTACK, workspace_name, params) def _first_direction(self) -> Direction: return Direction.VERTICAL def _resize_direction(self) -> ResizeDirection: return ResizeDirection.HEIGH...
class perm102_bmm_rcr_bias(perm102_bmm_rcr): def __init__(self): super().__init__() self._attrs['op'] = 'perm102_bmm_rcr_bias' def _infer_shapes(self, a: Tensor, b: Tensor, bias: Tensor): bias_shapes = bias._attrs['shape'] if (len(bias_shapes) != 2): raise RuntimeErro...
def find_graph_differences_summary(previous_graph: Optional[GraphRepr], current_graph: GraphRepr, previous_results: Dict[(str, Optional[List[Row]])], previous_erasure_results: Dict[(str, int)]) -> Optional[GraphDiffSummary]: graph_diff: Optional[GraphDiff] = _find_graph_differences(previous_graph, current_graph, pr...
def test_example_generation() -> None: option = Option(id='option', description='Option', examples=['selection']) number = Number(id='number', description='Number', examples=[('number', 2)], many=True) text = Text(id='text', description='Text', examples=[('text', '3')], many=True) selection = Selection(...
def in_progress(): try: (current_year, current_month) = TaskLog.objects.values_list('year', 'month').distinct().order_by('-year', '-month')[0] except IndexError: return False return (not TaskLog.objects.filter(year=current_year, month=current_month, task_name='fetch_and_import').exists())
(input_signature=(tf.TensorSpec(shape=[None], dtype=tf.string), tf.TensorSpec(shape=[None, 4], dtype=tf.int32))) def decode_and_crop_and_serve(image_bytes, crop_window): return {tf.saved_model.CLASSIFY_OUTPUT_SCORES: classifier(decode_and_crop(image_bytes=image_bytes, crop_window=crop_window)), tf.saved_model.CLASS...
class ExecutionContextAPI(ABC): def coinbase(self) -> Address: ... def timestamp(self) -> int: ... def block_number(self) -> BlockNumber: ... def difficulty(self) -> int: ... def mix_hash(self) -> Hash32: ... def gas_limit(self) -> int: ... def...
class Instance(): def __init__(self, location: Location) -> None: self.location = location (self.multiplexer, self.oef_search_dialogues, self.crypto, self.connection) = make_multiplexer_and_dialogues() self.thread = Thread(target=self.multiplexer.connect) def address(self) -> str: ...
class DataModelBuilder(object): def __init__(self, global_configs, scanner_configs, service_config, model_name): self.global_configs = global_configs self.scanner_configs = scanner_configs self.service_config = service_config self.model_name = model_name def build(self): ...
def load_modules(package): modules = pkgutil.iter_modules(package.__path__, (package.__name__ + '.')) for (_, name, _) in modules: logger.debug(f'loading module: {name}') try: importlib.import_module(name) except ModuleNotFoundError as error: logger.warning(f'fail...
('orca') def test_nitrobenzene(): inp_1 = {'xyz': 'lib:redox/nitrobenzene.xyz', 'charge': 0, 'mult': 1, 'opt': False} inp_2 = {'xyz': 'lib:redox/nitrobenzene_anion.xyz', 'charge': (- 1), 'mult': 2, 'opt': False} orca_gas = {'keywords': 'uks b3lyp 6-31G** rijcosx autoaux', 'pal': 4} orca_solv = orca_gas....
class _L2Responder_pcap(_L2Responder): _fd = None _inject = None _c_int_ = None def __init__(self, server_address, response_interface, qtags=None): import ctypes self._c_int_ = ctypes.c_int import ctypes.util from . import getifaddrslib pcap = ctypes.util.find_lib...
class PollOption(JsonDeserializable): def de_json(cls, json_string): if (json_string is None): return None obj = cls.check_json(json_string, dict_copy=False) return cls(**obj) def __init__(self, text, voter_count=0, **kwargs): self.text: str = text self.voter_...
def extension_controller_fortigate(data, fos): vdom = data['vdom'] state = data['state'] extension_controller_fortigate_data = data['extension_controller_fortigate'] filtered_data = underscore_to_hyphen(filter_extension_controller_fortigate_data(extension_controller_fortigate_data)) if ((state == 'p...
class MESH_OT_YAVNEBase(bpy.types.Operator): bl_idname = 'mesh.yavne_base' bl_label = 'YAVNE Base Operator' bl_options = {'INTERNAL'} addon_key = __package__.split('.')[0] def poll(cls, context): edit_object = context.edit_object return (edit_object and (edit_object.type == 'MESH') a...
(config_path='./conf', config_name='conf_apex_dqn') def main(cfg): if (cfg.seed is not None): random_utils.manual_seed(cfg.seed) logging.info(hydra_utils.config_to_json(cfg)) env = atari_wrapper.make_atari_env(**cfg.env) model = AtariDQNModel(env.action_space.n, network=cfg.network, dueling_dqn=...
.parametrize('elasticapm_client', [{'service_name': '%&!'}], indirect=True) def test_invalid_service_name_disables_send(elasticapm_client): assert (len(elasticapm_client.config.errors) == 1) assert ('SERVICE_NAME' in elasticapm_client.config.errors) assert elasticapm_client.config.disable_send
def test_supervisor_not_started(): timeout = 0.1 sleep_time = 0.5 exec_limiter = ExecTimeoutThreadGuard(timeout) with exec_limiter as exec_limit: assert (not exec_limiter._future_guard_task) TestThreadGuard.slow_function(sleep_time) assert (not exec_limit.is_cancelled_by_timeout())
def branches(src_dir, remote=True): clean_src = io.escape_path(src_dir) if remote: return _cleanup_remote_branch_names(process.run_subprocess_with_output(f"git -C {clean_src} for-each-ref refs/remotes/ --format='%(refname:short)'")) else: return _cleanup_local_branch_names(process.run_subpro...
class SimpleDocker(object): def __init__(self, use_udocker=None): self.identifier = LongIdentifier() if (use_udocker is None): self._with_udocker = self._use_udocker() else: self._with_udocker = use_udocker def _use_udocker(self): if is_docker_installed():...
def test_equal_szts_straight(): kwargs = copy.copy(KWARGS) kwargs['images'] = 10 kwargs['max_step'] = 0.04 convergence = {'rms_force_thresh': 2.4} kwargs['convergence'] = convergence szts_equal = SimpleZTS(get_geoms(('A', 'B')), param='equal') opt = run_cos_opt(szts_equal, SteepestDescent, *...
class Txt(Generator): def __init__(self, rmap=None, path='regs.txt', **args): super().__init__(rmap, **args) self.path = path def generate(self): self.validate() for reg in self.rmap: if (len(reg) > 1): raise ValueError(('Only registers with single bit...
class OptionPlotoptionsTreegraphSonificationContexttracksMappingTremoloDepth(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: s...
def extractMadsnailRu(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return False if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=...
(Output('forward-week', 'style'), [Input('week-ending', 'children')]) def toggle_forward_arrow_display(week_ending): if (calc_next_saturday(datetime.strptime(week_ending, '%A %b %d, %Y')) == calc_next_saturday(get_max_week_ending())): return {'color': 'rgba(0,0,0,0)', 'backgroundColor': 'rgba(0,0,0,0)', 'bo...
def check_provider_constraints(provider_name: str, feature: str, subfeature: str, phase: Optional[str]=None, constraints: Optional[Dict]=None) -> Tuple[(bool, str)]: subfeatures_providers = list_features(as_dict=True) provider_info = subfeatures_providers.get(provider_name, None) if (not provider_info): ...
class SingleSiteUniformMetropolisHastingsTest(unittest.TestCase): class SampleBernoulliModel(object): _variable def foo(self): return dist.Beta(torch.tensor(2.0), torch.tensor(2.0)) _variable def bar(self): return dist.Bernoulli(self.foo()) class SampleCat...
def test_average_regions_range_in_bins_end(): outfile = NamedTemporaryFile(suffix='.npz', prefix='average_region', delete=False) matrix = (ROOT + 'small_test_matrix.cool') bed_file = (ROOT + 'hicAverageRegions/regions_multi.bed') args = '--matrix {} --regions {} -o {} --rangeInBins 100 100 -cb {}'.form...
class BatchProcessor(): def __init__(self, batch_size=50, concurrent_requests=4): self.batch_size = batch_size self.concurrent_requests = concurrent_requests def process_event_requests(self, event_requests_async): async def process(): async for _ in self.process_event_request...
class EventEmailTemplateForm(EmailTemplateForm): def __init__(self, event, location): domain = Site.objects.get_current().domain super(EventEmailTemplateForm, self).__init__() self.fields['sender'].initial = location.from_email() self.fields['footer'].initial = forms.CharField(widget...
def apply_encryption(message: PlainMessage, credentials: V3, security_name: bytes, security_engine_id: bytes, engine_boots: int, engine_time: int) -> Union[(PlainMessage, EncryptedMessage)]: if ((credentials.priv is not None) and (not credentials.priv.method)): raise UnsupportedSecurityLevel('Encryption met...
class OptionSeriesColumnDataDragdrop(Options): def draggableX(self): return self._config_get(None) def draggableX(self, flag: bool): self._config(flag, js_type=False) def draggableY(self): return self._config_get(None) def draggableY(self, flag: bool): self._config(flag, ...
def _bail_if_private(candidate: str, allow_private: bool) -> None: if (candidate.startswith('_') and (not allow_private) and (not (candidate.startswith('__') and candidate.endswith('__')))): raise ValueError("It's disencouraged to patch/mock private interfaces.\nThis would result in way too coupled tests an...
def _StashRepos(repos_and_branch, params, pop=False): commands = [] for (repo, _branch) in repos_and_branch: if pop: cmd = [params.config.git, 'stash', 'pop'] else: cmd = [params.config.git, 'stash', '-u'] commands.append(ParallelCmd(repo, cmd)) ExecuteInParal...
_flyte_cli.command('update-plugin-override', cls=_FlyteSubCommand) _host_option _insecure_option _project_option _domain_option _optional_name_option _click.option('--task-type', help='Task type for which to apply plugin implementation overrides') _click.option('--plugin-id', multiple=True, help='Plugin id(s) to be use...
def lab_to_din99o(lab: Vector) -> Vector: (l, a, b) = lab val = (1 + (C2 * l)) l99o = ((C1 * math.copysign(math.log(abs(val)), val)) / KE) if ((a == 0) and (b == 0)): a99o = b99o = 0.0 else: eo = ((a * math.cos(RADS)) + (b * math.sin(RADS))) fo = (FACTOR * ((b * math.cos(RADS...
class SlaPolicyResponseHandler(GenericZendeskResponseHandler): def applies_to(api, response): return get_endpoint_path(api, response).startswith('/slas') def deserialize(self, response_json): if ('definitions' in response_json): definitions = self.object_mapping.object_from_json('def...
class TestUserUpdateClipper(): def _init_user_model(self, param_value): user_model = utils.TwoFC() user_model.fill_all(param_value) return user_model def test_calc_clip_factor(self) -> None: clip_factor = calc_clip_factor(clipping_value=5, norm=10) assertAlmostEqual(clip_...
class LocalEnsembleReader(): def __init__(self, storage: LocalStorageReader, path: Path): self._storage: Union[(LocalStorageReader, LocalStorageAccessor)] = storage self._path = path self._index = _Index.model_validate_json((path / 'index.json').read_text(encoding='utf-8')) self._exp...
def gen_function_call(func_attrs, backend_spec, indent=' ', bias_add=False): x = func_attrs['inputs'][0] xshape = x._attrs['shape'] y = func_attrs['outputs'][0] yshape = y._attrs['shape'] if bias_add: r = func_attrs['inputs'][1] return FUNC_CALL_TEMPLATE.render(func_name=func_attrs[...
class HFConfigKeys(): def conv_rotary_embedding_base(config: GPTNeoXConfig) -> int: assert (config.layer.attention.rotary_embeddings is not None) return config.layer.attention.rotary_embeddings.rotary_base def conv_rotary_embedding_fraction(config: GPTNeoXConfig) -> float: assert (config...
class LRUCache(): def __init__(self, capacity: int): self.capacity = capacity self.cache = {} self.head = ListNode(None, None) self.tail = ListNode(None, None) self.head.next = self.tail self.tail.prev = self.head def get(self, key: int) -> int: if (key no...
class ObjectWithEqualityComparisonMode(HasTraits): list_values = List(comparison_mode=ComparisonMode.equality) dict_values = Dict(comparison_mode=ComparisonMode.equality) set_values = Set(comparison_mode=ComparisonMode.equality) number = Any(comparison_mode=ComparisonMode.equality) calculated = Prop...
class Driver(): def __init__(self, user, password, db, u_search='', g_search='', c_search='', regex=''): try: self.driver = GraphDatabase.driver('neo4j://localhost:7687', auth=(user, password)) self.database = db self.user_search = u_search self.group_search =...
def test_distance_nearest_projection(): spacing = 0.3 coords = grid_coordinates((5, 10, (- 20), (- 17)), spacing=spacing, adjust='region') distance = median_distance(coords, k_nearest=1, projection=(lambda i, j: ((i * 2), (j * 2)))) npt.assert_allclose(distance, (spacing * 2)) assert (distance.shape...