code
stringlengths
281
23.7M
def cifti_parcellate_to_meants(settings): with ciftify.utils.TempDir() as tempdir: if settings.func.path.endswith('dtseries.nii'): tmp_parcelated = os.path.join(tempdir, 'parcellated.ptseries.nii') if settings.func.path.endswith('dscalar.nii'): tmp_parcelated = os.path.join(t...
class DeleteCategory(MethodView): decorators = [allows.requires(IsAdmin, on_fail=FlashAndRedirect(message=_('You are not allowed to modify categories'), level='danger', endpoint='management.overview'))] def post(self, category_id): category = Category.query.filter_by(id=category_id).first_or_404() ...
class OptionPlotoptionsTreegraphSonificationDefaultinstrumentoptionsMappingTremoloSpeed(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(se...
def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool: tbodyLines = None if ((startLine + 2) > endLine): return False nextLine = (startLine + 1) if (state.sCount[nextLine] < state.blkIndent): return False if state.is_code_block(nextLine): return Fal...
class OptionSeriesWindbarbSonificationContexttracksMappingLowpassFrequency(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 FullStackTest(unittest.TestCase, TestBot): def setUp(self, extra_plugin_dir=None, extra_test_file=None, loglevel=logging.DEBUG, extra_config=None) -> None: if ((extra_plugin_dir is None) and (extra_test_file is not None)): extra_plugin_dir = sep.join(abspath(extra_test_file).split(sep)[:(-...
class NiceExpander(): def __init__(self, expanded_button, unexpanded_button, paned, child): self.expanded_button = expanded_button self.unexpanded_button = unexpanded_button self.paned = paned self.child = child self.sensitive = True self.expanded = False self...
class TestResolve(tests.LimitedTestCase): def setUp(self): base_resolver = _make_mock_base_resolver() base_resolver.rr.address = '1.2.3.4' self._old_resolver = greendns.resolver greendns.resolver = base_resolver() def tearDown(self): greendns.resolver = self._old_resolver...
class Solution(): def minimumLengthEncoding(self, words: List[str]) -> int: words.sort(key=(lambda x: (- len(x)))) cnt = 0 tree = {} for word in words: curr = tree is_new = False for i in range((len(word) - 1), (- 1), (- 1)): c = wo...
class SupermeshProjectBlock(Block, Backend): def __init__(self, source, target_space, target, bcs=[], **kwargs): super(SupermeshProjectBlock, self).__init__(ad_block_tag=kwargs.pop('ad_block_tag', None)) import firedrake.supermeshing as supermesh if (not isinstance(source, self.backend.Funct...
def reclassify_statutory_citation(title, section): MAPPED_TITLE = '52' if (title == '2'): mapped_section = CITATIONS_MAP.get(section) if mapped_section: logger.debug('Mapping 2 U.S.C statute citation %s -> %s', (title, section), (MAPPED_TITLE, mapped_section)) return (MAP...
def stats(ts, tlog, dbal, capital): start = ts.index[0] end = ts.index[(- 1)] stats = pd.Series(dtype='object') stats['start'] = start.strftime('%Y-%m-%d') stats['end'] = end.strftime('%Y-%m-%d') stats['beginning_balance'] = _beginning_balance(capital) stats['ending_balance'] = _ending_balan...
class where(Operator): def __init__(self) -> None: super().__init__() self._attrs['op'] = 'where' def __call__(self, condition: Tensor, input_tensor: Tensor, other_tensor: Tensor, dtype: str='') -> Tensor: assert isinstance(condition, Tensor), f'condition needs to be a tensor, but got {t...
def extractWwwDummytranslationsCom(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_typ...
(scope='module') def android_app(default_app): del default_app android_apps = project_management.list_android_apps() for android_app in android_apps: if _starts_with(android_app.get_metadata().display_name, TEST_APP_DISPLAY_NAME_PREFIX): return android_app return project_management.c...
class ComputeTaskType(Enum): NONE = 'None' LLM_COMPLETION = 'llm_completion' TEXT_2_IMAGE = 'text_2_image' IMAGE_2_IMAGE = 'image_2_image' VOICE_2_TEXT = 'voice_2_text' TEXT_2_VOICE = 'text_2_voice' TEXT_EMBEDDING = 'text_embedding' IMAGE_EMBEDDING = 'image_embedding'
class Style(): def pos_sys_msg(string): print(((((('[' + Fore.GREEN) + '*') + St.RESET_ALL) + '] ') + string)) def neg_sys_msg(string): print(((((('[' + Fore.RED) + '-') + St.RESET_ALL) + '] ') + string)) def client_connect_msg(): stdout.write((((((('\n[' + Fore.GREEN) + '*') + St.RE...
class WorkflowExecutionPhase(object): UNDEFINED = _execution_pb2.WorkflowExecution.UNDEFINED QUEUED = _execution_pb2.WorkflowExecution.QUEUED RUNNING = _execution_pb2.WorkflowExecution.RUNNING SUCCEEDING = _execution_pb2.WorkflowExecution.SUCCEEDING SUCCEEDED = _execution_pb2.WorkflowExecution.SUCCE...
.parametrize('degree', [1, 2]) def test_rtce_expansion(tpc_quad, degree): actual = FiniteElement('RTCE', tpc_quad, degree) C_elt = FiniteElement('CG', interval, degree) D_elt = FiniteElement('DG', interval, (degree - 1)) expected = (HCurl(TensorProductElement(C_elt, D_elt)) + HCurl(TensorProductElement(...
def firebase_config() -> (None | FirebaseConfig): config_file = _os.getenv('FIREBASE_CONFIG') if (not config_file): return None if config_file.startswith('{'): json_str = config_file else: try: with open(config_file, 'r', encoding='utf8') as json_file: ...
class PaymentRequestTable(BaseWalletStore): LOGGER_NAME = 'db-table-prequest' CREATE_SQL = 'INSERT INTO PaymentRequests (paymentrequest_id, keyinstance_id, state, value, expiration, description, date_created, date_updated) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' READ_ALL_SQL = 'SELECT P.paymentrequest_id, P.keyins...
def test_adding_a_secret_mount_with_default_mode(): config = '\nsecretMounts:\n - name: elastic-certificates\n secretName: elastic-certs\n path: /usr/share/elasticsearch/config/certs\n subPath: cert.crt\n defaultMode: 0755\n' r = helm_template(config) s = r['statefulset'][uname]['spec']['templa...
def extractWhitemoonlight74WordpressCom(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, t...
class Observation(BMGNode): value: Any def __init__(self, observed: BMGNode, value: Any): self.value = value BMGNode.__init__(self, [observed]) def observed(self) -> BMGNode: return self.inputs[0] def __str__(self) -> str: return ((str(self.observed) + '=') + str(self.val...
class GuildOps(gh.ObjectType): GuCreate = gh.Field(Guild, name=gh.String(required=True, description=''), slogan=gh.String(required=True, description=''), totem=gh.String(description='(URL)'), description='') GuTransfer = gh.Boolean(guild_id=gh.Int(required=True, description='ID'), to=gh.Int(required=True, descr...
def run(build_dir, db_dir, pip_dir, intre, sides, l, r, pip_type, seg_type, exclude_re=None, balance_wire_re=None, balance_wire_direction=None, balance_wire_cnt=None, not_endswith=None, verbose=False): if (db_dir is None): db_dir = ('%s/%s' % (os.getenv('XRAY_DATABASE_DIR'), os.getenv('XRAY_DATABASE'))) ...
class GraphVizNode(): in_edges: Set[str] = set() def __init__(self, name: str) -> None: self.__name = name self.__grouping: str = '' self.__in_edge: str = '' self.__out_edges: List[str] = [] self.__upstream_node: 'GraphVizNode ' = None def name(self) -> str: r...
class OptionSeriesScatterSonificationDefaultspeechoptionsMappingPitch(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('undefined') def mapTo(self, text: s...
class Analytics(object): def __init__(self, filters=None): self.filters = frappe._dict((filters or {})) self.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] self.get_period_date_ranges() def run(self): self.get_columns() self....
class CliTester(): def __init__(self, monkeypatch, mocker): self.argv = sys.argv.copy() self.monkeypatch = monkeypatch self.mocker = mocker def mock_subroutines(self, *args, **kwargs): return def run_and_test_parameters(self, argv=None, parameters={}): sys.argv = ['br...
class Solution(): def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: def overlap(a, b): return ((a[0] < b[1]) and (b[0] < a[1])) intervals.sort() last = None count = 0 for interval in intervals: if ((not last) or (not overlap(last, int...
def exact_solution(X, t): radius = 0.15 if (nd == 2): xc = 0.5 yc = 0.75 if (ct.test_case == 1): r = np.sqrt((((X[0] - xc) ** 2) + ((X[1] - yc) ** 2))) return (radius - r) elif (type(X) != dict): return zalesak_disk_per_point(X, 0) else...
class OptionSeriesWordcloudSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionSeriesWordcloudSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionSeriesWordcloudSonificationDefaultspeechoptionsMappingPitch) def playDelay(self) -> 'OptionSeri...
class SimpleInspectorOverlay(TextGridOverlay): inspector = Any field_formatters = List(List(Callable)) tooltip_mode = Bool(False) visible = True visibility = Enum('auto', True, False) def _field_formatters_default(self): return [[basic_formatter('x', 2)], [basic_formatter('y', 2)]] d...
class Event(Reporter): def __init__(self, evaluator_url, token=None, cert_path=None): self._evaluator_url = evaluator_url self._token = token if (cert_path is not None): with open(cert_path, encoding='utf-8') as f: self._cert = f.read() else: s...
class flow_removed(message): version = 1 type = 11 def __init__(self, xid=None, match=None, cookie=None, priority=None, reason=None, duration_sec=None, duration_nsec=None, idle_timeout=None, packet_count=None, byte_count=None): if (xid != None): self.xid = xid else: s...
def test(): assert ((len(doc1.ents) == 2) and (len(doc2.ents) == 2) and (len(doc3.ents) == 2)), 'Fur alle Beispiele werden zwei Entitaten erwartet.' assert any((((e.label_ == 'PER') and (e.text == 'PewDiePie')) for e in doc2.ents)), 'Hast du das Label PER korrekt zugeordnet?' assert any((((e.label_ == 'PER'...
class OptionSeriesColumnrangeSonificationDefaultinstrumentoptionsMappingNoteduration(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,...
class AlarmClock(hass.Hass): def initialize(self): self.timer_handle_list = [] self.listen_event_handle_list = [] self.listen_state_handle_list = [] self.alarm_time = self.args['alarm_time'] self.wakemeup = self.args['wakemeup'] self.naturalwakeup = self.args['natural...
class AutozoomDialog(Gtk.Window): def __init__(self, main_window, f): super().__init__(title=_('Autozoom'), transient_for=main_window, modal=True) self.f = f content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) self.set_child(content) table = Gtk.Grid(column_spacing=5, row...
class CORSMiddleware(object): def process_request(self, request): if ('HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META): response = response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS response['Access-Control-Allow-Methods'] = ','.join(XS_SHARING_ALL...
def poisson3D(h, degree=2): try: from netgen.csg import CSGeometry, OrthoBrick, Pnt import netgen except ImportError: pytest.skip(reason='Netgen unavailable, skipping Netgen test.') comm = COMM_WORLD if (comm.Get_rank() == 0): box = OrthoBrick(Pnt(0, 0, 0), Pnt(np.pi, np....
def parse_url(url): is_url = False is_absolute = False (scheme, netloc, path, params, query, fragment) = urlparse(html_parser.unescape(url)) if RE_URL.match(scheme): is_url = True elif ((scheme == '') and (netloc == '') and (path == '')): is_url = True elif ((scheme == 'file') an...
class OptionSeriesFunnel3dSonificationContexttracksMappingTremolo(Options): def depth(self) -> 'OptionSeriesFunnel3dSonificationContexttracksMappingTremoloDepth': return self._config_sub_data('depth', OptionSeriesFunnel3dSonificationContexttracksMappingTremoloDepth) def speed(self) -> 'OptionSeriesFunne...
class load(bsn_tlv): type = 213 def __init__(self, value=None): if (value != None): self.value = value else: self.value = 0 return def pack(self): packed = [] packed.append(struct.pack('!H', self.type)) packed.append(struct.pack('!H', 0...
() ('infile', type=click.File('r'), default='-') ('-j', '--json', 'json_output', is_flag=True, default=False, help='JSON output') ('-u', '--unique', 'unique', is_flag=True, default=False, help='Remove duplicates') ('-v', 'verbose', is_flag=True, default=False, help='Verbose output') def cmd_data_extract_ipv4(infile, js...
_os(*metadata.platforms) def main(): msbuild = 'C:\\Users\\Public\\posh.exe' rcedit = 'C:\\Users\\Public\\rcedit.exe' common.copy_file(RENAMER, rcedit) common.copy_file(EXE_FILE, msbuild) common.log('Modifying the OriginalFileName attribute') common.execute([rcedit, msbuild, '--set-version-strin...
.skipcomplex def test_consecutive_nonlinear_solves(): from firedrake.adjoint import ReducedFunctional, Control, taylor_test mesh = UnitSquareMesh(1, 1) V = FunctionSpace(mesh, 'CG', 1) uic = Constant(2.0, domain=mesh) u1 = Function(V).assign(uic) u0 = Function(u1) v = TestFunction(V) F =...
def validate_exchange(item, k) -> None: validate_datapoint_format(datapoint=item, kind='exchange', zone_key=k) if (item.get('sortedZoneKeys', None) != k): raise ValidationError(f"Sorted country codes {item.get('sortedZoneKeys', None)} and {k} don't match") if ('datetime' not in item): raise ...
class TestOefSearchHandler(ERC1155DeployTestCase): is_agent_to_agent_messages = False def test_setup(self): assert (self.oef_search_handler.setup() is None) self.assert_quantity_in_outbox(0) def test_handle_unidentified_dialogue(self): incorrect_dialogue_reference = ('', '') ...
def extractAdjacentaisleHomeBlog(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('otome survival', 'The Otome Game Heroines Strongest Survival', 'translated'), ('PRC', 'PRC', 't...
def compiled_query(output_variables=None, group_by=None): if (output_variables is None): output_variables = [] postprocessors = [] calling_frame = inspect.stack()[1] if (group_by is not None): postprocessors.append(GroupByPostprocessor(group_by)) def func_transformer(fct): re...
def test_proper_name_argument(): argument = ProperNameArgument() assert argument.validate('NAME') assert argument.validate('__NAME__') assert argument.validate('<NAME>') assert argument.validate('-NAME-') assert (not argument.validate('-NA ME-')) assert (not argument.validate('NAME*'))
def cbFun(snmpEngine, sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx): if errorIndication: print(errorIndication) elif errorStatus: print(('%s at %s' % (errorStatus.prettyPrint(), ((errorIndex and varBinds[(int(errorIndex) - 1)][0]) or '?')))) else: for ...
def run_migrations_online(): configuration = config.get_section(config.config_ini_section) configuration['sqlalchemy.url'] = get_url() connectable = engine_from_config(configuration, prefix='sqlalchemy.', poolclass=pool.NullPool) def process_revision_directives(context, revision, directives): if...
class clamp(Operator): def __init__(self) -> None: super().__init__() self._attrs['op'] = 'clamp' self._attrs['has_profiler'] = False def __call__(self, x: Tensor, min_value: Any=None, max_value: Any=None) -> Tensor: if ((min_value is None) and (max_value is not None)): ...
class RadioList(): def __init__(self, name, station=None): self.name = name self.station = station def set_name(self, name): self.name = name def get_name(self): return self.name def get_items(self, no_cache=False): return [] def __str__(self): return ...
def extractIterations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (('SaeKano' in item['tags']) and (chp or vol)): return buildReleaseMessageWithType(item, 'Saenai Heroine no...
def init_oidc_app(app): oidc = OAuth(app) if oidc_enabled(app.config): client_id = app.config.get('OIDC_CLIENT') secret = app.config.get('OIDC_SECRET') client_kwargs = {'scope': app.config.get('OIDC_SCOPES'), 'token_endpoint_auth_method': app.config.get('OIDC_TOKEN_AUTH_METHOD')} ...
class BsModals(html.Html.Html): name = 'Bootstrap Modals' def __init__(self, report, components, title, width, height, options, profile): super(BsModals, self).__init__(report, []) self.style.clear_all() self.attr['class'].add('modal fade') self.attr['role'] = 'dialog' se...
def chunk_scaffolds(log, target, size): chromos = [] (temp_fd, temp_out) = tempfile.mkstemp(suffix='.fasta') os.close(temp_fd) temp_out_handle = open(temp_out, 'w') with open(target, 'rb') as f: tb = twobit.TwoBitFile(f) sequence_length = 0 tb_key_len = (len(tb.keys()) - 1) ...
def test_pyscf(): pyscf_ = PySCF(basis='3-21g', pal=4) geom = geom_from_library('hcn_iso_ts.xyz') geom.set_calculator(pyscf_) f = geom.forces.reshape((- 1), 3) print('PySCF') print(f) H = geom.hessian print('PySCF hessian') print(H.reshape((- 1), 9)) ref_geom = geom.copy() fr...
def _validate_enum_symbols(schema): symbols = schema['symbols'] for symbol in symbols: if ((not isinstance(symbol, str)) or (not SYMBOL_REGEX.fullmatch(symbol))): raise SchemaParseException('Every symbol must match the regular expression [A-Za-z_][A-Za-z0-9_]*') if (len(symbols) != len(s...
def tree_gen(mock_config_helper, tmp_path): (tmp_path / 'dir1').mkdir() ((tmp_path / 'dir1') / 'file1.txt').touch() (tmp_path / 'dir2').mkdir() tree_gen = TreeGenerator(conf_helper=mock_config_helper, root_dir=tmp_path, repo_url=' repo_name='TestProject', max_depth=3) return tree_gen
def aggregate_and_return_observation_data(observations): out_data = [] obs_length = 0 for obs in observations: if (not obs.get('has_component')): if obs.get('permitted_data_type'): obs_length += 1 if ((obs.get('permitted_data_type') == 'Select') and obs.get('o...
def forward(model, X, is_train): index = model.attrs['index'] shape = X.shape dtype = X.dtype def backprop_get_column(dY): dX = model.ops.alloc(shape, dtype=dtype) dX[index] = dY return dX if (len(X) == 0): return (X, backprop_get_column) Y = X[index] return (...
class OpenAIFunction(): def __init__(self, name: str, description: str, properties: Dict[(str, Dict[(str, str)])], required: Optional[List[str]]=None): self.name = name self.description = description self.properties = properties self.required = (required or []) def to_dict(self) ...
class clsvof_init_cond(object): def uOfXT(self, x, t): if (IC_type == 0): if ((x[0] == 0) and (x[1] >= 0.3) and (x[1] <= 0.35)): return 0.0 elif ((x[1] >= 0.3) and (x[1] <= 0.35)): return x[0] elif (x[1] >= 0.35): return np....
class EngineRichView(EngineView): def default_traits_view(self): view = View(HSplit(Item('engine', id='mayavi.engine_rich_view.pipeline_view', springy=True, resizable=True, editor=self.tree_editor, dock='tab', label='Pipeline'), Item('engine', id='mayavi.engine_rich_view.current_selection', editor=InstanceE...
_os(*metadata.platforms) def main(): powershell = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' exe = 'C:\\Users\\Public\\a.exe' common.copy_file(EXE_FILE, exe) common.execute([powershell, '/c', f'Set-Content -Stream RtaTest -value Heyo -Path {exe}'], timeout=10) common.remove_fil...
def test_raises_if_username_too_long(): requirements = UsernameRequirements(min=0, max=1, blacklist=set()) validator = UsernameValidator(requirements) registration = UserRegistrationInfo(username='no', password='no', email='', group=4, language='no') with pytest.raises(ValidationError) as excinfo: ...
def config_init(args): if (not os.path.exists(NOTIFICATION_HOME)): os.makedirs(NOTIFICATION_HOME) config_file = (NOTIFICATION_HOME + '/notification_server.yaml') if os.path.exists(config_file): logger.info('Notification server config has already initialized at {}.'.format(config_file)) e...
def populate_textarray(fname, feats_dir, feats_dict): feats_array = [] f = open(fname) for line in f: line = line.split('\n')[0] feats = line for feat in feats: feats_array.append(feats_dict[feat]) feats_array = np.array(feats_array) return feats_array
class BaseAutocompleteViewSet(APIView): def get_request_payload(request): json_request = request.data search_text = json_request.get('search_text', None) try: limit = int(json_request.get('limit', 10)) except ValueError: raise InvalidParameterException('Limit ...
class OptionSeriesScatter3dSonificationContexttracksMappingHighpassFrequency(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: s...
def upgrade(): op.execute('DELETE FROM comments WHERE update_id IS NULL') op.execute('DELETE FROM comment_bug_assoc WHERE comment_id IS NULL') op.execute('DELETE FROM comment_testcase_assoc WHERE comment_id IS NULL') op.alter_column('comments', 'update_id', existing_type=sa.INTEGER(), nullable=False)
def init_env_with_observation_normalization(env_factory: Callable[([], StructuredEnv)], normalization_config: Dict) -> ObservationNormalizationWrapper: wrapped_env = ObservationNormalizationWrapper.wrap(env_factory(), **normalization_config) wrapped_env = estimate_normalization_statistics(wrapped_env) retur...
() ('-j', 'json_output', is_flag=True, default=False, help='Output in JSON format') def cmd_net_interfaces(json_output): interfaces = get_ifaces() if json_output: print(json.dumps(interfaces, indent=4)) return True print('{:<3}{:<32}{:<19}{:<17}{}'.format('#', 'NAME', 'MAC', 'INET', 'INET6')...
def _all_dims_in_graph(sorted_graph: List[Tensor]): dim_idx = 0 for node in sorted_graph: for dim in node._attrs['shape']: (yield (dim_idx, dim)) dim_idx += 1 sorted_ops = graph_utils.get_sorted_ops(sorted_graph) for op in sorted_ops: input_accessors = op._attrs.g...
def main(arguments): if (arguments.command == 'generate'): obfuscated = generate.generate(password=arguments.password, obfuscator=arguments.obfuscator, agent=arguments.agent) generate.save_generated(obfuscated, arguments.path) if (arguments.path != '-'): log.info((messages.genera...
def create_panel_permissions(): (sales_panel, _) = get_or_create(PanelPermission, panel_name=SALES) (sales_admin, _) = get_or_create(CustomSysRole, name='Sales Admin') (marketer, _) = get_or_create(CustomSysRole, name='Marketer') sales_panel.custom_system_roles.append(sales_admin) sales_panel.custom...
_test def test_zmq_send_and_poll() -> None: class MyZMQGraphConfig(Config): addr: str zmq_topic: str output_filename: str class MyZMQGraph(Graph): DF_SOURCE: MySource ZMQ_SENDER: ZMQSenderNode ZMQ_POLLER: ZMQPollerNode DF_SINK: MySink def setup(sel...
def getvcs(vcstype, remote, local): if (vcstype == 'git'): return vcs_git(remote, local) if (vcstype == 'git-svn'): return vcs_gitsvn(remote, local) if (vcstype == 'hg'): return vcs_hg(remote, local) if (vcstype == 'bzr'): return vcs_bzr(remote, local) if (vcstype == ...
def upgrade(): op.create_table('activity', sa.Column('id', sa.Integer(), nullable=False), sa.Column('actor', sa.String(), nullable=True), sa.Column('time', sa.DateTime(), nullable=True), sa.Column('namespace', sa.String(), nullable=True), sa.Column('detail', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id'...
class ApodizationSpec(Tidy3dBaseModel): start: pd.NonNegativeFloat = pd.Field(None, title='Start Interval', description='Defines the time at which the start apodization ends.', units=SECOND) end: pd.NonNegativeFloat = pd.Field(None, title='End Interval', description='Defines the time at which the end apodizatio...
class OptionSeriesStreamgraphStatesHover(Options): def animation(self) -> 'OptionSeriesStreamgraphStatesHoverAnimation': return self._config_sub_data('animation', OptionSeriesStreamgraphStatesHoverAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
class TestServiceAsync(pb2_grpc.TestServiceServicer): def __init__(self, *args, **kwargs) -> None: pass async def GetServerResponse(self, request, context): message = request.message result = f'Hello I am up and running received "{message}" message from you' result = {'message': ...
class TestCentroidsMatrix(): class TestBuildSupportSet(): def test_should_raise_value_error_when_inputs_is_not_list(): with pytest.raises(ValueError) as error: CentroidsMatrix(kernel=sentinel.kernel).build_support_set(sentinel.inputs) assert (str(error.value) == f'Cen...
def CreateBmmCCRBillinearOperator(manifest, c_element_op): operation_kind = library.GemmKind.BatchGemm a_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.ColumnMajor) b_element_desc = library.TensorDesc(library.DataType.f16, library.LayoutType.ColumnMajor) c_element_desc = libr...
('normalize-data') ('events-file', type=click.File('r')) def normalize_data(events_file): file_name = os.path.splitext(os.path.basename(events_file.name))[0] events = RtaEvents({file_name: [json.loads(e) for e in events_file.readlines()]}) events.save(dump_dir=os.path.dirname(events_file.name))
def get_aggregate_flow_stats(dp, waiters, flow=None, to_user=True): flow = (flow if flow else {}) table_id = UTIL.ofp_table_from_user(flow.get('table_id', dp.ofproto.OFPTT_ALL)) flags = str_to_int(flow.get('flags', 0)) out_port = UTIL.ofp_port_from_user(flow.get('out_port', dp.ofproto.OFPP_ANY)) out...
def cs_getBeaconInfo(teamserver, user, password, cobaltstrike_directory, bid): username = f'{user}_beacon_query' with CSConnector(cs_host=teamserver, cs_user=username, cs_pass=password, cs_directory=cobaltstrike_directory) as cs: query = f'return binfo({bid})' beacon = cs.ag_get_object(query) ...
def get_connection(): connection = config.attributes.get('connection', None) if (connection is not None): (yield connection) return engine = engine_from_config(config.get_section(config.config_ini_section), prefix='sqlalchemy.', url=config.get_main_option('sqlalchemy.url'), poolclass=pool.Nu...
def extractWatermelonHelmets(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if (('Dragon Life' in item['tags']) or ('Dragon Life: Chapter' in item['title'])): return buildReleaseM...
class CanValidate(object): def remote_validate(self, params=None): params = (params or {}) data_cache = dict(self._data) changes_cache = dict(self._changes) params['execution_options'] = ['validate_only'] self.save(params=params) self._data = data_cache self._...
def _fuse_expand_elementwise(sorted_graph: List[Tensor]) -> List[Tensor]: def _is_compatible_with_broadcasting(expand_output_dim: IntVar, elementwise_input_dim: IntVar) -> bool: return ((expand_output_dim == elementwise_input_dim) or is_singleton_dimension(expand_output_dim)) def _replace_jagged_int_var...
class _CRG(LiteXModule): def __init__(self, platform, sys_clk_freq, sata_refclk_src='internal'): self.cd_sys = ClockDomain() self.cd_sata_refclk = ClockDomain() self.pll = pll = USPMMCM(speedgrade=(- 2)) pll.register_clkin(platform.request('clk300'), .0) pll.create_clkout(sel...
def get_registrable_entities(ctx: flyte_context.FlyteContext, options: typing.Optional[Options]=None) -> typing.List[FlyteControlPlaneEntity]: new_api_serializable_entities = OrderedDict() for entity in flyte_context.FlyteEntities.entities.copy(): if (isinstance(entity, PythonTask) or isinstance(entity,...
class OptionSeriesArcdiagramNodesDatalabels(Options): def align(self): return self._config_get('undefined') 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._confi...
_meta(characters.keine.Teach) class Teach(): name = '' description = ',,,:<style=Desc.Li>,</style><style=Desc.Li></style>' def clickable(self): return (self.my_turn() and (not ttags(self.me)['teach_used'])) def is_action_valid(self, sk, tl): cards = sk.associated_cards if ((not c...