code
stringlengths
281
23.7M
class Base(Executor): def __init__(self): self.__success = True self.__results = [] def get_success(self): return self.__success def set_failed(self): self.__success = False def add_result(self, result): self.__results.append(result) def write_result(self, mfd...
class _CxVariableFromPatternMatch(): def __init__(self, unique_idx): self._unique_idx = unique_idx self.dict_variable_name = 'dict_match_{0}'.format(unique_idx) def src(self, indentation): return '{0}{1} = match.groupdict()'.format((_TAB_STR * indentation), self.dict_variable_name)
def add_block(parent): new_block_hash = os.urandom(32) h = get_height(parent) blocks[new_block_hash] = ((h + 1), parent) if (parent not in children): children[parent] = [] children[parent].append(new_block_hash) for i in range(16): if ((h % (2 ** i)) == 0): ancestors[...
def test_document_can_be_created_dynamically(): n = datetime.now() md = MyDoc(title='hello') md.name = 'My Fancy Document!' md.created_at = n inner = md.inner assert (inner is md.inner) inner.old_field = 'Already defined.' md.inner.new_field = ['undefined', 'field'] assert ({'title':...
def load_gii_data(filename, intent='NIFTI_INTENT_NORMAL'): logger = logging.getLogger(__name__) try: surf_dist_nib = nibabel.load(filename) except: logger.error('Cannot read {}'.format(filename)) sys.exit(1) numDA = surf_dist_nib.numDA try: array1 = surf_dist_nib.getA...
def test_ttLib_open_save_ttfont(tmp_path, ttfont_path, flavor): output_path = (tmp_path / 'TestTTF-Regular.ttf') args = ['-o', str(output_path), str(ttfont_path)] if (flavor is not None): args.extend(['--flavor', flavor]) __main__.main(args) assert output_path.exists() assert (TTFont(out...
def setup_to_fail(): shutil.copy('/etc/postfix/main.cf', '/etc/postfix/main.cf.bak') print(shellexec("sed -i 's/^inet_interfaces = .*/inet_interfaces = all/' /etc/postfix/main.cf")) print(shellexec('systemctl restart postfix')) (yield None) shutil.move('/etc/postfix/main.cf.bak', '/etc/postfix/main....
class ParcelParser(): def __init__(self, struct_store, data, android_version): self.struct_store = struct_store self.data = data self.pos = 0 self.android_version = android_version def parse_field(self, name: str, type_name: str, read_func, parent: Optional[Field]=None) -> Field:...
class CasavaSampleSheet(SampleSheet): def __init__(self, samplesheet=None, fp=None): SampleSheet.__init__(self, samplesheet, fp) if (self._data is None): self._data = TabFile.TabFile(delimiter=',', column_names=('FCID', 'Lane', 'SampleID', 'SampleRef', 'Index', 'Description', 'Control', ...
def update_latex_documents(latex_documents, latexoverrides): if (len(latex_documents) > 1): _message_box('Latex documents specified as a multi element list in the _config', 'This suggests the user has made custom settings to their build', '[Skipping] processing of automatic latex overrides') return ...
def save_segbits(file_name, segbits): with open(file_name, 'w') as fp: for (tag, bits) in segbits.items(): if (not len(bits)): continue line = (tag + ' ') line += ' '.join([bit_to_str(bit) for bit in sorted(list(bits))]) fp.write((line + '\n'))
def addPinSelect(fori2c, name, choice): global TXBuffer addSelector_Head(name, False) addSelector_Item('None', (- 1), (str(choice) == str((- 1))), False, '') for x in range(len(Settings.Pinout)): try: if (int((Settings.Pinout[x]['altfunc'] == 0)) and (int(Settings.Pinout[x]['canchang...
class OptionPlotoptionsPyramid3dSonificationContexttracksMappingVolume(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_int_param_template(tensor): name = tensor._attrs['name'] dtype = tensor._attrs['dtype'] if (dtype == 'int64'): return FUNC_CALL_INT64_PARAM_TEMPLATE.render(name=name) elif (dtype in ('int', 'int32')): return FUNC_CALL_INT32_PARAM_TEMPLATE.render(name=name) else: raise...
def test_get_contract_factory_with_valid_owned_manifest(w3): owned_manifest = get_ethpm_local_manifest('owned', 'with_contract_type_v3.json') owned_package = w3.pm.get_package_from_manifest(owned_manifest) owned_factory = owned_package.get_contract_factory('Owned') tx_hash = owned_factory.constructor()....
.unit .parametrize('ingestion_manifest_directory', ['populated_manifest_dir', 'populated_nested_manifest_dir'], indirect=['ingestion_manifest_directory']) def test_ingest_manifests(ingestion_manifest_directory): actual_result = manifests.ingest_manifests(str(ingestion_manifest_directory)) assert (sorted(actual_...
class Scene(Entity, ProjectMixin, CodeMixin): __auto_name__ = False __tablename__ = 'Scenes' __mapper_args__ = {'polymorphic_identity': 'Scene'} scene_id = Column('id', Integer, ForeignKey('Entities.id'), primary_key=True) shots = relationship('Shot', secondary='Shot_Scenes', back_populates='scenes'...
def test_apexrest_patch_request(): testutil.add_response('login_response_200') testutil.add_response('apexrest_patch_response_200') testutil.add_response('api_version_response_200') client = testutil.get_client() apexrest_result = client.apexrest(action='foo', request_params={'foo': 0}) assert ...
_post_request(models) class CityAutocompleteViewSet(APIView): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/autocomplete/city.md' _response() def post(self, request, format=None): (search_text, country, state) = prepare_search_terms(request.data) scope = ('recipient_location' if...
def DoUnroll(c_loop): s = c_loop._node if ((not isinstance(s.hi, LoopIR.Const)) or (not isinstance(s.lo, LoopIR.Const))): raise SchedulingError(f"expected loop '{s.iter}' to have constant bounds") iters = (s.hi.val - s.lo.val) orig_body = c_loop.body().resolve_all() unrolled = [] for i i...
class TestSimpleParser(TestCase): def test_empty(self): properties = simple_parser('') self.assertEqual(properties, {'family': ['default'], 'size': 12.0, 'weight': 'normal', 'stretch': 'normal', 'style': 'normal', 'variants': set(), 'decorations': set()}) def test_typical(self): properti...
class LabelImport(): def _get_derivations(klass, account: AbstractAccount) -> Dict[(Sequence[int], int)]: keypaths = account.get_key_paths() result: Dict[(Sequence[int], int)] = {} for (keyinstance_id, derivation_path) in keypaths.items(): result[derivation_path] = keyinstance_id...
def mindee_financial_parser(original_response: dict) -> FinancialParserDataClass: extracted_data = [] for (idx, page) in enumerate(original_response['document']['inference']['pages']): predictions = page.get('prediction', {}) customer_company_registrations = predictions.get('customer_company_reg...
def extractIkigainovelsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('ABG30D', 'Agreement of Being Gay for 30 Days', 'translated')] for (tagname, name, tl_typ...
def symlink(link_to, link_from): rm_dir_or_link(link_from) try: if PY32: os.symlink(link_to, link_from, target_is_directory=True) elif (not WINDOWS): os.symlink(link_to, link_from) except OSError: logger.log_exc() if (not os.path.islink(link_from)): ...
def _apply_string(*, value, collection, action, default, target, options): data = get_data_entry(collection, value).data options.update_if_not_set(**data.get('plot_map', {})) magics = data['magics'] actions = list(magics.keys()) if (len(actions) != 1): raise ValueError(('%s %s: one, and only...
_posts.route('/') _posts.route('/<username>') def do_view(username=None): if (not username): if ('username' in g.session): username = g.session['username'] posts = libposts.get_posts(username) users = libuser.userlist() return render_template('posts.view.html', posts=posts, username=...
class GreetingWorkflowImpl(GreetingWorkflow): _method async def get_status(self, arg1: QueryArgType1, arg2: QueryArgType2) -> QueryRetType: return QUERY_RET_TYPE _method async def push_status(self, arg1: SignalArgType1, arg2: SignalArgType2): pass async def get_greeting(self): ...
def note_value(s): if (not s): return (0.0, 0) r = 1.0 dots = count_seq(s) s = s[dots:] (num, ct) = peel_float(s, 1.0) s = s[ct:] if (s[0] == '*'): if (dots == 1): r = num else: r = (num * pow(2.0, float((dots - 1)))) elif (s[0] == '.'): ...
class ModelSaveCallback(tf.keras.callbacks.Callback): def __init__(self, steps, model, model_save_path, is_chief): super().__init__() self.steps = steps self.model = model if is_chief: self.model_save_path = model_save_path else: self.model_save_path =...
def test_namespace(): asset_path = 'assets/dashExtensions_default.js' if os.path.isfile(asset_path): os.remove(asset_path) ptl = assign(js_func) assert (ptl == {'variable': 'dashExtensions.default.function0'}) with open(asset_path, 'r') as f: assets_content = f.read() assert (ass...
class internet(): address = ('google.com', 80) check_frequency = 1 dns_cache = [] last_checked = (time.perf_counter() - check_frequency) connected = False def __new__(cls): if (not internet.connected): internet.dns_cache = internet.resolve() now = time.perf_counter() ...
class OptionPlotoptionsColumnSonificationDefaultspeechoptionsActivewhen(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, nu...
class OptionPlotoptionsVariwidePointEvents(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 TreeCompiler(SQLCompiler): CTE_POSTGRESQL_WITH_TEXT_ORDERING = '\n WITH RECURSIVE __tree (\n "tree_depth",\n "tree_path",\n "tree_ordering",\n "tree_pk"\n ) AS (\n SELECT\n 0 AS tree_depth,\n array[T.{pk}] AS tree_path,\n array[{order_b...
def get_args_parser() -> argparse.ArgumentParser: from .. import __version__ parser = argparse.ArgumentParser(add_help=False, description='Hydra') parser.add_argument('--help', '-h', action='store_true', help="Application's help") parser.add_argument('--hydra-help', action='store_true', help="Hydra's he...
class BadgeRole(SphinxRole): def __init__(self, color: Optional[str]=None, *, outline: bool=False) -> None: super().__init__() self.color = color self.outline = outline def run(self) -> Tuple[(List[nodes.Node], List[nodes.system_message])]: node = nodes.inline(self.rawtext, self....
class HurricaneDatabase(Dataset): home_page = ' def __init__(self, *, bassin='atlantic', url=None): if (url is None): url = URLS[bassin.lower()] path = download_and_cache(url) p = [] with open(path) as f: lines = f for line in lines: ...
class ManufacturerSpecificData(Packet): def __init__(self, name='Manufacturer Specific Data'): self.name = name self.payload = [UShortInt('Manufacturer ID', endian='little'), Itself('Payload')] def decode(self, data): for p in self.payload: data = p.decode(data) retur...
class _UnitTestSubConfig(_UnitTestBaseConfig): ENV_CODE = 'uts' COMPONENT_NAME = 'Unit Test SubConfig Component' UNITTEST_CFG_A = 'SUB_UNITTEST_CFG_A' SUB_UNITTEST_1 = property((lambda self: ((self.UNITTEST_CFG_A + ':') + self.UNITTEST_CFG_D))) UNITTEST_CFG_D = 'SUB_UNITTEST_CFG_D' SUB_UNITTEST_...
def from_BE(be_stream): if (len(be_stream) == 4): d1 = int(be_stream[:2], 16) d2 = int(be_stream[2:], 16) if ((d1 < 32) or (d2 < 32)): raise ValueError('Invalid BE1 stream digit') index = (((d2 - 32) * 224) + (d1 - 32)) x = ((index // 224) - 112) y = ((ind...
_validator def validate_packages(request, **kwargs): packages = request.validated.get('packages') if (packages is None): return bad_packages = [] validated_packages = [] for p in packages: package = Package.get(p) if (not package): bad_packages.append(p) e...
def replace_datetime_refs(string, get_datetime): match = re.search(COMMAND_W_DT, string) if ((match is not None) and (get_datetime is not None)): delay = match.group(1) dt = get_datetime(delay) dt_string = dt.strftime('%Y-%m-%d') return re.sub(COMMAND_W_DT, dt_string, string) ...
class TestPrioQueue(object): def setup_method(self, method): raw_actions = [0, 1, 2, 3, 3, 3, 4, 5, 6, 7, 8, 9] self.queue = JobQueue() for action in raw_actions: self.queue.add_task(action, priority=10) self.queue.add_task(7, priority=5) def get_tasks(self): ...
class BaseBindTest(object): def setUp(self): self.xl = CreateObject('Excel.Application', dynamic=self.dynamic) def tearDown(self): for wb in self.xl.Workbooks: wb.Close(0) self.xl.Quit() del self.xl def test(self): xl = self.xl xl.Visible = 0 ...
class Solution(): def nextGreaterElement(self, n: int) -> int: def find_next_greater(n1): prev = None for i in range((len(n1) - 1), (- 1), (- 1)): curr = n1[i] if (prev is None): prev = curr continue ...
.django_db(transaction=True) .parametrize('url_name, view_name, required_params', ALL_URLS_DATA) def test_relationship_url_name_with_view_name(url_name, view_name, required_params, event_data1): params = get_reverse_params(required_params, **event_data1) path = reverse(url_name, kwargs=params) response = re...
class PyBikesScraper(object): proxy_enabled = False last_request = None requests_timeout = 300 retry = False retry_opts = {} def __init__(self, cachedict=None, headers=None): self.headers = (headers if isinstance(headers, dict) else {}) self.headers.setdefault('User-Agent', 'PyBi...
class DefListProcessor(BlockProcessor): RE = re.compile('(^|\\n)[ ]{0,3}:[ ]{1,3}(.*?)(\\n|$)') NO_INDENT_RE = re.compile('^[ ]{0,3}[^ :]') def test(self, parent, block): return bool(self.RE.search(block)) def run(self, parent, blocks): raw_block = blocks.pop(0) m = self.RE.searc...
def ensure_thrift_exception(fn: F) -> F: (fn) async def wrapper(self, *args, **kwargs): try: return (await fn(self, *args, **kwargs)) except Exception as e: if isinstance(e, fcr_ttypes.SessionException): raise e elif isinstance(e, fcr_ttypes.In...
class MouseEvent(UIEvent): def altKey(self): return JsBoolean.JsBoolean.get(js_code='event.altKey') def button(self): return JsNumber.JsNumber('event.button', is_py_data=False) (['Safari']) def buttons(self): return JsNumber.JsNumber('event.buttons', is_py_data=False) def isT...
def throttle_with_time(dt, node, rate_tol: float=0.95, log_level: int=DEBUG): time_fn = (lambda : (time.monotonic_ns() / .0)) node_name = node.ns_name color = node.color effective_log_level = node.backend.log_level log_time = 2 def _throttle_with_time(source): def subscribe(observer, sch...
def test_create_attr_reserved_name(generate_data: pd.DataFrame): instance = _XYZData(generate_data) with pytest.raises(ValueError, match='The proposed name Q_AZI is a reserved name'): instance.create_attr('Q_AZI', attr_type='CONT', value=823.0) instance.create_attr('Q_AZI', attr_type='CONT', value=8...
.parametrize('col, expected_index', split_distinct_test) def test_split_distinct(col, expected_index): data = pd.DataFrame({'A': [it for it in range(0, 200)], 'B': ([1, 2, 3, 4, 5, 6, 6, 6, 6, 6] * 20), 'C': (['A', 'B', 'C', 'D', 'E', 'F', 'F', 'F', 'F', 'F'] * 20), 'time': (([date(2019, 1, (it + 1)) for it in rang...
class TestOefSearchHandler(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'tac_negotiation') is_agent_to_agent_messages = False def setup(cls): super().setup() cls.oef_search_handler = cast(OefSearchHandler, cls._skill.skill_context.handlers.oef) ...
def main(): if (sys.argv[2] == 'streamed'): reader = StreamReader(open(sys.argv[1], 'rb')) records = [stringify_record(r) for r in reader.records if (not isinstance(r, MessageIndex))] print(json.dumps({'records': records}, indent=2)) else: reader = SeekingReader(open(sys.argv[1],...
def test_gaussian_blur(test_device: Device, blur_input: BlurInput) -> None: if ((test_device.type == 'cpu') and (blur_input.dtype == torch.float16)): warn('half float is not supported on the CPU because of `torch.mm`, skipping') pytest.skip() manual_seed(2) tensor = torch.randn(3, blur_input...
def create_dock_window(parent, editor): window = DockWindow(parent).control button1 = wx.Button(window, (- 1), 'Button 1') button2 = wx.Button(window, (- 1), 'Button 2') button3 = wx.Button(window, (- 1), 'Button 3') button4 = wx.Button(window, (- 1), 'Button 4') button5 = wx.Button(window, (- 1...
def initialize_value(distribution: Distribution, initialize_from_prior: bool=False): sample_val = distribution.sample() if initialize_from_prior: return sample_val support = distribution.support if isinstance(support, dist.constraints.independent): support = support.base_constraint i...
class base_dict_test_case(unittest.TestCase): def test__bool__(self): b = BaseDict() self.assertFalse(b) self.assertFalse(bool(b)) self.assertEqual(b, b.dict()) b = BaseDict() b['a'] = 1 self.assertTrue(b) self.assertTrue(bool(b)) self.assertEq...
(frozen=True) class ContextInfo(): ancestor: object array: Optional[list] index: Optional[int] name: Optional[str] def is_root(self): return (self.ancestor is None) def is_head(self): return (self.in_array and (self.index == 0)) def is_last(self): return (self.in_arra...
class OptionSeriesLineSonificationDefaultspeechoptionsMappingTime(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 OptionPlotoptionsAreaSonificationDefaultinstrumentoptionsMappingFrequency(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 OptionPlotoptionsLollipopSonificationContexttracksMappingHighpassResonance(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, tex...
def test_purity_checker(casper, w3, funded_accounts, purity_checker): acct = funded_accounts[0] external_acct = funded_accounts[1] non_submitted_external_acct = funded_accounts[2] some_pure_contract = deploy_minimal_contract(w3, acct) purity_checker.functions.submit(some_pure_contract).transact() ...
def test_normalize_multiplicative_h5_cool(capsys): outfile_one = NamedTemporaryFile(suffix='.cool', delete=False) outfile_one.close() args = '--matrices {} --normalize multiplicative --multiplicativeValue {} -o {}'.format(matrix_one_cool, 2, outfile_one.name).split() compute(hicNormalize.main, args, 5) ...
class BLEServer(): def __init__(self, name='', receiverfunc=None, pmodefunc=None): self.receiverfunc = receiverfunc self.name = name self.bleno = None self.service = None self.initialized = False self.address = '' self.modefunc = pmodefunc def start(self):...
class GameHoldemWinnerDetectorIntegrationTest(unittest.TestCase): def test_get_winners(self): player1 = Player('player-1', 'Player One', 800.0) player2 = Player('player-2', 'Player Two', 600.0) player3 = Player('player-3', 'Player Three', 1200.0) player4 = Player('player-4', 'Player ...
class SKT_OT_removeShapeKeys(Operator): bl_idname = 'skt.remove_src_shape_keys' bl_label = 'Remove Shape Keys of Source' bl_description = 'Remove all Shape Keys of Source Mesh' bl_context = 'objectmode' bl_options = {'REGISTER', 'INTERNAL', 'UNDO'} def poll(cls, context): skt = context.s...
class Card(Dict): id: Optional[int] = None cardId: Optional[int] = None name: Optional[str] = None effect: Optional[str] = None zz: Optional[str] = None mainType: Optional[str] = None type: Optional[str] = None level: Optional[str] = None attribute: Optional[str] = None atk: Opti...
class OptionSeriesXrangeSonificationTracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesXrangeSonificationTracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesXrangeSonificationTracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesXrangeSonificationTracksMappingT...
class OrderedDefaultDict(collections.OrderedDict): def __init__(self, default_factory=None, *args, **kwds): if ((default_factory is not None) and (not isinstance(default_factory, Callable))): raise TypeError('First argument must be callable') super(OrderedDefaultDict, self).__init__(*arg...
class IDialog(IWindow): cancel_label = Str() help_id = Str() help_label = Str() ok_label = Str() resizeable = Bool(True) return_code = Int(OK) style = Enum('modal', 'nonmodal') def open(self): def _create_buttons(self, parent): def _create_contents(self, parent): def _create_...
class PySparkPipelineModelTransformer(TypeTransformer[PipelineModel]): _TYPE_INFO = BlobType(format='binary', dimensionality=BlobType.BlobDimensionality.MULTIPART) def __init__(self): super(PySparkPipelineModelTransformer, self).__init__(name='PySparkPipelineModel', t=PipelineModel) def get_literal_...
def upgrade(): op.execute('ALTER TABLE swaps DROP CONSTRAINT swaps_pkey CASCADE') op.create_primary_key('swaps_pkey', 'swaps', ['block_number', 'transaction_hash', 'trace_address']) op.create_index('arbitrage_swaps_swaps_idx', 'arbitrage_swaps', ['swap_transaction_hash', 'swap_trace_address'])
.parametrize('action', ['view_action', 'publish']) def test_actions_rendered(admin_client, article, action): url = reverse('admin:blog_article_changelist') changelist = admin_client.get(url) input_name = '_action__articleadmin__admin__{}__blog__article__{}'.format(action, article.pk) assert (input_name ...
class ImageControl(wx.Window): _selectedPenDark = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DSHADOW), 1, wx.SOLID) _selectedPenLight = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DHIGHLIGHT), 1, wx.SOLID) def __init__(self, parent, bitmap, selected=None, handler=None, padding=10): if (...
class QstatJob(): def __init__(self, jobid, name, user, state, queue): self.id = jobid self.name = name self.user = user self.state = state self.queue = queue try: self.queue_name = self.queue.split('')[0] except IndexError: self.queue_...
class EspeStation(BikeShareStation): def __init__(self, data): super(EspeStation, self).__init__() self.name = data['nombreEstacion'] self.latitude = float(data['latitud']) self.longitude = float(data['longitud']) self.bikes = int(data['bicicletasEnEstacion']) self.fr...
class _SortFilterProxyModel(QSortFilterProxyModel): _filter_type: MatchType = MatchType.UNKNOWN _filter_match: Optional[Union[(str, Address)]] = None _account: Optional[AbstractAccount] = None def set_account(self, account: AbstractAccount) -> None: self._account = account def set_filter_mat...
class ArgsKwargs(): def __init__(self, args, kwargs, func=None): assert isinstance(kwargs, dict) assert isinstance(args, (list, tuple)) args = list(args) self.args = args self.kwargs = kwargs self.func = func self.positionals_only = [] self.defaults = ...
class TestDOHB64(unittest.TestCase): _provider(b64_source) def test_b64_encode(self, input, output): self.assertEqual(utils.doh_b64_encode(input), output) _provider(b64_source) def test_b64_decode(self, output, input): self.assertEqual(utils.doh_b64_decode(input), output) def test_b6...
def test_gpg_verify_invalid_sig(common): with pytest.raises(BadSignature): import_key('gpgsync_test_pubkey.asc', common.gpg.homedir) msg = open(get_gpg_file('signed_message-invalid.txt'), 'rb').read() msg_sig = open(get_gpg_file('signed_message-invalid.txt.sig'), 'rb').read() common....
.parametrize('word,morph', [('', ('', '')), ('', ('', '')), ('', ('', ';-')), ('', ('', ';-')), ('', ('', '-;-')), ('', ('', ';'))]) def test_ja_morph(NLP, word, morph): doc = NLP(word) (reading, infl) = morph assert (reading == doc[0].morph.get('Reading')[0]) if (infl == ''): assert ('Inflectio...
def apply_patch(file_content: str, patches: list[dict[(str, Any)]]): content_lines = file_content.strip().split('\n') new_content = [] last_end_line = (- 1) for patch in patches: if (patch['start'] <= last_end_line): raise ValueError(f"Line ranges overlap. Previous range ends at line...
def reconstruct_polynomial_from_samples(root_of_unity, samples, zero_polynomial_function, shifted_zero_poly=None, eval_shifted_zero_poly=None, inv_eval_shifted_zero_poly=None): zero_vector = [(0 if (x is None) else 1) for x in samples] time_a = time() (zero_eval, zero_poly) = zero_polynomial_function(root_o...
.usefixtures('use_tmpdir') def test_that_loading_non_existant_workflow_job_gives_validation_error(): test_config_file_base = 'test' test_config_file_name = f'{test_config_file_base}.ert' test_config_contents = dedent('\n NUM_REALIZATIONS 1\n LOAD_WORKFLOW_JOB does_not_exist\n ') wi...
class OptionPlotoptionsTimelineSonificationContexttracksMappingRate(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def test_recursive_update_new_fields(): to_update = dict(subdict=dict(to_update=1)) new_values = dict(subdict=dict(to_update2=False)) with pytest.raises(ValueError, match="Key 'to_update2' is not contained in the dictionary to update."): recursive_update(to_update, new_values) assert ('to_update...
class NotificationType(MibNode): objects = () status = 'current' description = '' reference = '' def getObjects(self): return self.objects def setObjects(self, *args, **kwargs): if kwargs.get('append'): self.objects += args else: self.objects = arg...
def test_dummy_agent(): AgentRegistry.register(DummyAgent()) ctx = MagicMock(spec=grpc.ServicerContext) agent = AgentRegistry.get_agent('dummy') metadata_bytes = json.dumps(asdict(Metadata(job_id=dummy_id))).encode('utf-8') assert (agent.create(ctx, '/tmp', dummy_template, task_inputs).resource_meta...
def lambda_handler(s3_notification_event: Dict[(str, List[Any])], _) -> int: try: for record in s3_notification_event['Records']: event_name: str = record['eventName'] if ('Digest' in record['s3']['object']['key']): return 200 if event_name.startswith('Obj...
.param_file((FIXTURE_PATH / 'attributes.md')) def test_attributes(file_params, sphinx_doctree_no_tr: CreateDoctree): sphinx_doctree_no_tr.set_conf({'extensions': ['myst_parser'], 'myst_enable_extensions': ['attrs_inline', 'attrs_block']}) result = sphinx_doctree_no_tr(file_params.content, 'index.md') file_p...
def _import(path_str, replace=False): if isinstance(replace, str): replace = eval(replace.capitalize()) path = Path(path_str) with path.open() as fp: new_networks = yaml.safe_load(fp) with _get_data_folder().joinpath('network-config.yaml').open() as fp: old_networks = yaml.safe_l...
class GLULayer(nn.Module): def __init__(self, n_input, n_output, n_sublayers=3, kernel_size=3, pool_size=2, eps=1e-05): super().__init__() self.args = (n_input, n_output) self.kwargs = {'n_sublayers': n_sublayers, 'kernel_size': kernel_size, 'pool_size': pool_size} lin_bn_layers = []...
class TestRemoveSkillWithPublicId(): def setup_class(cls): cls.runner = CliRunner() cls.agent_name = 'myagent' cls.cwd = os.getcwd() cls.t = tempfile.mkdtemp() dir_path = Path('packages') tmp_dir = (cls.t / dir_path) src_dir = (cls.cwd / Path(ROOT_DIR, dir_pat...
class VideoTestCase(unittest.TestCase): def test_to_xml_method_is_working_properly(self): v = Video() v.width = 1024 v.height = 778 t = Track() t.enabled = True t.locked = False v.tracks.append(t) f = File() f.duration = 34 f.name = 'sh...
def test_dependency_set_computations(): node0 = OperatorNode({}, {'name': 'test0', 'type': 'none'}) node1 = OperatorNode({}, {'name': 'test1', 'type': 'none'}) node2 = OperatorNode({}, {'name': 'test2', 'type': 'none', 'upstream_dependencies': ['test0', 'test1']}) node3 = OperatorNode({}, {'name': 'test...
def generate_setup(s): return ([b.multiply(b.G1, pow(s, i, MODULUS)) for i in range((WIDTH + 1))], [b.multiply(b.G2, pow(s, i, MODULUS)) for i in range((WIDTH + 1))], [b.multiply(b.G1, field.eval_poly_at(l, s)) for l in LAGRANGE_POLYS], [b.multiply(b.G2, field.eval_poly_at(l, s)) for l in LAGRANGE_POLYS])
def test_cli_ignore_notebooks(poetry_venv_factory: PoetryVenvFactory) -> None: with poetry_venv_factory('example_project') as virtual_env: issue_report = f'{uuid.uuid4()}.json' result = virtual_env.run(f'deptry . --ignore-notebooks -o {issue_report}') assert (result.returncode == 1) ...