code
stringlengths
281
23.7M
class Grub1(Bootloader): __slots__ = [] _GRUB_KERNEL_BOOT_ENTRY = re.compile('^ \\s* kernel \\s+ \\S+ \\s+', (re.X | re.M)) def edit(self, config, state, name, value=None): config = str(config) matches = list(self._GRUB_KERNEL_BOOT_ENTRY.finditer(config)) for match in reversed(matche...
def main(): module = AnsibleModule(argument_spec={'name': {'required': True, 'type': 'str'}, 'version': {'default': None, 'required': False, 'type': 'str'}, 'state': {'default': 'present', 'required': False, 'choices': ['present', 'absent', 'latest']}, 'channels': {'default': None, 'required': False}, 'executable':...
class OptionSeriesHistogramSonificationContexttracksMappingNoteduration(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 TFConfig(object): def __init__(self, num_worker, num_ps, properties, python_file, func, env_path): self._num_worker = num_worker self._num_ps = num_ps self._properties = properties self._python_file = python_file self._func = func self._env_path = env_path d...
class PipeFactory(HasPrivateTraits): name = Str(adapts='name', help='the name of the vtk object created.') figure = Instance(Scene) _engine = Instance(Engine, help='the figure on which the object should be added') _target = Any _do_redraw = Bool def add_module(self, parent, kwargs=dict()): ...
def set_graph_topology(graph: lg.Graph) -> None: serialized_graph = serialize_graph(graph) sub_pub_map = sub_pub_grouping_map(graph) if hasattr(graph, 'set_topology'): graph.set_topology(serialized_graph, sub_pub_map) else: raise AttributeError('\n Provided graph is missing `s...
class OptionSeriesPackedbubbleSonificationContexttracksMappingHighpass(Options): def frequency(self) -> 'OptionSeriesPackedbubbleSonificationContexttracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionSeriesPackedbubbleSonificationContexttracksMappingHighpassFrequency) def re...
(scope='module') def df_duplicate_features_with_different_data_types(): data = {'A': pd.Series(([5.5] * 3)).astype('float64'), 'B': 1, 'C': 'foo', 'D': pd.Timestamp(''), 'E': pd.Series(([1.0] * 3)).astype('float32'), 'F': False, 'G': pd.Series(([1] * 3), dtype='int8')} df = pd.DataFrame(data) return df
def evaluate_tokens(tokens, **kwargs): is_final = kwargs.pop('is_final', False) evaluated_toklists = kwargs.pop('evaluated_toklists', ()) if DEVELOP: internal_assert((not kwargs), 'invalid keyword arguments to evaluate_tokens', kwargs) if (not USE_COMPUTATION_GRAPH): return tokens if...
def test_transformer_pipeline_tobytes(): nlp = Language() nlp.add_pipe('transformer', config=DEFAULT_CONFIG) nlp.initialize() assert (nlp.pipe_names == ['transformer']) nlp_bytes = nlp.to_bytes() nlp2 = Language() nlp2.add_pipe('transformer', config=DEFAULT_CONFIG) nlp2.from_bytes(nlp_by...
class Int(RangeValidator): messages = dict(integer=_('Please enter an integer value')) def _convert_to_python(self, value, state): try: return int(value) except (ValueError, TypeError): raise Invalid(self.message('integer', state), value, state) _convert_from_python =...
def make_overlap_graph(contigs_file, dot_file): cmdline = [OVERLAP_EXEC, contigs_file, dot_file, str(config.vals['overlap']['min_overlap']), str(config.vals['overlap']['max_overlap'])] if config.vals['overlap']['detect_kmer']: cmdline.append('--detect-kmer') logger.info('Building assembly graph') ...
def build_ticket_summary(all_metrics): ticket_map = {} for filename in all_metrics: metrics = all_metrics[filename] for metric_name in metrics['metrics']: info = metrics['metrics'][metric_name] for ticket_id in info['tickets']: if (ticket_id not in ticket_...
def extractHeroicNovels(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('id', 'ID The Greatest Fusion Fantasy', 'translated'), ('Magician City', 'Magician City', 'translated'),...
def get_setting_int(key, default=None): try: return ADDON.getSettingInt(key) except (AttributeError, TypeError): value = get_setting(key, default) try: return int(value) except ValueError: return default except RuntimeError: return default
def upgrade(): bind: Connection = op.get_bind() existing_systems: ResultProxy = bind.execute(text('select id, meta, vendor_id from ctl_systems;')) for row in existing_systems: if row['vendor_id']: logger.warning('Skipped migrating system > meta > vendor > id for system {} as vendor_id al...
def _get_name_of_upgrade(raw_binary, upgrade_command): tmp = re.search(b'\\xa8\\x01([\\w ]+) [\\w ]+', raw_binary[upgrade_command['end_offset']:(upgrade_command['end_offset'] + NAME_FIELD_MAX)]) if (tmp is not None): tmp = tmp.group(1).decode('utf-8', 'ignore') tmp = _remove_uneccessary_spaces(...
def _get_block_by_hash(chain, block_hash): block = chain.get_block_by_hash(block_hash) if (block.number >= chain.get_block().number): raise BlockNotFound(f'No block found for block hash: {block_hash}') block_at_height = chain.get_canonical_block_by_number(block.number) if (block != block_at_heig...
class HyperLogLogPlusPlus(HyperLogLog): _hash_range_bit = 64 _hash_range_byte = 8 def __init__(self, p: int=8, reg: Optional[np.ndarray]=None, hashfunc: Callable=sha1_hash64, hashobj: Optional[object]=None): super(HyperLogLogPlusPlus, self).__init__(p=p, reg=reg, hashfunc=hashfunc, hashobj=hashobj) ...
class ControllerBase(object): special_vars = ['action', 'controller'] def __init__(self, req, link, data, **config): self.req = req self.link = link self.data = data self.parent = None for (name, value) in config.items(): setattr(self, name, value) def __c...
class SentRoute(object): def __init__(self, path, peer, filtered=None, timestamp=None): assert (path and hasattr(peer, 'version_num')) self.path = path self._sent_peer = peer self.filtered = filtered if timestamp: self.timestamp = timestamp else: ...
class GeoPos(): def __init__(self, lat, lon): self.lat = toFloat(lat) self.lon = toFloat(lon) def slists(self): return [toList(self.lat), toList(self.lon)] def strings(self): return [toString(self.lat, LAT), toString(self.lon, LON)] def __str__(self): strings = se...
def convertOptions(options: Any, varId: str) -> str: if isJsData(options): return ('(function (ops, obj){\nfunction dictToExpr(a, b){Object.entries(a).forEach(([k, v]) => {if (\ntypeof v == "object" && !Array.isArray(v)){if(b[k]){dictToExpr(v, b[k])}} else {b[k] = v}})}; return dictToExpr(ops, obj)\n})(%s, ...
def graphs_with_dangerous_use_in_definition_block_but_not_between_definition_and_target() -> Tuple[(ControlFlowGraph, ControlFlowGraph)]: x = vars('x', 3) y = vars('y', 3) z = vars('z', 3, aliased=True) c = const(11) in_n0 = BasicBlock(0, [_call('scanf', [], [_addr(z[0])]), _assign(z[1], z[0]), _ass...
_in_both(CompWithInit2) def test_component_init2(): m = CompWithInit2(False) print(m.foo1, m.foo2, m.foo3) m = CompWithInit2(True) print(m.foo1, m.foo2, m.foo3) m = CompWithInit2(False, foo1=6, foo2=7, foo3=8) print(m.foo1, m.foo2, m.foo3) m = CompWithInit2(True, foo1=6, foo2=7, foo3=8) ...
def validate_item_config(item_type: str, package_path: Path) -> None: item_config = load_item_config(item_type, package_path) loader = ConfigLoaders.from_package_type(item_type) for field_name in loader.required_fields: try: getattr(item_config, field_name) except AttributeError:...
class OptionPlotoptionsAreaSonificationContexttracksActivewhen(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, num: float)...
def insert_environment(current_dict: Dict, env_key: str, env_val: str) -> None: if (NESTED_KEY_DELIMITER in env_key): env_key_split = env_key.split(NESTED_KEY_DELIMITER, 1) current_dict_key = env_key_split[0] next_env_key = env_key_split[1] next_dict = current_dict.get(current_dict_k...
class PlaybackProgressBar(Gtk.ProgressBar): def __init__(self, player): Gtk.ProgressBar.__init__(self) self.__player = player try: awidget = self.get_accessible() awidget.set_role(Atk.Role.AUDIO) except Exception: logger.debug('Exception setting AT...
class ActivityFilter(FilterSet): start_date_gte = IsoDateTimeFilter(field_name='start_date', lookup_expr='gte') start_date_lte = IsoDateTimeFilter(field_name='start_date', lookup_expr='lte') end_date_gte = IsoDateTimeFilter(field_name='end_date', lookup_expr='gte') end_date_lte = IsoDateTimeFilter(field...
def test_get_identified_release_signers(): entry = {'version': '1.2.0', 'date': '2019-03-20T18:00:00.000000+13:00', 'signatures': ['IPHe+QklAmNmIdROtaMXt8YSomu9edExbQSg+Rm8Ckc8Mm1iAvb1yYIo1eqhJvndT9b6gaVtgtjzXaNAnfyKa20=', 'IOpCqrDwQsOjOyMfr4FiHMeY6ekyHZz/qUJ/eas0KWN/XDl9HegERwL7Qcz+jKWg66X+2k9nT3KBvV0OopNpZd8=']} ...
class PendingChildExecutionInfo(betterproto.Message): workflow_id: str = betterproto.string_field(1) run_id: str = betterproto.string_field(2) workflow_type_name: str = betterproto.string_field(3) initiated_id: int = betterproto.int64_field(4) parent_close_policy: v1enums.ParentClosePolicy = betterp...
.usefixtures('use_tmpdir') def test_that_private_over_global_args_gives_logging_message(caplog): caplog.set_level(logging.INFO) with open('job_file', 'w', encoding='utf-8') as fout: fout.write(dedent('\n EXECUTABLE echo\n ARGLIST <ARG>\n ARG_TYPE 0 STRING\n ')...
class OptionSeriesSplineDataMarker(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 LoginForm(AuthenticationForm): def __init__(self, request, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.request = request self.fields['username'].label = _('username or email') self.fields['username'].widget = EmailInput(attrs={'class': 'input-transpa...
def create_custom_forms_for_attendees(event): form = 'attendee' is_required = True is_included = True is_fixed = True event_id = event.id email_form = CustomForms(form=form, is_required=is_required, is_included=is_included, is_fixed=is_fixed, event_id=event_id, type='email', field_identifier='em...
class OptionPlotoptionsPieSonificationTracksMappingHighpass(Options): def frequency(self) -> 'OptionPlotoptionsPieSonificationTracksMappingHighpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPieSonificationTracksMappingHighpassFrequency) def resonance(self) -> 'OptionPlotoptio...
class XMLHttpRequest(): def __init__(self, page: Optional[primitives.PageModel], js_code: str, method_type: Optional[str], url: Optional[str], data: JsData.Datamap=None, asynchronous: bool=False): self.data = (JsData.Datamap() if (data is None) else data) (self.page, self.__headers, self.url) = (pag...
class push_vlan_on_egress(bsn_tlv): type = 162 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 downgrade(): op.add_column('sponsors', sa.Column('sponsor_type_id', sa.INTEGER(), autoincrement=False, nullable=True)) op.create_foreign_key(u'sponsors_sponsor_type_id_fkey', 'sponsors', 'sponsor_type', ['sponsor_type_id'], ['id'], ondelete=u'CASCADE') op.drop_column('sponsors', 'sponsor_type') op.c...
class OptionSeriesColumnpyramidData(Options): def accessibility(self) -> 'OptionSeriesColumnpyramidDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesColumnpyramidDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): ...
def deduplicate_taxa(records): logging.info(('Applying _deduplicate_taxa generator: ' + 'removing any duplicate records with identical IDs.')) taxa = set() for record in records: taxid = record.id if ('|' in record.id): try: taxid = int(record.id.split('|')[0]) ...
_cli_group.command(cls=build_lazy_click_command(_dynamic_factory=_remote_model_dynamic_factory)) def start(**kwargs): from dbgpt.model.cluster import WorkerStartupRequest, RemoteWorkerManager worker_manager: RemoteWorkerManager = _get_worker_manager(MODEL_CONTROLLER_ADDRESS) req = WorkerStartupRequest(host=...
def df(objs, labels: Optional[List[str]]=None): import pandas as pd from .objects import DynamicObject if objs: objs = list(objs) obj = objs[0] if is_dataclass(obj): df = pd.DataFrame.from_records((dataclassAsTuple(o) for o in objs)) df.columns = [field.name f...
class NERPromptExample(PromptExample): text: str entities: Dict[(str, List[str])] def from_prodigy(cls, example: Dict, labels: Iterable[str]) -> 'PromptExample': if ('text' not in example): raise ValueError('Cannot make PromptExample without text') entities_by_label = defaultdict...
def get_characters(aln, nucleotides): cnt = Counter() percent_missing = [] for seq in aln: seq_string = str(seq.seq).upper() cnt.update(seq_string) percent_missing.append((float(seq_string.count('?')) / len(seq_string))) return (cnt, numpy.mean(numpy.array(percent_missing)))
class ListItems(): def text(self): return ListData def link(self): return RecItems.ItemsLinkRec def box(self): return RecItems.ItemsBoxRec def tweet(self): return RecItems.ItemsTweetRec def icon(self): return RecItems.ItemsIconRec def check(self): ...
def torch_softmax_with_temperature(model: Model, X: Floats2d, targets: Ints1d) -> Tuple[(Floats2d, Floats2d)]: import torch Wt = xp2torch(model.get_param('W')) bt = xp2torch(model.get_param('b')) temperature = model.attrs['softmax_temperature'] Xt = xp2torch(X, requires_grad=True) Yt_gold = xp2t...
class RWLockRead(RWLockable): def __init__(self, lock_factory: Union[(Callable[([], Lockable)], Type[asyncio.Lock])]=asyncio.Lock, time_source: Callable[([], float)]=time.perf_counter) -> None: self.v_read_count: int = 0 self.c_time_source = time_source self.c_resource = lock_factory() ...
(['animation', 'shot previs']) def check_multiple_shot_nodes(progress_controller=None): if (progress_controller is None): progress_controller = ProgressControllerBase() shot_nodes = pm.ls(type='shot') progress_controller.maximum = len(shot_nodes) local_shot_nodes = [] for shot in shot_nodes:...
class Bar(DC): chartFnc = 'BarChart' def controlsUseVisibility(self, flag: bool): return self.fnc(('controlsUseVisibility(%s)' % JsUtils.jsConvertData(flag, None))) def singleSelection(self): self.xUnitsOridinal() self.scaleBand() return self.fnc('addFilterHandler(function(fi...
def generate_legal_moves_for_bit(state, bit): o = set() xormask = (2 ** bit) state = [int(x) for x in state.split(',')] for i in range((2 ** (len(state) - 1))): new_state = state[:] indexmask = 1 for j in range(len(state)): if (j > (j ^ xormask)): if (...
def _test_correct_response_for_psc_code_object(client): resp = client.post('/api/v2/search/spending_by_award', content_type='application/json', data=json.dumps({'filters': {'award_type_codes': ['A', 'B', 'C', 'D'], 'psc_codes': {'require': [['Service', 'P', 'PSC', 'PSC1']], 'exclude': [['Service', 'P', 'PSC', 'PSC0...
class ChartForceDirected(Chart): builder_name = 'ChartLine' def dom(self) -> JsNvd3.JsNvd3ForceDirectedGraph: if (self._dom is None): self._dom = JsNvd3.JsNvd3ForceDirectedGraph(page=self.page, js_code=self.js_code, component=self) return self._dom def add_trace(self, data: dict,...
def test_basic_create_unsigned_transaction(chain): transaction = chain.create_unsigned_transaction(nonce=0, gas_price=1234, gas=21001, to=TO_ADDRESS, value=4321, data=b'test') assert (transaction.nonce == 0) assert (transaction.gas_price == 1234) assert (transaction.gas == 21001) assert (transaction...
class MockClass(CategoricalMethodsMixin): def __init__(self, unseen=None, missing_values='raise'): self.encoder_dict_ = {'words': {'dog': 1, 'dig': 0.66, 'cat': 0}} self.n_features_in_ = 1 self.feature_names_in_ = ['words'] self.variables_ = ['words'] self.missing_values = mi...
class UtilsTestCase(unittest.TestCase): def test_isinf(self): self.assertTrue(utils.isinf(float('inf'))) self.assertTrue(utils.isinf(float('-inf'))) self.assertFalse(utils.isinf(float(.0))) def test_between(self): self.assertSequenceEqual(list(utils.between(0.0, 10.0, 10)), [0.0,...
def execute_query(query, params): cursor = connection.cursor() if isinstance(params, dict): cursor.execute(query, params) elif params: cursor.execute(query, tuple(itertools.chain.from_iterable(params))) else: cursor.execute(query) data = dictfetchall(cursor) cursor.close(...
class ParentTarget(TargetStr): def instance_method(self, arg1: str, arg2: str, kwarg1: str='', kwarg2: str='') -> List[str]: return ['original response'] async def async_instance_method(self, arg1: str, arg2: str, kwarg1: str='', kwarg2: str='') -> List[str]: return ['async original response'] ...
def diag_quadrupole3d_30(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 10, 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 = (x4 ** 2) x6 = (3.0 * x0) x7 = (x3 * x4) x8 = (x0 * ((((- 2.0) *...
class OptionSeriesGaugeSonificationDefaultinstrumentoptionsMappingPitch(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('y') def mapTo(self, text: str): ...
class TestPutDefaultMessagingConfigSecrets(): (scope='function') def url(self, messaging_config) -> str: return (V1_URL_PREFIX + MESSAGING_DEFAULT_SECRETS).format(service_type=MessagingServiceType.mailgun.value) (scope='function') def payload(self): return {MessagingServiceSecrets.MAILGU...
class ImagePlotTraits(HasTraits): plot = Instance(Plot) origin = Enum('bottom left', 'top left', 'bottom right', 'top right') traits_view = View(Group(Item('origin', label='Data origin'), Item('plot', editor=ComponentEditor(), show_label=False), orientation='vertical'), width=600, height=600, resizable=True...
_meta(characters.kaguya.DilemmaDamageAction) class DilemmaDamageAction(): def choose_card_text(self, act, cards): if act.cond(cards): return (True, '') else: return (False, '()') def effect_string_before(self, act): return f'{N.char(act.source)}{N.char(act.target)...
class GraphTask(ABC): def __init__(self, traversal_node: TraversalNode, resources: TaskResources): super().__init__() self.traversal_node = traversal_node self.resources = resources self.connector: BaseConnector = resources.get_connector(self.traversal_node.node.dataset.connection_ke...
class bsn_lua_upload(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 64 def __init__(self, xid=None, flags=None, filename=None, data=None): if (xid != None): self.xid = xid else: self.xid = None if (flags != None): self.f...
class CmdChannel(COMMAND_DEFAULT_CLASS): key = '' aliases = ['', ''] help_category = 'Comms' locks = 'cmd:not pperm(channel_banned);admin:all();manage:all();changelocks:perm(Admin)' switch_options = ('list', 'all', 'history', 'sub', 'unsub', 'mute', 'unmute', 'alias', 'unalias', 'create', 'destroy',...
class OptionPlotoptionsWordcloudSonificationTracksMappingTremoloSpeed(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 ContainerClient(object): def __init__(self, global_configs, **kwargs): (max_calls, quota_period) = api_helpers.get_ratelimiter_config(global_configs, API_NAME) cache_discovery = (global_configs['cache_discovery'] if ('cache_discovery' in global_configs) else False) self.repository = Co...
def CommandFactory(name: str=None, command_id: int=None) -> Type[CommandAPI[None]]: if (command_id is None): command_id = 0 if (name is None): name = CommandNameFactory() return type(name, (BaseCommand,), {'protocol_command_id': command_id, 'serialization_codec': NoneSerializationCodec()})
class CreateFileRequest(DatClass): name: str file_id: str = None type: BaseFileType = 'folder' parent_file_id: str = 'root' size: int = field(default=None, repr=False) check_name_mode: CheckNameMode = field(default='auto_rename', repr=False) content_hash: str = field(default=None, repr=False...
def _dropout_ragged(model: Model[(InT, InT)], Xr: Ragged, is_train: bool) -> Tuple[(Ragged, Callable)]: X = Xr.data lengths = Xr.lengths mask = model.ops.get_dropout_mask(X.shape, model.attrs['dropout_rate']) Y = (X * mask) def backprop(dYr: Ragged) -> Ragged: return Ragged((dYr.data * mask)...
def update_node_faces(node, n2f, img): faceblock = {} n2f[node] = faceblock for position in FACE_POSITIONS: fixed_faces = getattr(node.props.get('_faces'), position, {}) all_faces = getattr(node.props.get('_temp_faces'), position) for (column, values) in fixed_faces.items(): ...
def dispatch(args): assert (len(args) >= 3) (mod_name, func_name, params) = (args[1], args[2], args[3:]) plugins = plugin_loader.loadPlugins('modules', 'PluginInterface_') if (mod_name not in plugins): log.error("Plugin module '%s' not found!", mod_name) print_help() return s...
class Icon(Html.Html): name = 'Icon' builder_name = 'HtmlIcon' tag = 'i' def __init__(self, page, value, width, height, color, tooltip, options, html_code, profile): if ((options['icon_family'] is not None) and (options['icon_family'] != 'bootstrap-icons')): self.requirements = (opti...
def scan_barcode_osx(*args_ignored, **kwargs_ignored): import subprocess prog = os.path.join(base_dir, 'CalinsQRReader.app/Contents/MacOS/CalinsQRReader') if (not os.path.exists(prog)): raise RuntimeError('Cannot start QR scanner; helper app not found.') data = '' try: with subproces...
class TestLastAlertFinding(SimpleTestCase): def test_no_alert_when_empty(self): cusum = bookmark_utils.CUSUM(['a', 'b']) cusum.alert_indices = [] self.assertIsNone(cusum.get_last_alert_info(), None) def test_no_alert_when_alert_not_most_recent(self): cusum = bookmark_utils.CUSUM(...
def recursive_group_by(argument): if (type(argument) in PRIMITIVES): return str(argument) if callable(argument): return recursive_group_by(argument()) try: result_list = [recursive_group_by(i) for i in argument] result_string = ','.join(result_list) return '({})'.form...
def remove_after_space(filename): result = filename if filename: idx_whitespace = (- 1) idx = (len(filename) - 1) for c in reversed(filename): if (c == '.'): break elif (c == ' '): idx_whitespace = idx idx -= 1 i...
class Composite(Html.Html): name = 'Composite' _option_cls = OptText.OptionsComposite def __init__(self, page: primitives.PageModel, schema, width, height, html_code, options, profile, helper): super(Composite, self).__init__(page, None, html_code=html_code, profile=profile, options=options, css_att...
def test_es_morphologizer_return_char(NLP): text = 'hi Aaron,\r\n\r\nHow is your schedule today, I was wondering if you had time for a phone\r\ncall this afternoon?\r\n\r\n\r\n' doc = NLP(text) for token in doc: if token.is_space: assert (token.pos == SPACE) assert (doc[3].text == '\...
class TextStringEncoder(encoding.TextStringEncoder): def validate_value(cls, value: Any) -> None: if is_bytes(value): try: value = to_text(value) except UnicodeDecodeError: cls.invalidate_value(value, msg='not decodable as unicode string') supe...
def setup_logging() -> None: def sl_processor_add_source_context(_, __, event_dict: Dict) -> Dict: (frame, name) = _find_first_app_frame_and_name([__name__, 'logging']) event_dict['file'] = frame.f_code.co_filename event_dict['line'] = frame.f_lineno event_dict['function'] = frame.f_...
class ClassHtml(): def __init__(self, component: primitives.HtmlModel=None, page: primitives.PageModel=None): (self._css_struct, self._css_class) = (None, None) (self.component, self.page) = (component, page) if (component is not None): self.page = component.page (self.cl...
class Person(): first: str last: str fullname: str def __init__(self, first, last, fullname): self.first = first self.last = last self.fullname = fullname def to_dict(self): return {'first': self.first, 'last': self.last, 'fullname': self.fullname}
class OptionPlotoptionsPyramid3dSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionPlotoptionsPyramid3dSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionPlotoptionsPyramid3dSonificationContexttracksMappingLowpassFrequency) def...
def matrix(text, cast): mtx = [] for first in cast: row = [] for second in cast: count = 0 for (title, chapter) in text['chapters'].items(): for sent in sent_tokenize(chapter): if ((first in sent) and (second in sent)): ...
class TestDeleteConnection(): (scope='function') def url(self, oauth_client: ClientDetail, policy, connection_config) -> str: return f'{V1_URL_PREFIX}{CONNECTIONS}/{connection_config.key}' def test_delete_connection_config_not_authenticated(self, url, api_client: TestClient, generate_auth_header, co...
class TextWithBorder(Html.Html): requirements = (cssDefaults.ICON_FAMILY,) name = 'Text with Border and Icon' _option_cls = OptText.OptionsText def __init__(self, page: primitives.PageModel, record: list, width: tuple, height: tuple, align: Optional[str], helper: Optional[str], options: Optional[dict], ...
class OptionSeriesColumnpyramidDataAccessibility(Options): def description(self): return self._config_get(None) def description(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(None) def enabled(self, flag: bool): self._config...
class ParticleSwarmOptimization(): def __init__(self, config: dict, backtest_wrap): self.backtest_wrap = backtest_wrap self.config = config self.do_long = config['long']['enabled'] self.do_short = config['short']['enabled'] self.n_particles = max(config['n_particles'], len(co...
def size_int(size_txt): try: return float(size_txt) except: try: size_txt = size_txt.upper() size = get_float(size_txt) if ('K' in size_txt): size *= 1000.0 if ('M' in size_txt): size *= 1000000.0 if ('G'...
def test_color_management_is_set_to_aces_cg(create_test_db, create_pymel, create_maya_env): pm = create_pymel from anima.dcc.mayaEnv.render import MayaColorManagementConfigurator MayaColorManagementConfigurator.configure(config_name='ACEScg') cmp = pm.colorManagementPrefs assert (cmp(q=1, cmEnabled=...
class RangeSelectionOverlay(AbstractOverlay): axis = Enum('index', 'value') plot = Property(observe='component') mapper = Instance(AbstractMapper) axis_index = Property metadata_name = Str('selections') border_color = ColorTrait('dodgerblue') border_width = Float(1.0) border_style = Line...
def _mk_bytecode(opcodes, data): index_tracker = itertools.count(0) for opcode in opcodes: opcode_as_byte = bytes((opcode,)) if (opcode in NON_PUSH_CODES): (yield (next(index_tracker), opcode_as_byte)) else: data_size = (opcode - 95) push_data = data.d...
class Planetary2(Boxes): ui_group = 'Unstable' description = "Still has issues. The middle planetary gears set must not have a mashing sun gear as it can't be a proper gear set." def __init__(self) -> None: Boxes.__init__(self) self.buildArgParser('nema_mount') self.argparser.add_arg...
def mismatched_host_error(host, form): g.log.info('Submission rejected. From a different host than confirmed.') if request_wants_json(): return jsonerror(403, {'error': 'Submission from different host than confirmed', 'submitted': host, 'confirmed': form.host}) return (render_template('error.html', ...
class dumpSoForm(QDialog, Ui_DumpSoDialog): def __init__(self, parent=None): super(dumpSoForm, self).__init__(parent) self.setupUi(self) self.setWindowOpacity(0.93) self.btnSubmit.clicked.connect(self.submit) self.moduleName = '' self.btnClear.clicked.connect(self.cle...
class Metadata(HasTraits): id = Str class_name = Str factory = Either(Str, Callable, allow_none=False) desc = Str help = Str menu_name = Str tooltip = Str input_info = Instance(PipelineInfo) output_info = Instance(PipelineInfo) def get_callable(self): factory = self.facto...
class MainDialog(QtWidgets.QDialog, AnimaDialogBase): def __init__(self, *args, **kwargs): super(MainDialog, self).__init__(*args, **kwargs) self.vertical_layout = None self._setup_ui() def _setup_ui(self): self.vertical_layout = QtWidgets.QVBoxLayout(self) ConformerUI(se...