code
stringlengths
281
23.7M
class OptionPlotoptionsPyramidSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionPlotoptionsPyramidSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionPlotoptionsPyramidSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionPlotoptionsPyramidSo...
class ViewUpdater(ReadWriteDbInterface): def update_view(self, plugin_name: str, content: bytes): with self.get_read_write_session() as session: entry = session.get(WebInterfaceTemplateEntry, plugin_name) if (entry is None): new_entry = WebInterfaceTemplateEntry(plugi...
class OptionSeriesAreasplinerangeSonificationDefaultspeechoptionsActivewhen(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...
_entry_point def test_intercepted_scope_non_flyte_exception(): value_error = ValueError('Bad value') with pytest.raises(scopes.FlyteScopedUserException) as e: _user_func(value_error) e = e.value assert (e.value == value_error) assert ('Bad value' in e.verbose_message) assert ('User error...
class ConvDepthwiseBiasTestCase(unittest.TestCase): def test_fp16(self, batch=4): groups = 32 size = (12, 12) target = detect_target() X = Tensor(shape=[IntImm(batch), *size, 32], dtype='float16', name='input_0', is_input=True) W = Tensor(shape=[32, 3, 3, 1], dtype='float16',...
def test_list_models(model_list): filter_str = 'displayName={0} OR tags:{1}'.format(model_list[0].display_name, model_list[1].tags[0]) all_models = ml.list_models(list_filter=filter_str) all_model_ids = [mdl.model_id for mdl in all_models.iterate_all()] for mdl in model_list: assert (mdl.model_i...
def maketodo(pipfile, dbfile): todos = set() with open(pipfile, 'r') as f: for line in f: todos.add(line.split()[0]) with open(dbfile, 'r') as f: for line in f: todos.remove(line.split()[0]) for line in todos: if line.endswith('.VCC_WIRE'): con...
class MusicRequest(BaseModel): song: Optional[List[str]] = Field(default=None, description='The song(s) that the user would like to be played.') album: Optional[List[str]] = Field(default=None, description='The album(s) that the user would like to be played.') artist: Optional[List[str]] = Field(default=Non...
def extractL4StkHomeBlog(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('second story online', 'Second Story Online', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous',...
(no_gui_test_assistant, 'No GuiTestAssistant') class TestAdvancedEditorAreaPane(unittest.TestCase, GuiTestAssistant): def setUp(self): GuiTestAssistant.setUp(self) self.area_pane = AdvancedEditorAreaPane() def tearDown(self): if (self.area_pane.control is not None): with self...
class Coherence(PipelineStage): name = 'coherence' def run(self, task: DecompilerTask) -> None: variables = self._collect_variables(task.graph) self.enforce_same_types(variables) self.enforce_same_aliased_value(variables) def _collect_variables(self, cfg: ControlFlowGraph) -> Dict[(s...
class NameModel(Model): def get_data_generator(self, document_features_context: DocumentFeaturesContext) -> NameDataGenerator: return NameDataGenerator(document_features_context=document_features_context) def get_semantic_extractor(self) -> NameSemanticExtractor: return NameSemanticExtractor() ...
class TestSequenceFunctions(unittest.TestCase): def __init__(self, *args, **kwargs): logSetup.initLogging() super().__init__(*args, **kwargs) def setUp(self): self.buildTestTree() def buildTestTree(self): self.tree = hamDb.BkHammingTree() for (nodeId, nodeHash) in TES...
def extractDeeptranslations5WordpressCom(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, ...
class StalkerThumbnailCache(object): def get(cls, thumbnail_full_path, login=None, password=None): filename = os.path.basename(thumbnail_full_path) logger.debug(('filename : %s' % filename)) cache_path = os.path.expanduser(defaults.local_cache_folder) cached_file_full_path = os.path....
def require_showbase(func): (func) def wrapper(*args, **kwargs): if is_showbase_initialized(): return func(*args, **kwargs) raise ConfigError(f"ShowBase instance has not been initialized, but a function has been called that requires it: '{func.__name__}'.") return wrapper
class ShamelessOniisanPageProcessor(HtmlProcessor.HtmlPageProcessor): wanted_mimetypes = ['text/html'] want_priority = 80 loggerPath = 'Main.Text.ShamelessOniisan' def wantsUrl(url): if re.search('^ url): print(("wwsd Wants url: '%s'" % url)) return True return Fa...
class MeteredSocket(): def __init__(self, socket): self._socket = socket self._recv_bytes = 0 self._recv_ops = 0 self._send_bytes = 0 self._send_ops = 0 def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): return self._socket...
class OptionPlotoptionsPyramid3dSonificationDefaultspeechoptionsMappingVolume(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: ...
class GalacticCommunityProcessor(AbstractGamestateDataProcessor): ID = 'galactic_community' DEPENDENCIES = [CountryProcessor.ID, RulerEventProcessor.ID] def __init__(self): super().__init__() self._ruler_dict = None self._countries_dict = None def extract_data_from_gamestate(self...
class TensorboardLogger(ExperimentLogger): def __init__(self, save_dir: tp.Union[(Path, str)], with_media_logging: bool=True, name: tp.Optional[str]=None, **kwargs: tp.Any): self._with_media_logging = with_media_logging self._save_dir = str(save_dir) self._name = (name or 'tensorboard') ...
def extract_flake8_import_order() -> Dict[(str, str)]: return {'I666': 'Import statement mixes groups.', 'I100': 'Import statements are in the wrong order.', 'I101': 'Imported names are in the wrong order.', 'I201': 'Missing newline between import groups.', 'I202': 'Additional newline in a group of imports.'}
class OptionPlotoptionsBulletSonificationDefaultinstrumentoptionsMappingGapbetweennotes(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(se...
def calculate_intrinsic_cost(tx: Transaction) -> Uint: data_cost = 0 for byte in tx.data: if (byte == 0): data_cost += TX_DATA_COST_PER_ZERO else: data_cost += TX_DATA_COST_PER_NON_ZERO if (tx.to == Bytes0(b'')): create_cost = TX_CREATE_COST else: ...
class NotificationList(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): notifications = Notification.objects.filter(to_user_id=request.user.id) serializer = NotificationSerializerGet(notifications, user=None, many=True) return Response(serializer.data...
(short_help='Get stock codes.') ('-n', '--name', 'names', metavar='NAME', multiple=True, help='Name of stock. Can set multiple times.') ('-m', '--market', 'markets', metavar='MARKET', multiple=True, type=click.Choice(market_codes, case_sensitive=False), help='Stock market code to get. Can set multiple times.') ('-p', '...
class TestOpenClose(): def test_open_none_existing_device(device_not_exists: PyK4A): with pytest.raises(K4AException): device_not_exists.open() def test_open_existing_device(device: PyK4A): device.open() def test_open_twice(device: PyK4A): device.open() with pytes...
def request_new_link(request, useremail=None, usertoken=None): try: if ((useremail is None) or (usertoken is None)): if (request.method == 'POST'): form = RequestNewVerificationEmail(request.POST) if form.is_valid(): form_data: dict = form.clea...
class BlogPost(Document): content = Text() tags = Keyword(multi=True) class Index(): name = 'test-blogpost' def add_tags(self): s = Search(index='test-percolator') s = s.query('percolate', field='query', index=self._get_index(), document=self.to_dict()) for percolator in ...
def run(): print('\nmodule top(input wire in, output wire out);\n ') params = {} sites = list(gen_sites()) for ((tile_name, site_name), isone) in zip(sites, util.gen_fuzz_states(len(sites))): params[tile_name] = (site_name, isone) print('\n (* KEEP, DONT_TOUCH, LOC = "{}" *)\n GT...
class FuncParser(): def __init__(self, callables, start_char=_START_CHAR, escape_char=_ESCAPE_CHAR, max_nesting=_MAX_NESTING, **default_kwargs): if isinstance(callables, dict): loaded_callables = {**callables} else: loaded_callables = {} for module_or_path in make...
def quadrupole3d_01(ax, da, A, bx, db, B, R): result = numpy.zeros((6, 1, 3), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + R[0]) x4 = (x2 + B[0]) x5 = (x3 * x4) x6 = (0.5 * x0) x7 = ((ax * bx) * x0) x8 = ((((5. * da) * db...
def validate_check_in_out_status(station: Station, attendee_data: UserCheckIn): if attendee_data: if ((attendee_data.station.station_type == station.station_type) and (station.station_type == STATION_TYPE.get('check in'))): raise UnprocessableEntityError({'attendee': attendee_data.ticket_holder_...
class Solution(): def flatten(self, head: 'Node') -> 'Node': def flat(head): prev = None curr = head while (curr is not None): if (curr.child is not None): (ch, ct) = flat(curr.child) n = curr.next ...
def _fuse_gemm_reshape_permute0213(sorted_graph: List[Tensor], workdir: str=None) -> List[Tensor]: sorted_ops = graph_utils.get_sorted_ops(sorted_graph) for op in sorted_ops: if (op._attrs['op'] != 'gemm_rcr'): continue outputs = op._attrs['outputs'] assert (len(outputs) == 1...
class OptionSeriesColumnDataDatalabelsFilter(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, ...
def test_transacting_with_contract_no_arguments(w3, math_contract, transact, call): initial_value = call(contract=math_contract, contract_function='counter') txn_hash = transact(contract=math_contract, contract_function='incrementCounter') txn_receipt = w3.eth.wait_for_transaction_receipt(txn_hash) asse...
def get_lpddr4_phy_init_sequence(phy_settings, timing_settings): cl = phy_settings.cl cwl = phy_settings.cwl bl = 16 dq_odt = getattr(phy_settings, 'dq_odt', 'RZQ/2') ca_odt = getattr(phy_settings, 'ca_odt', 'RZQ/2') pull_down_drive_strength = getattr(phy_settings, 'pull_down_drive_strength', 'R...
def concat_pooling_forward(pooling: Model[(Ragged, Floats2d)], X: List[Ragged], is_train: bool): xp = pooling.ops.xp datas = [] lens = [] doc_lens = [] for X_doc_data in X: datas.append(X_doc_data.dataXd) lens.append(X_doc_data.lengths) doc_lens.append(len(X_doc_data.lengths)...
def __start_commoncrawl_extractor(warc_path, callback_on_article_extracted=None, callback_on_warc_completed=None, valid_hosts=None, start_date=None, end_date=None, strict_date=True, reuse_previously_downloaded_files=True, local_download_dir_warc=None, continue_after_error=True, show_download_progress=False, log_level=l...
def main(): with open('../config.yaml') as f: config_dict = yaml.full_load(f) config = dm.Config(**config_dict) ctx = zmq.Context() sock_sender = ctx.socket(zmq.PUSH) sock_sender.bind(config.zmq_input_address) sock_receiver = ctx.socket(zmq.PULL) sock_receiver.connect(config.zmq_...
class ParserReflect(): def __init__(self, pdict, log=None): self.pdict = pdict self.start = None self.error_func = None self.tokens = None self.modules = set() self.grammar = [] self.error = False if (log is None): self.log = PlyLogger(sys....
_session def single_file_update(session, product_file, directory, product): filename = f"{product_file['identifier']}.nc" if session.query(db.File).filter((db.File.filename == filename)).first(): logger.warning('File %s already processed', filename) return logger.info('Downloading file %s', ...
def use_direct_and_iddr(p, luts, connects): p['mux_config'] = random.choice(('direct', 'idelay', 'none')) p['iddr_mux_config'] = random.choice(('direct', 'idelay', 'none')) if (p['iddr_mux_config'] != 'none'): p['INIT_Q1'] = random.randint(0, 1) p['INIT_Q2'] = random.randint(0, 1) p[...
class CfgNode(_CfgNode): def cast_from_other_class(cls, other_cfg): new_cfg = cls(other_cfg) for (k, v) in other_cfg.__dict__.items(): new_cfg.__dict__[k] = v return new_cfg def merge_from_file(self, cfg_filename: str, *args, **kwargs): cfg_filename = reroute_config_p...
class HTTPError(Exception): def __init__(self, code, reason=None, debug=None, headers={}): self.answer = if (reason is None): message = self.answer else: message = ('%s (%s)' % (self.answer, reason)) Exception.__init__(self, message) self.code = code ...
class OptionSeriesLineSonificationDefaultinstrumentoptionsMappingLowpassFrequency(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, te...
class List(KqlNode): __slots__ = ('items',) precedence = (Value.precedence + 1) operator = '' template = Template('$items') def __init__(self, items): self.items = items KqlNode.__init__(self) def delims(self): return {'items': ' {} '.format(self.operator)} def __eq__...
def extractQuthsCom(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: ...
('calling_file, calling_module', [param('tests/test_apps/sweep_complex_defaults/my_app.py', None, id='file_path'), param(None, 'tests.test_apps.sweep_complex_defaults.my_app', id='pkg_path')]) def test_sweep_complex_defaults(hydra_restore_singletons: Any, hydra_sweep_runner: TSweepRunner, calling_file: str, calling_mod...
def update_awards(award_tuple: Optional[tuple]=None) -> int: if award_tuple: values = [award_tuple, award_tuple, award_tuple] predicate = 'WHERE tn.award_id IN %s' else: values = None predicate = '' return execute_database_statement(general_award_update_sql_string.format(pred...
class CssDivModalContent(CssStyle.Style): _attrs = {'margin': '10%', 'padding': '5px 5px 5px 5px', 'border': '1px solid #888', 'width': '75%', 'box-shadow': '0 19px 38px rgba(0, 0, 0, 0.12), 0 15px 12px rgba(0, 0, 0, 0.22)', 'display': 'inline-flex', 'flex-direction': 'column'} def customize(self): self...
.django_db def test_federal_account_list_pagination(client, agency_account_data, helpers): query_params = f'?fiscal_year={helpers.get_mocked_current_fiscal_year()}&limit=2&page=1' resp = client.get(url.format(code='007', query_params=query_params)) expected_result = {'fiscal_year': helpers.get_mocked_curren...
class MDHKinematicChain(KinematicChain): _links = attr.ib(type=Sequence[MDHLink]) def __attrs_post_init__(self) -> None: self._links = _validate_links(self._links) def from_parameters(cls: Any, parameters: npt.NDArray[np.float64]) -> Any: kc = cls(parameters) return kc def matrix...
class BiometricWindow(QMainWindow): def __init__(self): super().__init__() self.reg_exp_for_ip = '((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?=\\s*netmask)' self.init_ui() def closeEvent(self, event): can_exit = (not hasattr(self, 'p')) ...
def set_icc_max(config): for plane in CURRENT_PLANES: try: write_current_amp = config.getfloat('ICCMAX.{:s}'.format(power['source']), plane, fallback=config.getfloat('ICCMAX', plane, fallback=(- 1.0))) if (write_current_amp > 0): write_value = calc_icc_max_msr(plane, ...
class SnortLib(app_manager.RyuApp): def __init__(self): super(SnortLib, self).__init__() self.name = 'snortlib' self.config = {'unixsock': True} self._set_logger() self.sock = None self.nwsock = None def set_config(self, config): assert isinstance(config, ...
class XarFile(): def __init__(self, filename): self.filename = filename (root, self.extension) = os.path.splitext(self.filename) self.alias = os.path.basename(root) self._read_header() version_suffix = ('-%d' % self.version) if self.alias.endswith(version_suffix): ...
class FaucetTaggedOrderedSwapVidMirrorTest(FaucetTaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\n 101:\n description: "tagged"\nacls:\n 1:\n - rule:\n vlan_vid: 100\n actions:\n mirror: %(port_3)d\n force_port_v...
.django_db def test_award_type(award_data_fixture, elasticsearch_award_index): elasticsearch_award_index.update_index() should = {'match': {'type': 'A'}} query = create_query(should) client = elasticsearch_award_index.client response = client.search(index=elasticsearch_award_index.index_name, body=q...
class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print('{} - Contact by {}'.format(time.strftime('[%Y/%m/%d %I:%M:%S]'), self.client_address[0])) response = open('data/cnc1-response.raw', 'rb') self.request.sendall(res...
def compute_max_saturation(a: float, b: float, lms_to_rgb: Matrix, ok_coeff: list[Matrix]) -> float: if (alg.vdot(ok_coeff[0][0], [a, b]) > 1): (k0, k1, k2, k3, k4) = ok_coeff[0][1] (wl, wm, ws) = lms_to_rgb[0] elif (alg.vdot(ok_coeff[1][0], [a, b]) > 1): (k0, k1, k2, k3, k4) = ok_coeff[...
(scope='function') def privacy_notice_fr_provide_service_frontend_only(db: Session) -> Generator: privacy_notice = PrivacyNotice.create(db=db, data={'name': 'example privacy notice us_co provide.service.operations', 'notice_key': 'example_privacy_notice_us_co_provide.service.operations', 'description': 'a sample pr...
def build_neck(config): from .db_fpn import DBFPN from .east_fpn import EASTFPN from .sast_fpn import SASTFPN from .rnn import SequenceEncoder from .pg_fpn import PGFPN from .table_fpn import TableFPN support_dict = ['DBFPN', 'EASTFPN', 'SASTFPN', 'SequenceEncoder', 'PGFPN', 'TableFPN'] ...
class CssBigIcon(CssStyle.Style): _attrs = {'display': 'inline-block', 'margin': '0 10px 0 10px', 'cursor': 'pointer'} def customize(self): self.css({'color': self.page.theme.danger.base, 'font-size': self.page.body.style.globals.icon.big_size()}) self.hover.css({'color': self.page.theme.danger....
def check_pde_args(F, J, Jp): if (not isinstance(F, (ufl.BaseForm, slate.slate.TensorBase))): raise TypeError(("Provided residual is a '%s', not a BaseForm or Slate Tensor" % type(F).__name__)) if (len(F.arguments()) != 1): raise ValueError('Provided residual is not a linear form') if (not i...
def extractWwwPeachblossomgroveCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('World of Hidden Phoenixes' in item['tags']): return buildReleaseMessageWithType(item, 'World...
class BracketPlugin(object): def __init__(self, plugin, loaded): self.enabled = False self.args = (plugin['args'] if ('args' in plugin) else {}) self.plugin = None if ('command' in plugin): plib = plugin['command'] try: module = _import_module(...
class OptionSeriesPolygonSonificationContexttracksMappingGapbetweennotes(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 SimulEvalResults(): def __init__(self, path: Union[(Path, str)]) -> None: self.path = Path(path) scores_path = (self.path / 'scores') if scores_path.exists(): self.is_finished = True with open((self.path / 'scores')) as f: self.scores = json.load...
class OptionSeriesColumnpyramidSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionSeriesColumnpyramidSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionSeriesColumnpyramidSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) ->...
class SingletonMeta(ImmutableMeta): def __new__(mcls, name, bases, namespace, **kwargs): cls = super().__new__(mcls, name, bases, namespace, **kwargs) cls._cache = weakref.WeakValueDictionary() return cls def _new(cls, *args): try: self = cls._cache[args] exce...
_pass_through.command('pyflyte-map-execute') _click.option('--inputs', required=True) _click.option('--output-prefix', required=True) _click.option('--raw-output-data-prefix', required=False) _click.option('--max-concurrency', type=int, required=False) _click.option('--test', is_flag=True) _click.option('--dynamic-addl...
class OptionSeriesAreasplineData(Options): def accessibility(self) -> 'OptionSeriesAreasplineDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesAreasplineDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): s...
def extractNeoTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('The Man Picked up by the Gods'.lower() in item['title'].lower()): return buildReleaseMessageWithType...
class modules(): def __init__(self): self._load_command = COMMANDS['modprobe'] self._unload_command = COMMANDS['rmmod'] def __repr__(self): return ('%s' % self.__class__) def loaded_modules(self): mods = [] deps = {} try: with open('/proc/modules',...
def cMedQA2(): train_data = csv.reader(open('./QA/cMedQA2-master/train_candidates.txt')) test_data = csv.reader(open('./QA/cMedQA2-master/test_candidates.txt')) questions_data = csv.reader(open('./QA/cMedQA2-master/question.csv')) answers_data = csv.reader(open('./QA/cMedQA2-master/answer.csv')) que...
class OptionSeriesSankeyStatesSelectMarker(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._conf...
def get_icdar_2013_detector_dataset(cache_dir=None, skip_illegible=False): if (cache_dir is None): cache_dir = tools.get_default_cache_dir() main_dir = os.path.join(cache_dir, 'icdar2013') training_images_dir = os.path.join(main_dir, 'Challenge2_Training_Task12_Images') training_zip_images_path ...
class OptionSeriesWindbarbDataMarker(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._config(num...
class EnglishSpeechCounter(SpeechToSpeechAgent): def __init__(self, args): super().__init__(args) self.wait_seconds = args.wait_seconds self.tts_model = TTSModel() def add_args(parser): parser.add_argument('--wait-seconds', default=1, type=int) def policy(self, states: Option...
class OptionSeriesSankeyEvents(Options): def afterAnimate(self): return self._config_get(None) def afterAnimate(self, value: Any): self._config(value, js_type=False) def checkboxClick(self): return self._config_get(None) def checkboxClick(self, value: Any): self._config(v...
class TestSVSignature(unittest.TestCase): def test_accessors(self): deletion = SignatureDeletion('chr1', 100, 300, 'cigar', 'read1') self.assertEqual(deletion.get_source(), ('chr1', 100, 300)) self.assertEqual(deletion.get_key(), ('DEL', 'chr1', 200)) def test_position_distance_to(self):...
class ErtWorkflowDocumentation(_ErtDocumentation): pm = ErtPluginManager() _JOBS = pm.get_documentation_for_workflows() _TITLE = 'Workflow jobs' _SECTION_ID = 'ert-workflow-jobs' def run(self) -> List[nodes.section]: section_id = ErtWorkflowDocumentation._SECTION_ID title = ErtWorkfl...
class TestXYZD65Serialize(util.ColorAssertsPyTest): COLORS = [('color(xyz-d65 0 0.3 0.75 / 0.5)', {}, 'color(xyz-d65 0 0.3 0.75 / 0.5)'), ('color(xyz-d65 0 0.3 0.75)', {'alpha': True}, 'color(xyz-d65 0 0.3 0.75 / 1)'), ('color(xyz-d65 0 0.3 0.75 / 0.5)', {'alpha': False}, 'color(xyz-d65 0 0.3 0.75)'), ('color(xyz-d...
def extractRiftxrCom(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 SegmentByPeaks(data, peaks, weights=None): segs = np.zeros_like(data) for (seg_start, seg_end) in zip(np.insert(peaks, 0, 0), np.append(peaks, len(data))): if ((weights is not None) and (weights[seg_start:seg_end].sum() > 0)): val = np.average(data[seg_start:seg_end], weights=weights[seg...
def test_rf_directional_expectation(dummy_titanic_rf, dummy_passengers): model = dummy_titanic_rf (p1, p2) = dummy_passengers test_df = pd.DataFrame.from_dict([p1], orient='columns') (X, y) = get_feats_and_labels(prep_df(test_df)) p1_prob = model.predict(X)[0] p1_female = p1.copy() p1_female...
def service_definition_file(servicename): boto_service_definition_files() service_definitions_for_service = fnmatch.filter(boto_service_definition_files(), (('**/' + servicename) + '/*/service-*.json.gz')) service_definitions_for_service.sort() return service_definitions_for_service[(- 1)]
class CommandResponder(cmdrsp.CommandResponderBase): CMDGEN_MAP = {v2c.GetRequestPDU.tagSet: cmdgen.GetCommandGenerator(), v2c.SetRequestPDU.tagSet: cmdgen.SetCommandGenerator(), v2c.GetNextRequestPDU.tagSet: cmdgen.NextCommandGeneratorSingleRun(), v2c.GetBulkRequestPDU.tagSet: cmdgen.BulkCommandGeneratorSingleRun(...
def del_port(manager, system_id, bridge_name, fn): def _delete_port(tables, *_): bridge = _get_bridge(tables, bridge_name) if (not bridge): return port = fn(tables) if (not port): return ports = bridge.ports ports.remove(port) bridge.po...
def main(): formula = {'py_files': re.compile('^(#!.*\\n)\\n*', re.MULTILINE)} sample = fetch_samplefile() filelists = fetch_files(sample.keys()) failure_list = [] for filename in filelists: if (not verify_file(filename, sample, formula)): failure_list.append(os.path.relpath(file...
class ShopifyCustomer(EcommerceCustomer): def __init__(self, customer_id: str): self.setting = frappe.get_doc(SETTING_DOCTYPE) super().__init__(customer_id, CUSTOMER_ID_FIELD, MODULE_NAME) def sync_customer(self, customer: Dict[(str, Any)]) -> None: customer_name = ((cstr(customer.get('f...
class spawnAttachForm(QDialog, Ui_SpawnAttachDialog): def __init__(self, parent=None): super(spawnAttachForm, self).__init__(parent) self.setupUi(self) self.setWindowOpacity(0.93) self.btnSubmit.clicked.connect(self.submit) self.packageName = '' self.packages = [] ...
def test_slate_hybridization_wrong_option(): (a, L, W) = setup_poisson() w = Function(W) params = {'mat_type': 'matfree', 'ksp_type': 'preonly', 'pc_type': 'python', 'pc_python_type': 'firedrake.HybridizationPC', 'hybridization': {'ksp_type': 'preonly', 'pc_type': 'lu', 'localsolve': {'ksp_type': 'preonly',...
(('cfg', 'expected'), [param({'_target_': 'tests.instantiate.ArgsClass', '_args_': ['${.1}', 2]}, ArgsClass(2, 2), id='config:args_only'), param({'_target_': 'tests.instantiate.ArgsClass', '_args_': [1], 'foo': '${._args_}'}, ArgsClass(1, foo=[1]), id='config:args+kwargs'), param({'_target_': 'tests.instantiate.ArgsCla...
def setup(): global mc print('') plist = list(serial.tools.list_ports.comports()) idx = 0 for port in plist: print('{} : {}'.format(idx, port)) idx += 1 if (idx == 0): print('The connected device was not detected. Please try reconnecting.') exit(1) _in = input...
class AdminSalesInvoicesSchema(Schema): class Meta(): type_ = 'admin-sales-invoices' self_view = 'v1.admin_sales_invoices' inflect = dasherize id = fields.String() identifier = fields.String() status = fields.String() amount = fields.Float() created_at = fields.DateTime()...
class ThreeDSImporter(VRMLImporter): reader = Instance(tvtk.ThreeDSImporter, args=(), kw={'compute_normals': True}, allow_none=False, record=True) def has_output_port(self): return True def get_output_object(self): return self.reader.output_port def _file_name_changed(self, value): ...
def gist_gray(range, **traits): _data = dict(red=[(0.0, 0.0, 0.0), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0.), (0., 0., 0....