code
stringlengths
281
23.7M
def _add_mail_adress_score(string, score): regex = '(([^<>()[\\]\\\\.,;:\\\\"]+(\\.[^<>()[\\]\\\\.,;:\\\\"]+)*)|(\\".+\\"))((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))' match = re.search(regex, string) return ((score + 150) if match else score)
class OptionPlotoptionsHeatmapSonificationContexttracksMappingGapbetweennotes(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: ...
def test_require6(evmtester, branch_results): evmtester.requireBranches(6, False, False, False, False) results = branch_results() for i in [1813, 1850, 1896, 1902, 1908, 1933, 1939, 1945]: assert ([i, (i + 1)] in results[True]) with pytest.raises(VirtualMachineError): evmtester.requireBr...
class OptionSeriesAreaDataDatalabels(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config(flag, js...
class ApiClient(object): PRIMITIVE_TYPES = ((float, bool, bytes, six.text_type) + six.integer_types) NATIVE_TYPES_MAPPING = {'int': int, 'long': (int if six.PY3 else long), 'float': float, 'str': str, 'bool': bool, 'date': datetime.date, 'datetime': datetime.datetime, 'object': object} def __init__(self, co...
class Main(object): UPDATE_INTERVALL = 30 def __init__(self): self.masters = {} self.masteruri = masteruri_from_master() self.hostname = get_hostname(self.masteruri) self._localname = '' self.__lock = threading.RLock() self._load_interface() self._check_ho...
class RouterIPV4Linux(RouterIPV4): def __init__(self, *args, **kwargs): super(RouterIPV4Linux, self).__init__(*args, **kwargs) assert isinstance(self.interface, vrrp_event.VRRPInterfaceNetworkDevice) self.__is_master = False self._arp_thread = None def start(self): self._...
def clear_pi_system_pi_web_api(host, admin, password, pi_database, af_hierarchy_list, asset_dict): print('Going to delete the element hierarchy list {}.'.format(af_hierarchy_list)) delete_element_hierarchy(host, admin, password, pi_database, af_hierarchy_list) print('Deleted the element hierarchy list {}.'....
def test_no_summary_seeking(tmpdir: Path): filepath = (tmpdir / 'no_summary.mcap') write_no_summary_mcap(filepath) with open(filepath, 'rb') as f: reader = SeekingReader(f) assert (len(list(reader.iter_messages())) == 200) assert (len(list(reader.iter_attachments())) == 1) as...
def _find_common_alerts(first_alerts: Union[(List[PendingTestAlertSchema], List[PendingModelAlertSchema], List[PendingSourceFreshnessAlertSchema])], second_alerts: Union[(List[PendingTestAlertSchema], List[PendingModelAlertSchema], List[PendingSourceFreshnessAlertSchema])]) -> Union[(List[PendingTestAlertSchema], List[...
def common_stuff(request): from core.version import __version__, __edition__ from gui.node.utils import get_dc1_settings from api.system.update.api_views import UpdateView return {'settings': settings, 'dc_settings': request.dc.settings, 'dc1_settings': get_dc1_settings(request), 'ANALYTICS': (None if r...
def test_injection(): resource = object() def _init(): _init.counter += 1 return resource _init.counter = 0 class Container(containers.DeclarativeContainer): resource = providers.Resource(_init) dependency1 = providers.List(resource) dependency2 = providers.List(r...
class BrowserPlugin(Plugin): VIEWS = 'envisage.ui.workbench.views' name = 'TVTK Pipeline Browser' id = 'tvtk.browser' views = List(contributes_to=VIEWS) def _views_default(self): return [self._browser_view_factory] def _browser_view_factory(self, window, **traits): from tvtk.plug...
.unit class TestLoggerPii(): (scope='function') def log_pii_true(self) -> None: original_value = CONFIG.logging.log_pii CONFIG.logging.log_pii = True (yield) CONFIG.logging.log_pii = original_value (scope='function') def log_pii_false(self) -> None: original_value...
class BMGNode(ABC): inputs: InputList outputs: ItemCounter def __init__(self, inputs: List['BMGNode']): assert isinstance(inputs, list) self.inputs = InputList(self, inputs) self.outputs = ItemCounter() def is_leaf(self) -> bool: return (len(self.outputs.items) == 0)
def main(): (X, y) = datasets.make_classification(n_samples=1000, n_features=10, n_classes=4, n_clusters_per_class=1, n_informative=2) data = datasets.load_iris() X = normalize(data.data) y = data.target y = to_categorical(y.astype('int')) def model_builder(n_inputs, n_outputs): model = ...
def gen_dummy_pc_instance() -> PrivateComputationInstance: infra_config: InfraConfig = InfraConfig(instance_id='pc_instance_id', role=PrivateComputationRole.PUBLISHER, status=PrivateComputationInstanceStatus.POST_PROCESSING_HANDLERS_COMPLETED, status_update_ts=int(time.time()), instances=[gen_dummy_stage_state_inst...
class OptionSeriesWordcloudOnpoint(Options): def connectorOptions(self) -> 'OptionSeriesWordcloudOnpointConnectoroptions': return self._config_sub_data('connectorOptions', OptionSeriesWordcloudOnpointConnectoroptions) def id(self): return self._config_get(None) def id(self, text: str): ...
class OptionSeriesStreamgraphMarkerStatesSelect(Options): def enabled(self): return self._config_get(True) def enabled(self, flag: bool): self._config(flag, js_type=False) def fillColor(self): return self._config_get('#cccccc') def fillColor(self, text: str): self._config...
class OwnershipState(BaseOwnershipState): __slots__ = ('_amount_by_currency_id', '_quantities_by_good_id') def __init__(self) -> None: self._amount_by_currency_id = None self._quantities_by_good_id = None def set(self, amount_by_currency_id: CurrencyHoldings=None, quantities_by_good_id: Good...
class DownBlocks(fl.Chain): def __init__(self, in_channels: int, device: ((Device | str) | None)=None, dtype: (DType | None)=None): self.in_channels = in_channels super().__init__(fl.Chain(fl.Conv2d(in_channels=in_channels, out_channels=320, kernel_size=3, padding=1, device=device, dtype=dtype)), fl...
def _shape_to_str(shapes: List[Union[(IntVar, Tensor)]], intimm_to_int=False): shape_str = '[' for (idx, shape) in enumerate(shapes): if (idx != 0): shape_str += ', ' if isinstance(shape, IntImm): if intimm_to_int: shape_str += f'{shape.value()}' ...
def dfs(root_path: str) -> List[str]: ret = [] for (root, _, files) in os.walk(root_path, topdown=False): for name in files: path = os.path.join(root, name) if path.endswith('.py'): with open(path) as fi: src = fi.read() fla...
def sync_tree(root, dest, concurrency=1, disable_progress=False, recursive=False, dont_checkout=False, dont_store_token=False): if (not disable_progress): progress.init_progress(len(root.leaves)) actions = get_git_actions(root, dest, recursive, dont_checkout, dont_store_token) with concurrent.future...
class TestPIDRunProtocolStageService(IsolatedAsyncioTestCase): ('fbpcp.service.storage.StorageService') ('fbpcp.service.onedocker.OneDockerService') def setUp(self, mock_onedocker_service, mock_storage_service) -> None: self.mock_onedocker_svc = mock_onedocker_service self.mock_storage_svc =...
_group.command('search-alerts') ('query', required=False) ('--date-range', '-d', type=(str, str), default=('now-7d', 'now'), help='Date range to scope search') ('--columns', '-c', multiple=True, help='Columns to display in table') ('--extend', '-e', is_flag=True, help='If columns are specified, extend the original colu...
class ClassDocumenter(autodoc.ClassDocumenter): def import_object(self, raiseerror: bool=False) -> bool: ret = super().import_object(raiseerror) if isinstance(self.object, dsl.Schema.__class__): self.object = self.object.__class__ self.doc_as_attr = False return ret ...
def get_required_data_to_create_purchase_record(order, center, error_logs): data = [] if ((not frappe.db.exists('Purchase Invoice', {'zenoti_order_no': order['order_number']})) and (not frappe.db.exists('Purchase Order', {'zenoti_order_no': order['order_number']}))): cost_center = center.get('erpnext_co...
class OptionPlotoptionsColumnpyramidSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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 mapT...
def find_closest_segment(segs, target_length): closest_length = float('inf') closest_seg = None for seg in segs: length_difference = abs((len(seg) - target_length)) if (length_difference < closest_length): closest_length = length_difference closest_seg = seg retur...
class RichTextFormField(forms.fields.CharField): def __init__(self, *args, **kwargs): self.cleanse = kwargs.pop('cleanse', None) super().__init__(*args, **kwargs) css_class = self.widget.attrs.get('class', '') css_class += ' item-richtext' self.widget.attrs['class'] = css_cla...
class MissingTranslationHandler(ResponseHandler): def applies_to(api, response): return ('translations/missing.json' in get_endpoint_path(api, response)) def build(self, response): return self.deserialize(response.json()) def deserialize(self, response_json): return response_json['lo...
class SkipBuildCache(): def __init__(self, context_skip_cache_flag: bool=True): self.context_skip_cache_flag = context_skip_cache_flag def __enter__(self): global skip_cache_flag self.old_skip_cache_flag = skip_cache_flag skip_cache_flag = self.context_skip_cache_flag def __e...
def test_nan_encoding_for_new_categories_if_unseen_is_ignore(): df_fit = pd.DataFrame({'col1': ['a', 'a', 'b', 'a', 'c'], 'col2': ['1', '2', '3', '1', '2']}) df_transf = pd.DataFrame({'col1': ['a', 'd', 'b', 'a', 'c'], 'col2': ['1', '2', '3', '1', '4']}) encoder = CountFrequencyEncoder(unseen='ignore').fit(...
def set_nested_key(dict_: dict, keys: list, key: Any, value: Any): new_dict = dict_ for k in keys: if (not (k in new_dict)): new_dict[k] = {} if isinstance(new_dict[k], dict): new_dict = new_dict[k] else: raise ValueError() new_dict[key] = value
class OptionPlotoptionsSankeySonification(Options): def contextTracks(self) -> 'OptionPlotoptionsSankeySonificationContexttracks': return self._config_sub_data('contextTracks', OptionPlotoptionsSankeySonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionPlotoptionsSankeySonificationDef...
def prepare_message(caller: Address, target: Union[(Bytes0, Address)], value: U256, data: Bytes, gas: Uint, env: Environment, code_address: Optional[Address]=None, should_transfer_value: bool=True, is_static: bool=False) -> Message: if isinstance(target, Bytes0): current_target = compute_contract_address(ca...
def apk_parse_release_filename(apkname): m = apk_release_filename_with_sigfp.match(apkname) if m: return (m.group('appid'), int(m.group('vercode')), m.group('sigfp')) m = apk_release_filename.match(apkname) if m: return (m.group('appid'), int(m.group('vercode')), None) return (None, ...
def _generate_apidocs_default_packages() -> None: for (component_type, default_package) in DEFAULT_PACKAGES: public_id = PublicId.from_str(default_package) author = public_id.author name = public_id.name type_plural = component_type.to_plural() package_dir = (((PACKAGES_DIR /...
def _parse_sitemap(root): d = dict() for node in root: for n in node: if ('loc' in n.tag): d[n.text] = {} def parse_xml_node(node, node_url, prefix=''): nonlocal d keys = [] for element in node: if element.text: tag = el...
class OptionSonificationDefaultinstrumentoptionsMappingTremoloSpeed(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 OptionSeriesBarSonificationContexttracksMappingTime(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): self._...
(eq=False) class Argument(Expression): info: str = '' type_string: Optional[str] = None name: Optional[str] = None def id(self): return id_str(self, 3) def __str__(self): arg = (self.name if self.name else f'arg_{self.id}') return f'{{{arg}}}' __repr__ = __str__
def _split_periods(curr_data: pd.DataFrame, ref_data: pd.DataFrame, feature_name: str): max_ref_date = ref_data[feature_name].max() min_curr_date = curr_data[feature_name].min() if (curr_data.loc[((curr_data[feature_name] == min_curr_date), 'number_of_items')].iloc[0] > ref_data.loc[((ref_data[feature_name]...
def test_bulk_rejected_documents_are_retried(sync_client): failing_client = FailingBulkClient(sync_client, fail_with=ApiError(message='Rejected!', body={}, meta=ApiResponseMeta(status=429, headers={}, duration=0, node=None))) docs = [{'_index': 'i', '_id': 47, 'f': 'v'}, {'_index': 'i', '_id': 45, 'f': 'v'}, {...
class YotpoReviewsAuthenticationStrategy(AuthenticationStrategy): name = 'yotpo_reviews' configuration_model = YotpoReviewsAuthenticationConfiguration def __init__(self, configuration: YotpoReviewsAuthenticationConfiguration): self.store_id = configuration.store_id self.secret_key = configur...
('pybikes.data._import', _import) ('pybikes.data._iter_data', _iter_data) ('pybikes.data._t_cache', {}) ('pybikes.data._traversor', _traverse_lib()) class TestData(): def test_find_not_found(self): with pytest.raises(BikeShareSystemNotFound): find('abracadabra') def test_find_single_class(se...
class ArchivedResults(enum.Enum): INCLUDE = (1, None) EXCLUDE = (2, False) ONLY = (3, True) def __init__(self, int_value, api_value): self.int_value = int_value self.api_value = api_value def __str__(self): return self.name.lower() def __repr__(self): return str(s...
def test_call_undefined_error_message_with_container_instance_parent(): class UserService(): def __init__(self, database): self.database = database class Container(containers.DeclarativeContainer): database = providers.Dependency() user_service = providers.Factory(UserService...
def greet_user(): path = Path('username.json') username = get_stored_username(path) if username: print(f'Welcome back, {username}!') else: username = input('What is your name? ') contents = json.dumps(username) path.write_text(contents) print(f"We'll remember you ...
class ExtensionRegistryTestMixin(): def test_empty_registry(self): registry = self.registry extensions = registry.get_extensions('my.ep') self.assertEqual(0, len(extensions)) extension_points = registry.get_extension_points() self.assertEqual(0, len(extension_points)) def...
class Permission(models.Model): is_dummy = False name = models.CharField(_('name'), max_length=80, unique=True) alias = models.CharField(_('alias'), max_length=80) class Meta(): app_label = 'gui' verbose_name = _('Permission') verbose_name_plural = _('Permissions') def __unic...
class OptionPlotoptionsScatterSonificationContexttracksMappingRate(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): ...
(Output('readiness-exclamation', 'style'), [Input('readiness-date', 'children')]) def show_readiness_exclamation(dummy): show = {'display': 'inline-block', 'fontSize': '1rem', 'color': orange, 'paddingLeft': '1%'} hide = {'display': 'none'} max_sleep_date = app.session.query(func.max(ouraSleepSummary.report...
def gtp_rat_timeout_profile(data, fos): vdom = data['vdom'] state = data['state'] gtp_rat_timeout_profile_data = data['gtp_rat_timeout_profile'] filtered_data = underscore_to_hyphen(filter_gtp_rat_timeout_profile_data(gtp_rat_timeout_profile_data)) if ((state == 'present') or (state is True)): ...
def trace_galerkin_projection(degree, quad=False, conv_test_flag=0, mesh_res=None): if (mesh_res is None): mesh = UnitSquareMesh(10, 10, quadrilateral=quad) elif isinstance(mesh_res, int): mesh = UnitSquareMesh((2 ** mesh_res), (2 ** mesh_res), quadrilateral=quad) else: raise ValueEr...
class MyClass(): def __init__(self, a, b): self.a = a self.b = b def compute(self, n): a = self.a b = self.b if ts.is_transpiled: result = ts.use_block('block0') else: result = np.zeros_like(a) for _ in range(n): ...
def genomicRegion(string): region = ''.join(string.split()) if (region == ''): return None if (sys.version_info[0] == 2): region = region.translate(None, ',;|!{}()').replace('-', ':') if (sys.version_info[0] == 3): region = region.translate(str.maketrans('', '', ',;|!{}()')).repl...
class Definition(Block): NAME = 'define' def on_create(self, parent): return etree.SubElement(parent, 'dl') def on_end(self, block): remove = [] offset = 0 for (i, child) in enumerate(list(block)): if (child.tag.lower() in ('dt', 'dd')): continue ...
def decode_snooz(snooz): (version, last_timestamp_ms) = struct.unpack_from('=bQ', snooz) if ((version != 1) and (version != 2)): sys.stderr.write(('Unsupported btsnooz version: %s\n' % version)) exit(1) decompressed = zlib.decompress(snooz[9:]) sys.stdout.buffer.write(b'btsnoop\x00\x00\x...
def validate_boolean(rule): if (str(rule['value']).lower() in ('1', 't', 'true')): return True elif (str(rule['value']).lower() in ('0', 'f', 'false')): return False else: msg = (INVALID_TYPE_MSG.format(**rule) + '. Use true/false') raise InvalidParameterException(msg)
class ProcessData(): def __init__(self, silence_thresh_dB, sr, device, seq_len, crepe_params, loudness_params, rms_params, hop_size, max_len, center, overlap=0.0, debug=False, contiguous=False, contiguous_clip_noise=False): super().__init__() self.silence_thresh_dB = silence_thresh_dB self.c...
def dump_tags(location): from pprint import pprint mka = parse(location) segment = mka['Segment'][0] info = segment['Info'][0] try: timecodescale = info['TimecodeScale'][0] except KeyError: timecodescale = 1000000 length = ((info['Duration'][0] * timecodescale) / .0) prin...
class DataTable(OptPlotly.DataChart): def domain(self) -> DataDomain: return self.sub_data('domain', DataDomain) def set_domain(self, x, y=None): self.domain.x = x self.domain.y = (y or x) def columnorder(self): return self._attrs['columnorder'] def columnorder(self, val)...
class ExpansionConverter(object): def __init__(self, type_routes, type_expansions): self.type_routes = type_routes self.type_expansions = type_expansions def dict_to_trees(self, expansion_dict): trees = [] for (node_type, expansion_list) in six.iteritems(expansion_dict): ...
class SchemasVclResponse(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_import()...
def extractTericherryWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=fra...
def house_of_einherjar(): delete(4) fake_chunk1 = ('A' * 224) fake_chunk1 += p64(((heap_base + 240) - tinypad)) add(232, fake_chunk1) fake_chunk2 = p64(256) fake_chunk2 += p64(((heap_base + 240) - tinypad)) fake_chunk2 += (p64(6299712) * 4) edit(2, fake_chunk2) delete(2)
def get_weather(longitude: float, latitude: float): logger = get_run_logger() logger.info(f'Getting weather of latitude={latitude} and longitude={longitude}') api_endpoint = f' response = requests.get(api_endpoint) if (response.status_code == 200): weather_data = json.loads(response.text) ...
class SearchPageForm(FlaskForm): search_query = StringField(_('Criteria'), validators=[DataRequired(), Length(min=3, max=50)]) search_types = SelectMultipleField(_('Content'), validators=[DataRequired()], choices=[('post', _('Post')), ('topic', _('Topic')), ('forum', _('Forum')), ('user', _('Users'))]) subm...
def add_service(): def _add_service(fledge_url, service, service_branch, retries, installation_type='make', service_name='', enabled=True): retval = utils.get_request(fledge_url, '/fledge/service') for ele in retval['services']: if (ele['type'].lower() == service): return...
def extractMegruminatesWordpressCom(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_ty...
def COMMETHOD(idlflags, restype, methodname, *argspec): helptext = (''.join((t for t in idlflags if isinstance(t, helpstring))) or None) (paramflags, argtypes) = _resolve_argspec(argspec) if ('propget' in idlflags): name = ('_get_%s' % methodname) elif ('propput' in idlflags): name = ('_...
(suppress_health_check=[HealthCheck.function_scoped_fixture]) (ecl_runs) def test_gridprop_unrst_same_formatted(tmp_path, ecl_run): funrst = (tmp_path / 'file.FUNRST') resfo.write(funrst, resfo.read(ecl_run.unrst_file), resfo.Format.FORMATTED) ecl_run.unrst_file.seek(0) funrst_gridprop = xtgeo.gridprope...
class FunctionalModule(): name: str description: str method: Callable[(..., Any)] signature: dict[(str, dict)] def __init__(self, name, description, method, signature): self.name = name self.description = description self.method = method self.signature = signature
class FileParamType(click.ParamType): name = 'file path' def convert(self, value: typing.Any, param: typing.Optional[click.Parameter], ctx: typing.Optional[click.Context]) -> typing.Any: remote_path = (None if getattr(ctx.obj, 'is_remote', False) else False) if (not FileAccessProvider.is_remote(...
def upgrade(): op.create_table('regcode', sa.Column('id', sa.Integer(), nullable=False), sa.Column('password', sa.LargeBinary(), nullable=False), sa.Column('code', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id')) op.create_index(op.f('ix_regcode_password'), 'regcode', ['password'], unique=False)
def create_arnold_stand_in(path=None): if (not pm.objExists('ArnoldStandInDefaultLightSet')): pm.createNode('objectSet', name='ArnoldStandInDefaultLightSet', shared=True) pm.lightlink(object='ArnoldStandInDefaultLightSet', light='defaultLightSet') stand_in = pm.createNode('aiStandIn', n='ArnoldS...
class OptionSeriesSplineStatesInactive(Options): def animation(self) -> 'OptionSeriesSplineStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesSplineStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): se...
def _get_feature_subfeature_phase(): load_feature_list = list_features() list_without_provider = list(set([(f, s, (ph[0] if ph else '')) for (p, f, s, *ph) in load_feature_list])) detailed_providers_list = [] for (feature, subfeature, *phase) in list_without_provider: detailed_params = pytest.pa...
def dipole3d_20(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 6, 1), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + A[0]) x4 = (x2 + R[0]) x5 = (x3 * x4) x6 = ((ax * bx) * x0) x7 = ((((5. * da) * db) * (x0 ** 1.5)) * numpy...
class TestSinkMethodCompatibility(): def _verify_kitchen_sink(self, client): resp = client.simulate_request('BREW', '/features') assert (resp.status_code == 200) assert (resp.headers.get('X-Missing-Feature') == 'kitchen-sink') def test_add_async_sink(self, client, asgi): if (not ...
def any_of(*exprs, **kwargs): use_adaptive = (kwargs.pop('use_adaptive', use_adaptive_any_of) and SUPPORTS_ADAPTIVE) reverse = reverse_any_of if DEVELOP: reverse = kwargs.pop('reverse', reverse) internal_assert((not kwargs), 'excess keyword arguments passed to any_of', kwargs) AnyOf = (Match...
_dict def __new__(cls, value): if (NoAlias in cls._settings_): raise TypeError('NoAlias enumerations cannot be looked up by value') if (type(value) is cls): return value try: return cls._value2member_map_[value] except KeyError: pass except TypeError: for (mem...
class Naws(): def __init__(self, protocol): self.naws_step = 0 self.protocol = protocol self.protocol.protocol_flags['SCREENWIDTH'] = {0: DEFAULT_WIDTH} self.protocol.protocol_flags['SCREENHEIGHT'] = {0: DEFAULT_HEIGHT} self.protocol.negotiationMap[NAWS] = self.negotiate_size...
class Menu(models.Model): nid = models.AutoField(primary_key=True) menu_title = models.CharField(verbose_name='', max_length=16, null=True) menu_title_en = models.CharField(verbose_name='', max_length=32, null=True) title = models.CharField(verbose_name='slogan', max_length=32, null=True) abstract =...
class ViewerSession(object): archFiles = None items = None def __init__(self): self.archHandle = None self.lastAccess = time.time() self.pruneAge = (60 * 120) def shouldPrune(self): lastChange = (time.time() - self.lastAccess) if (lastChange > self.pruneAge): ...
def lazy_import(): from fastly.model.service_invitation_data_attributes import ServiceInvitationDataAttributes from fastly.model.service_invitation_data_relationships import ServiceInvitationDataRelationships from fastly.model.type_service_invitation import TypeServiceInvitation globals()['ServiceInvita...
def read_event(io, metadata): (process_idx, tid, event_class_val, operation_val, _, _, duration, date, result, stacktrace_depth, _, details_size, extra_details_offset) = CommonEventStruct.unpack(io.read(CommonEventStruct.size)) process = metadata.process_idx(process_idx) event_class = EventClass(event_class...
def make_hashable(obj: Any) -> Tuple: if isinstance(obj, (tuple, list)): return tuple((make_hashable(e) for e in obj)) if isinstance(obj, dict): return tuple(sorted(((k, make_hashable(v)) for (k, v) in obj.items()))) if isinstance(obj, (set, frozenset)): return tuple(sorted((make_has...
class TestParaphrase(unittest.TestCase): def setUp(self) -> None: self.num_perturbations = 4 self.perturber = Paraphrase(num_perturbations=self.num_perturbations, temperature=0.1) return def test_paraphrase(self): for prompt in TRUTHFUL_DATASET: sim_prompt = self.pert...
class IPv4Dscp(MatchTest): def runTest(self): match = ofp.match([ofp.oxm.eth_type(2048), ofp.oxm.ip_dscp(4)]) matching = {'dscp=4 ecn=0': simple_tcp_packet(ip_tos=16), 'dscp=4 ecn=3': simple_tcp_packet(ip_tos=19)} nonmatching = {'dscp=5 ecn=0': simple_tcp_packet(ip_tos=20)} self.veri...
def upgrade(): op.execute("UPDATE custom_forms SET is_public=True WHERE form='session' and (field_identifier='title' or field_identifier='subtitle' or field_identifier='shortAbstract' or field_identifier='longAbstract' or field_identifier='level' or field_identifier='track' or field_identifier='sessionType' or fiel...
def pie_chart(): normal_radius = 100 hover_radius = 110 normal_title_style = ft.TextStyle(size=12, color=ft.colors.WHITE, weight=ft.FontWeight.BOLD) hover_title_style = ft.TextStyle(size=16, color=ft.colors.WHITE, weight=ft.FontWeight.BOLD, shadow=ft.BoxShadow(blur_radius=2, color=ft.colors.BLACK54)) ...
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('csv', help='The input CSV to read') parser.add_argument('--output', '-o', default='out.mcap', help='The MCAP output path to write') args = parser.parse_args() pointcloud: typing.Dict[(str, typing.Any)] float32...
class OptionSeriesDependencywheelZones(Options): def className(self): return self._config_get(None) def className(self, text: str): self._config(text, js_type=False) def color(self): return self._config_get(None) def color(self, text: str): self._config(text, js_type=Fals...
def _migrate_items_to_ecommerce_item(log): shopify_fields = ['shopify_product_id', 'shopify_variant_id'] for field in shopify_fields: if (not frappe.db.exists({'doctype': 'Custom Field', 'fieldname': field})): return items = _get_items_to_migrate() try: _create_ecommerce_item...
class FBPrintApplicationDocumentsPath(fb.FBCommand): def name(self): return 'pdocspath' def description(self): return "Print application's 'Documents' directory path." def options(self): return [fb.FBCommandArgument(short='-o', long='--open', arg='open', boolean=True, default=False, ...
class Movie(object): def __init__(self, filename=None): self._filename = filename self._start_timestamp = None self._end_timestamp = None self._duration = None self._events = {} def filename(self): return self._filename def filename(self, value): self....
def main(): parser = argparse.ArgumentParser() parser.add_argument('-i', required=True, type=str, help='Input .rdb file') parser.add_argument('-g', required=True, type=str, help='Input tag group definition file') parser.add_argument('-o', required=True, type=str, help='Output .rdb file') args = pars...