code
stringlengths
281
23.7M
('unique_count') class UniqueCountPipe(ByPipe): minimum_args = 1 def output_schemas(cls, arguments, event_schemas): if (len(event_schemas) < 1): return event_schemas event_schemas = list(event_schemas) (first_event_type,) = event_schemas[0].schema.keys() if any((v for...
class FieldProjectionAngleMonitor(AbstractFieldProjectionMonitor): proj_distance: float = pydantic.Field(1000000.0, title='Projection Distance', description='Radial distance of the projection points from ``local_origin``.', units=MICROMETER) theta: ObsGridArray = pydantic.Field(..., title='Polar Angles', descri...
class ManifestStaticS3Storage(ManifestFilesMixin, StaticS3Storage): default_s3_settings = StaticS3Storage.default_s3_settings.copy() default_s3_settings.update({'AWS_S3_MAX_AGE_SECONDS_CACHED': (((60 * 60) * 24) * 365)}) def post_process(self, *args, **kwargs): initial_aws_s3_max_age_seconds = self....
class CrossAttnUpBlock2D(nn.Module): def __init__(self, in_channels: int, out_channels: int, prev_output_channel: int, temb_channels: int, dropout: float=0.0, num_layers: int=1, resnet_eps: float=1e-06, resnet_time_scale_shift: str='default', resnet_act_fn: str='swish', resnet_groups: int=32, resnet_pre_norm: bool=...
class Foo(HasTraits): a = Any b = Bool s = Str i = Instance(HasTraits) e = Event d = Delegate('i') p = Property def _get_p(self): return self._p def _set_p(self, p): self._p = p p_ro = Property def _get_p_ro(self): return id(self) p_wo = Property ...
class RLAB(Lab): BASE = 'xyz-d65' NAME = 'rlab' SERIALIZE = ('--rlab',) WHITE = WHITES['2deg']['D65'] CHANNELS = (Channel('l', 0.0, 100.0), Channel('a', (- 125.0), 125.0, flags=FLG_MIRROR_PERCENT), Channel('b', (- 125.0), 125.0, flags=FLG_MIRROR_PERCENT)) ENV = Environment(WHITE, YN, SURROUND['a...
class PopupCircularProgress(PopupSlider): defaults = [d for d in PopupSlider.defaults if (not d[0].startswith('bar_border'))] defaults += [('start_angle', 0, "Starting angle (in degrees) for progress marker. 0 is 12 o'clock and angle increases in a clockwise direction."), ('clockwise', True, 'Progress increases...
def get_frame_info(frame, lineno, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None): f_locals = getattr(frame, 'f_locals', {}) if _getitem_from_frame(f_locals, '__traceback_hide__'): return None ...
class OptionPlotoptionsScatter3dSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool)...
_routes.route('/<string:event_identifier>/sessions/dates') _event_id def get_dates(event_id): date_list = list(zip(*db.session.query(func.date(Session.starts_at)).distinct().filter((Session.event_id == event_id), (Session.starts_at != None), or_((Session.state == 'accepted'), (Session.state == 'confirmed'))).order_...
class ExprCursorA(CursorArgumentProcessor): def __init__(self, many=False): self.match_many = many def _cursor_call(self, expr_pattern, all_args): if self.match_many: if isinstance(expr_pattern, list): if all((isinstance(ec, PC.ExprCursor) for ec in expr_pattern)): ...
def validate_observation_statistics(statistics: dict, validation_callback: Callable): def process_key(_key: Any): if (('min' in statistics[_key]) and isinstance(statistics[_key]['min'], np.ndarray)): statistics[_key]['min'] = np.min(np.asarray(statistics[_key]['values'])) statistics[...
class Object(Field): name = 'object' _coerce = True def __init__(self, doc_class=None, dynamic=None, properties=None, **kwargs): if (doc_class and (properties or (dynamic is not None))): raise ValidationException('doc_class and properties/dynamic should not be provided together') ...
def load(profile_path, limit=200, quiet=False, extract_features_vector=True): profile_file = os.path.join(profile_path, 'profile.json') tweets_path = os.path.join(profile_path, 'tweets') if (not os.path.exists(profile_file)): return None if (not os.path.exists(tweets_path)): return None ...
def get_histogram_for_distribution(*, current_distribution: Distribution, reference_distribution: Optional[Distribution]=None, title: str='', xaxis_title: Optional[str]=None, yaxis_title: Optional[str]=None, color_options: ColorOptions): current_histogram = HistogramData(name='current', x=pd.Series(current_distribu...
class GraphQLBackendInstrumentation(AbstractInstrumentedModule): name = 'graphql' instrument_list = [('graphql.backend.core', 'GraphQLCoreBackend.document_from_string'), ('graphql.backend.cache', 'GraphQLCachedBackend.document_from_string')] def get_graphql_tx_name(self, graphql_doc): try: ...
def test_get_version_raise(): econfig = ecl_config.Ecl100Config() class_file = inspect.getfile(ecl_config.Ecl100Config) class_dir = os.path.dirname(os.path.abspath(class_file)) msg = os.path.join(class_dir, 'ecl100_config.yml') with pytest.raises(ValueError, match=msg): econfig._get_version(...
def test_fill_value(): def f(x, y, z): return (((2 * (x ** 3)) + (3 * (y ** 2))) - z) x = np.linspace(1, 4, 11) y = np.linspace(4, 7, 22) z = np.linspace(7, 9, 33) data = f(*np.meshgrid(x, y, z, indexing='ij', sparse=True)) pts = np.array([[0.1, 6.2, 8.3], [3.3, 5.2, 10.1]]) op = Reg...
(scope='function') def policy(db: Session, oauth_client: ClientDetail, storage_config: StorageConfig) -> Generator: access_request_policy = Policy.create(db=db, data={'name': 'example access request policy', 'key': 'example_access_request_policy', 'client_id': oauth_client.id, 'execution_timeframe': 7}) access_...
class CovidStateMenu(menus.ListPageSource): def __init__(self, entries: Iterable[str]): super().__init__(entries, per_page=1) async def format_page(self, menu: GenericMenu, state) -> str: embed = discord.Embed(color=(await menu.ctx.embed_colour()), title='Covid-19 | USA | {} Statistics'.format(s...
class TabRowContextMenu(JsPackage): lib_set_var = False def add(self, name: str, url: str, icon: str=None): js_service = self.page.js.fncs.service() if (icon is not None): return JsObjects.JsVoid(('%s.options.rowContextMenu.push({label: \'<i class="%s" style="margin-right:5px"></i>%s...
def expand_pos(wordmap): if (wordmap['pos'] == 'A'): wordmap['pos'] = 'ADJECTIVE' elif (wordmap['pos'] == 'N'): wordmap['pos'] = 'NOUN' elif (wordmap['pos'] == 'V'): wordmap['pos'] = 'VERB' elif (wordmap['pos'] == 'P'): wordmap['pos'] = 'PARTICLE' elif (wordmap['pos']...
class TintPreference(widgets.RGBAButtonPreference, widgets.CheckConditional): name = 'plugin/moodbar/tint' condition_preference_name = 'plugin/moodbar/use_tint' default = 'rgba(255, 255, 255, 0.2)' def __init__(self, preferences, widget): widgets.RGBAButtonPreference.__init__(self, preferences, ...
class OptionSeriesTreegraphSonificationDefaultspeechoptionsMappingTime(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): ...
_required _required _required(NetworkAdminPermission) _required _POST def admin_network_form(request): qs = request.GET.copy() if (request.POST['action'] == 'update'): try: net = Subnet.objects.select_related('owner', 'dc_bound').get(name=request.POST['adm-name']) except Subnet.DoesN...
class OptionSeriesSunburstSonificationContexttracksMappingHighpassFrequency(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: st...
def test_load_schema_output_is_correct_6(): ' load_schema_dir = join(abspath(dirname(__file__)), 'load_schema_test_6') schema_path = join(load_schema_dir, 'A.avsc') loaded_schema = fastavro.schema.load_schema(schema_path, _write_hint=False) expected_schema = {'name': 'A', 'type': 'record', 'fields':...
class TestCompress(unittest.TestCase): def test_compress(self, func): self.assertEqual(func(None), None) self.assertEqual(func(''), '') self.assertEqual(func('AABBCC'), 'AABBCC') self.assertEqual(func('AAABCCDDDDE'), 'A3BC2D4E') self.assertEqual(func('BAAACCDDDD'), 'BA3C2D4')...
def test_make_subprocess(tmp_path: Path) -> None: process = local.start_controller(tmp_path, 'python -c \'import os;print(os.environ["SUBMITIT_LOCAL_JOB_ID"])\'', timeout_min=1) paths = utils.JobPaths(tmp_path, str(process.pid), 0) pg = process.pid process.wait() stdout = paths.stdout.read_text() ...
class _Keywords(_Filter): underscore_name = 'keywords' def generate_elasticsearch_query(cls, filter_values: List[str], query_type: _QueryType, **options) -> ES_Q: keyword_queries = [] fields = ['recipient_name', 'naics_description', 'product_or_service_description', 'transaction_description', 'p...
class OptionPlotoptionsAreasplinerangeSonificationPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class TestSuperFencesCustomExceptionAttrList(util.MdCase): extension = ['pymdownx.superfences', 'attr_list'] extension_configs = {'pymdownx.superfences': {'custom_fences': [{'name': 'test', 'class': 'test', 'format': custom_format, 'validator': custom_validator_except}]}} def test_custom_fail_exception(self...
class TestRansomNote(unittest.TestCase): def test_ransom_note(self): solution = Solution() self.assertRaises(TypeError, solution.match_note_to_magazine, None, None) self.assertEqual(solution.match_note_to_magazine('', ''), True) self.assertEqual(solution.match_note_to_magazine('a', '...
def build_model(): num_labels = 20 kernel = 3 input_tensor = Input(shape=(320, 320, 3)) x = Conv2D(64, (kernel, kernel), activation='relu', padding='same', name='conv1_1', kernel_initializer='he_normal', bias_initializer='zeros')(input_tensor) x = BatchNormalization()(x) x = Conv2D(64, (kernel, ...
def load_profiles_info_1_5() -> Tuple[(Profile, Dict[(str, Any)])]: flags: Namespace = get_flags() profile_renderer = ProfileRenderer(getattr(flags, 'VARS', {})) profile_name = find_profile_name(flags.PROFILE, flags.PROJECT_DIR, profile_renderer) raw_profiles = read_profile(flags.PROFILES_DIR) raw_p...
def test_debug_after_response_sent(test_client_factory): async def app(scope, receive, send): response = Response(b'', status_code=204) (await response(scope, receive, send)) raise RuntimeError('Something went wrong') app = ServerErrorMiddleware(app, debug=True) client = test_client_...
def get_token_font_size_feature(previous_token: Optional[LayoutToken], current_token: LayoutToken): if (not previous_token): return 'HIGHERFONT' previous_font_size = previous_token.font.font_size current_font_size = current_token.font.font_size if ((not previous_font_size) or (not current_font_s...
class OptionSeriesWordcloudSonificationContexttracksMappingFrequency(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 MessageBox(QtWidgets.QMessageBox): def __init__(self, text: Union[(str, List[str])], title: str, default_button=QtWidgets.QMessageBox.Ok, icon=QtWidgets.QMessageBox.Icon.Information, parent=None) -> int: super().__init__(parent) if isinstance(text, list): self.setText('\n'.join(tex...
class Github(IntervalModule): settings = (('format', 'format string'), ('status', 'Dictionary mapping statuses to the text which represents that status type. This defaults to ``GitHub`` for all status types.'), ('colors', 'Dictionary mapping statuses to the color used to display the status text'), ('refresh_icon', ...
def get_casava_sample_sheet(samplesheet=None, fp=None, FCID_default='FC1'): if (fp is not None): sample_sheet_fp = fp else: sample_sheet_fp = io.open(samplesheet, 'rt') sample_sheet_content = ''.join(sample_sheet_fp.readlines()) try: iem = IEMSampleSheet(fp=io.StringIO(sample_she...
def send_mail(to, template, context): html_content = render_to_string(f'accounts/emails/{template}.html', context) text_content = render_to_string(f'accounts/emails/{template}.txt', context) msg = EmailMultiAlternatives(context['subject'], text_content, settings.DEFAULT_FROM_EMAIL, [to]) msg.attach_alte...
.usefixtures('use_tmpdir') def test_that_empty_job_directory_gives_warning(): test_config_file_base = 'test' test_config_file_name = f'{test_config_file_base}.ert' test_config_contents = dedent('\n NUM_REALIZATIONS 1\n DEFINE <STORAGE> storage/<CONFIG_FILE_BASE>-<DATE>\n RUNPATH <STORA...
class ConcatenateTanhTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(ConcatenateTanhTestCase, self).__init__(*args, **kwargs) self._test_id = 0 def _run_concatenate(self, *, concatenate_op, input_shapes, dim=None, test_name='concatenate_tanh_cat', input_type='float16'): ...
class DeleteFileCommand(): def __init__(self) -> None: self._deleted_files: List[str] = [] def execute(self, filename: str) -> None: print(f'deleting {filename}') self._deleted_files.append(filename) def undo(self) -> None: filename = self._deleted_files.pop() print(f...
class Cycle(): name: str top_line: str = None bottom_line: str = None small_icon: str = None def __init__(self, name: str, config: Dict[(str, str)], computer: Computer): self.name = name if ('top_line' in config['top_line']): self.top_line = config['top_line'] if ...
class FileDialogDemo(HasTraits): file_name = File() open = Button('Open...') traits_view = View(HGroup(Item('open', show_label=False), '_', Item('file_name', style='readonly', springy=True)), width=0.5) def _open_changed(self): file_name = open_file(extensions=TextInfo(), filter='Python file (*....
(name='api.vm.base.tasks.vm_create_cb', base=MgmtCallbackTask, bind=True) () def vm_create_cb(result, task_id, vm_uuid=None): vm = Vm.objects.select_related('dc').get(uuid=vm_uuid) dc_settings = vm.dc.settings msg = result.get('message', '') if ((result['returncode'] == 0) and (msg.find('Successfully cr...
class OFPTableFeaturePropUnknown(OFPTableFeatureProp): def __init__(self, type_, length=None, data=None): super(OFPTableFeaturePropUnknown, self).__init__(type_, length) self.data = data def _parse_prop(cls, buf): return {'data': buf} def _serialize_prop(self): return self.da...
class CategoricalCrossentropy(Loss): names: Optional[Sequence[str]] missing_value: Optional[Union[(str, int)]] _name_to_i: Dict[(str, int)] def __init__(self, *, normalize: bool=True, names: Optional[Sequence[str]]=None, missing_value: Optional[Union[(str, int)]]=None, neg_prefix: Optional[str]=None, la...
class EmbeddedModelRegistry(ModelRegistry): def __init__(self, system_app: (SystemApp | None)=None, heartbeat_interval_secs: int=60, heartbeat_timeout_secs: int=120): super().__init__(system_app) self.registry: Dict[(str, List[ModelInstance])] = defaultdict(list) self.heartbeat_interval_secs...
class Section(BaseObject): def __init__(self, api=None, category_id=None, created_at=None, description=None, html_url=None, id=None, locale=None, manageable_by=None, name=None, outdated=None, position=None, sorting=None, source_locale=None, updated_at=None, url=None, user_segment_id=None, **kwargs): self.ap...
def test_two_step_unwrap(): first_config = UnwrapPostProcessorConfiguration(data_path='results') second_config = UnwrapPostProcessorConfiguration(data_path='info') data = {'results': [{'info': {'email': '', 'preferences': {}}}, {'info': {'email': '', 'preferences': {}}}]} first_processor = UnwrapPostPro...
class VideoEditor(Editor): control = Instance(QVideoWidget) surface = Any() media_content = Any() media_player = Instance(QMediaPlayer) aspect_ratio = AspectRatio() state = PlayerState() position = Float() duration = Float() media_status = MediaStatus() buffer = Range(0, 100) ...
def get_checksum(item): userdata = item['UserData'] checksum = ('%s_%s_%s_%s_%s_%s_%s' % (item['Etag'], userdata['Played'], userdata['IsFavorite'], userdata.get('Likes', '-'), userdata['PlaybackPositionTicks'], userdata.get('UnplayedItemCount', '-'), userdata.get('PlayedPercentage', '-'))) return checksum
class AllChildren(Rule): rule: Rule combined_rule: Rule def __init__(self, rule: Rule, get_children: Callable[([Any], Dict[(str, Any)])], construct: Callable[([type, Dict[(str, Any)]], Any)], name: str='all_children') -> None: Rule.__init__(self, name) self.rule = rule self.combined_...
def test_check_feeder_broker_connection(mocker): from feeder.util.feeder import check_connection class MockDevice(dict): gatewayHid = 'gateway_hid' device = MockDevice() session = mocker.Mock() broker = mocker.Mock() broker._sessions = {'gateway_hid': (session, None)} session.return_...
def Run(params): from mu_repo.get_repos_and_curr_branch import GetReposAndCurrBranch from mu_repo.repos_with_changes import ComputeReposWithChangesFromCurrentBranchToOrigin repos_and_curr_branch = GetReposAndCurrBranch(params) keywords = {} if (len(params.args) < 2): Print('Not enough argume...
_index_loaded def default_search_with_decks(editor: aqt.editor.Editor, textRaw: Optional[str], decks: List[int]): if (textRaw is None): return index = get_index() if (len(textRaw) > 3000): if ((editor is not None) and (editor.web is not None)): UI.empty_result('Query was <b>too l...
.feature('unit') .story('south') class TestServicesSouthServer(): def south_fixture(self, mocker): def cat_get(): config = _TEST_CONFIG config['plugin']['value'] = config['plugin']['default'] return config mocker.patch.object(FledgeMicroservice, '__init__', return...
class TestElaborate(unittest.TestCase): pitch_motif = [80, 77, None] duration_motif = [2, 1, 1] scale = [5, 7, 8, 10, 0, 1, 4] steps = [(- 1), (- 1), (- 1)] def test_right(self): out = elaborate(self.pitch_motif, self.duration_motif, 0, self.steps, self.scale, 'right', (1 / 4)) expec...
def test_get_raw_message_serialization(): kwargs_arg = ContractApiMessage.Kwargs({'key_1': 1, 'key_2': 2}) msg = ContractApiMessage(message_id=1, dialogue_reference=(str(0), ''), target=0, performative=ContractApiMessage.Performative.GET_RAW_MESSAGE, ledger_id='some_ledger_id', contract_id='some_contract_id', c...
def test_hicCompareMatrices_doubleMinusOneEqual0(): outfile = NamedTemporaryFile(suffix='.cool', delete=False) outfile.close() args = '--matrices {} {} --outFileName {} --operation diff'.format((ROOT + 'hicCompareMatrices/small_test_matrix_twice.cool'), (ROOT + 'small_test_matrix.cool'), outfile.name).split...
def cflaf(x, d, M=128, P=5, mu_L=0.2, mu_FL=0.5, mu_a=0.5): nIters = (min(len(x), len(d)) - M) Q = (P * 2) beta = 0.9 sk = np.arange(0, (Q * M), 2) ck = np.arange(1, (Q * M), 2) pk = np.tile(np.arange(P), M) u = np.zeros(M) w_L = np.zeros(M) w_FL = np.zeros((Q * M)) alpha = 0 ...
def resample_file(input_file: Path, output_file: Path, overwrite: bool, samping_rate: int, mono: bool): import librosa import soundfile as sf if ((overwrite is False) and output_file.exists()): return (audio, _) = librosa.load(str(input_file), sr=samping_rate, mono=mono) if (audio.ndim == 2)...
class MutationResponse(): def __init__(self, mutation, response): self.code = response['code'] self.url = response['url'] self.headers = response['headers'] self.body = decode_bytes(response['body']) self.body_binary = response['body'] self.time = response['time']
class EmailTemplateRenderer(): def __init__(self, repository: 'EmailTemplateRepository', *, templates_overrides: (dict[(EmailTemplateType, 'EmailTemplate')] | None)=None): self.repository = repository self._jinja_environment: (jinja2.Environment | None) = None self.templates_overrides = temp...
def test(): assert (len(pattern) == 2), 'Le motif doit decrire deux tokens (deux dictionnaires).' assert (isinstance(pattern[0], dict) and isinstance(pattern[1], dict)), "Chaque element d'un motif doit etre un dictionnaire." assert ((len(pattern[0]) == 1) and (len(pattern[1]) == 1)), "Chaque element du moti...
def do_istft(data): window_fn = tf.signal.hamming_window win_size = args.stft['win_size'] hop_size = args.stft['hop_size'] inv_window_fn = tf.signal.inverse_stft_window_fn(hop_size, forward_window_fn=window_fn) pred_cpx = (data[(..., 0)] + (1j * data[(..., 1)])) pred_time = tf.signal.inverse_stf...
def get_gauntlet_progress(lengths: dict[(str, Any)], unlock: bool=True) -> dict[(str, Any)]: total = lengths['total'] stars = lengths['stars'] stages = lengths['stages'] clear_progress = get_length_data(4, 1, (total * stars)) clear_progress = list(helper.chunks(clear_progress, stars)) clear_amou...
class APIResponse(Response): api_return_types = (list, dict) def __init__(self, content=None, *args, **kwargs): super().__init__(None, *args, **kwargs) media_type = None if (isinstance(content, self.api_return_types) or (content == '')): renderer = request.accepted_renderer ...
def read_line(f, metrics, iline_idx, xline_idx): samples = metrics['samplecount'] xline_stride = metrics['xline_stride'] iline_stride = metrics['iline_stride'] offsets = metrics['offset_count'] xline_trace0 = _segyio.fread_trace0(20, len(iline_idx), xline_stride, offsets, xline_idx, 'crossline') ...
class EnvoyBuilder(base_builder.BaseBuilder): def __init__(self, manager: source_manager.SourceManager) -> None: super(EnvoyBuilder, self).__init__(manager) self._source_tree = self._source_manager.get_source_tree(proto_source.SourceRepository.SRCID_ENVOY) self._source_repo = self._source_ma...
class TestAction(unittest.TestCase, UnittestTools): def setUp(self): self.application = GUIApplication() def test_defaults(self): action = GUIApplicationAction() event = ActionEvent() action.perform(event) self.assertTrue(action.enabled) self.assertTrue(action.vis...
def extractMdzstranslationWordpressCom(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...
class CommandsTestCase(TestCase): def test_import_practices_from_epraccur(self): Practice.objects.create(code='A81044', ccg_id='00M', ccg_change_reason='Manually set') args = [] epraccur = 'frontend/tests/fixtures/commands/' epraccur += 'epraccur_sample.csv' opts = {'epraccur...
def read_grdecl_3d_property(filename, keyword, dimensions, dtype=float): result = None with open_grdecl(filename, keywords=[], simple_keywords=(keyword,)) as kw_generator: try: (_, result) = next(kw_generator) except StopIteration as si: raise xtgeo.KeywordNotFoundError(f...
_page.route('/table/settings', methods=['POST']) def settings(): res = check_uuid(all_data['uuid'], request.json['uuid']) if (res != None): return jsonify(res) settings = request.json['settings'] all_data['settings'].update({key.replace(' ', '_'): value for (key, value) in settings.items()}) ...
class dns_analytics(bsn_tlv): type = 190 def __init__(self): return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('!H', 0)) length = sum([len(x) for x in packed]) packed[1] = struct.pack('!H', length) ...
def get_input(req): try: x = request.args.get('x') if ((x is not None) and (x != '')): return x except: pass try: x = request.form.get('x') if ((x is not None) and (x != '')): return x except: pass try: x = request.files...
def test_write_jsonl_file(): data = [{'hello': 'world'}, {'test': 123}] with make_tempdir() as temp_dir: file_path = (temp_dir / 'tmp.json') write_jsonl(file_path, data) with Path(file_path).open('r', encoding='utf8') as f: assert (f.read() == '{"hello":"world"}\n{"test":123}...
class TProtocolMessage(Message): protocol_id = PublicId.from_str('fetchai/t_protocol:0.1.0') protocol_specification_id = PublicId.from_str('some_author/some_protocol_name:1.0.0') DataModel = CustomDataModel DataModel1 = CustomDataModel1 DataModel2 = CustomDataModel2 DataModel3 = CustomDataModel3...
def create_generic_coordinates(net, mg=None, library='igraph', respect_switches=False, geodata_table='bus_geodata', buses=None, overwrite=False): _prepare_geodata_table(net, geodata_table, overwrite) if (library == 'igraph'): if (not IGRAPH_INSTALLED): soft_dependency_error('build_igraph_fro...
def get_predictor(args, mode): predictor = None if (mode == GENEPRED_MODE_SEARCH): predictor = None elif (mode == GENEPRED_MODE_PRODIGAL): predictor = ProdigalPredictor(args) else: raise EmapperException(('Unknown gene prediction mode %s' % mode)) return predictor
class OptionPlotoptionsLineDragdropGuideboxDefault(Options): def className(self): return self._config_get('highcharts-drag-box-default') def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get('rgba(0, 0, 0, 0.1)') def color(self...
def make_commkey(key, session_id, ticks=50): key = int(key) session_id = int(session_id) k = 0 for i in range(32): if (key & (1 << i)): k = ((k << 1) | 1) else: k = (k << 1) k += session_id k = pack(b'I', k) k = unpack(b'BBBB', k) k = pack(b'BBBB',...
('config_name, overrides, expected, warning_file', [param('include_nested_group_name_', [], [ResultDefault(config_path='group1/group2/file1', package='group1.file1', parent='group1/group_item1_name_'), ResultDefault(config_path='group1/group_item1_name_', parent='include_nested_group_name_', package='group1', is_self=T...
.isa('neon') def test_neon_memcpy(compiler): def memcpy_neon(n: size, dst: (R[n] DRAM), src: (R[n] DRAM)): for i in seq(0, ((n + 3) / 4)): if ((n - (4 * i)) >= 4): tmp: (f32[4] Neon) neon_vld_4xf32(tmp, src[(4 * i):((4 * i) + 4)]) neon_vst_4xf32...
class OptionSeriesGaugeSonificationContexttracksMappingPlaydelay(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 select_random_faucet(): private_key_base = 'deaddeaddeaddead5fb92d83ed54c0ea1eb74e72a84ef980d42953caaa6d' selected_faucet_index = random.randrange(0, (499 + 1), 1) hex_selector_bytes = ('%0.4x' % selected_faucet_index) faucet_private_key = (private_key_base + hex_selector_bytes) return (selected...
class RelationshipsForWafRule(ModelComposed): allowed_values = {} validations = {} _property def additional_properties_type(): lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = False _property def openapi_types(): lazy_imp...
.xfail(reason='Infura rate limiting - the test suite needs a refactor', strict=False) def test_existing_different_chains(network): network.connect('mainnet') with pytest.warns(BrownieCompilerWarning): Contract.from_explorer('0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2') network.disconnect() netwo...
def test_align_extract_taxon_fasta_from_alignments(o_dir, e_dir, request): program = 'bin/align/phyluce_align_extract_taxon_fasta_from_alignments' output = os.path.join(o_dir, 'mafft-gblocks-clean-gallus.fasta') cmd = [os.path.join(request.config.rootdir, program), '--alignments', os.path.join(e_dir, 'mafft...
def test_headerdb_persist_header_returns_new_canonical_chain(headerdb, genesis_header): (gen_result, _) = headerdb.persist_header(genesis_header) assert (gen_result == (genesis_header,)) chain_a = mk_header_chain(genesis_header, 3) chain_b = mk_header_chain(genesis_header, 2) chain_c = mk_header_cha...
def extractYasuitlBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Dream Life', 'Dream Life -Dreams in a Different World-', 'translated'), ('PRC', 'PRC', 'translated...
def extractThesolmannBlogspotCom(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 SplitLargeConcatTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(SplitLargeConcatTestCase, self).__init__(*args, **kwargs) self.test_count = 0 def _make_tensors(self, num_inputs, input_shape, dtype, input_names=None): if (input_names is not None): ...
def test_parse_server_js_define_new(): html = '\n some data;require("TimeSliceImpl").guard(function(){new (require("ServerJS"))().handle({"define":[["DTSGInitialData",[],{"token":""},100]],"require":[...]});}, "ServerJS define", {"root":true})();\n more data\n <script><script>require("TimeSliceImpl").guard...
def environment_python_interpreter(): ENV_PYTHON = {'CPython': 'python%(major)d.%(minor)d', 'Jython': 'jython', 'PyPy': 'pypy', 'IronPython': 'ipy'} python = (ENV_PYTHON[platform.python_implementation()] % {'major': sys.version_info[0], 'minor': sys.version_info[1], 'patch': sys.version_info[2]}) return ('/...
def test_wrap_method(): default_config: dict = load_env_config(dummy_wrappers_module, 'dummy_env_config_with_dummy_wrappers.yml') env_config: dict = default_config['env'] env_config['core_env'] = {'_target_': DummyCoreEnvironment, 'observation_space': ObservationConversion().space()} env = DummyEnvironm...