code
stringlengths
281
23.7M
def test_lifecycle_hooks(): config = '' r = helm_template(config) c = r['statefulset'][name]['spec']['template']['spec']['containers'][0] assert ('lifecycle' not in c) config = '\n lifecycle:\n preStop:\n exec:\n command: ["/bin/bash","/preStop"]\n ' r = helm_template(...
class TestBurnBitCommands(EfuseTestCase): .skipif((arg_chip != 'esp32'), reason='ESP32-only') def test_burn_bit_for_chips_with_3_key_blocks(self): self.espefuse_py('burn_bit -h') self.espefuse_py('burn_bit BLOCK3 0 1 2 4 8 16 32 64 96 128 160 192 224 255') self.espefuse_py('summary', che...
class TestTempDir(unittest.TestCase): def tearDown(self): if os.path.exists(self.path): shutil.rmtree(self.path) def test_temp_dir_removed_when_exception_occurs(self): try: with utils.TempDir() as temp: self.path = temp assert os.path.exist...
class QGradientEditorWidget(QtGui.QWidget, GradientEditorWidget): def __init__(self, master, vtk_table, on_change_color_table=None, colors=None): kw = dict(master=master, vtk_table=vtk_table, on_change_color_table=on_change_color_table, colors=colors) super().__init__(**kw) gradient_preview_...
def plot_timeline(title: str, events: pd.DataFrame, ranks: Optional[List[int]]=None) -> None: t0 = perf_counter() must_have_columns: List[str] = ['calibrated_start_global', 'calibrated_end_global', 'task', 'label'] if (not set(must_have_columns).issubset(set(events.columns))): raise ValueError(f"the...
def test_exclude_columns(): (app, db, admin) = setup() with app.app_context(): (Model1, Model2) = create_models(db) view = CustomModelView(Model1, db.session, column_exclude_list=['test2', 'test4', 'enum_field', 'date_field', 'time_field', 'datetime_field', 'sqla_utils_choice', 'sqla_utils_enum'...
def downgrade(): op.create_index('web_pages_state_netloc_idx', 'web_pages', ['state', 'netloc'], unique=False) op.drop_index(op.f('ix_nu_outbound_wrappers_link_url'), table_name='nu_outbound_wrappers') op.drop_index(op.f('ix_nu_outbound_wrappers_container_page'), table_name='nu_outbound_wrappers') op.dr...
def test_rename_intrinsic(): string = write_rpc_request(1, 'initialize', {'rootPath': str((test_dir / 'rename'))}) file_path = ((test_dir / 'rename') / 'test_rename_nested.f90') string += rename_request('bar', file_path, 8, 27) (errcode, results) = run_request(string, ['-n', '1']) assert (errcode ==...
(scope='module') def sample_image(ref_path: Path) -> Image.Image: test_image = (ref_path / 'macaw.png') if (not test_image.is_file()): warn(f'could not reference image at {test_image}, skipping') pytest.skip(allow_module_level=True) img = Image.open(test_image) assert (img.size == (512, ...
class DiplomacyDictProcessor(AbstractGamestateDataProcessor): ID = 'diplomacy' DEPENDENCIES = [CountryProcessor.ID] def __init__(self): super().__init__() self.diplomacy_dict = None self.truce_countries = None def initialize_data(self): self.diplomacy_dict = {} se...
def sync(): print('logging in...') client = FrappeClient(' 'xxx', 'xxx') with open('jobs.csv', 'rU') as jobsfile: reader = csv.reader(jobsfile, dialect='excel') for row in reader: if (row[0] == 'Timestamp'): continue print(('finding ' + row[EMAIL])) ...
.usefixtures('use_tmpdir') def test_that_non_existant_job_directory_gives_config_validation_error(): test_config_file_base = 'test' test_config_file_name = f'{test_config_file_base}.ert' test_config_contents = dedent('\n NUM_REALIZATIONS 1\n DEFINE <STORAGE> storage/<CONFIG_FILE_BASE>-<DATE>\...
class FBPrintAccessibilityIdentifiers(fb.FBCommand): def name(self): return 'pa11yi' def description(self): return 'Print accessibility identifiers of all views in hierarchy of <aView>' def args(self): return [fb.FBCommandArgument(arg='aView', type='UIView*', help='The view to print ...
def gen_list_setup_check(out, cls, version): out.write(("\n/**\n * Populate a list of type %(cls)s with two of each type of subclass\n * list Pointer to the list to be populated\n * value The seed value to use in populating the list\n * The value after increments for this object's values\n */\nint\n%(cls)s_%(v_n...
def audit_organizations(url: str, headers: Dict[(str, str)], include_keys: Optional[List]=None) -> None: organization_resources: Optional[List[FidesModel]] if include_keys: organization_resources = get_server_resources(url, 'organization', include_keys, headers) else: raw_organization_resour...
('flytekit.configuration.plugin.FlyteRemote', spec=FlyteRemote) ('flytekit.clients.friendly.SynchronousFlyteClient', spec=SynchronousFlyteClient) def test_non_fast_register_require_version(mock_client, mock_remote): mock_remote._client = mock_client mock_remote.return_value._version_from_hash.return_value = 'du...
def extractWwwOtakubuCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Hyaku Ma No Omo', 'Hyaku Ma No Omo', 'translated'), ('Hyaku Ma No Aruji', 'Hyaku Ma No Aruji', 'transla...
class FeederBroker(Broker): def __init__(self, config_overrides=None): if (config_overrides is None): config_overrides = {} config = {'listeners': {'default': {'max-connections': 50000, 'type': 'tcp'}, 'tcp-1': {'bind': f'0.0.0.0:{settings.mqtt_port}'}, 'tcp-ssl-1': {'bind': f'0.0.0.0:{s...
class ServerLogFormatter(logging.Formatter): def __init__(self, use_color=True): super().__init__() self.use_color = use_color self.color_mapping = {'CRITICAL': 'bold_red', 'ERROR': 'red', 'WARNING': 'yellow', 'INFO': 'green', 'DEBUG': 'blue'} def format(self, rec): if rec.exc_in...
def unconfirm_multiple(): unconfirming_for_email = session.get('unconfirming') if (not unconfirming_for_email): return (render_template('error.html', title='Forbidden', text="You're not allowed to unconfirm these forms."), 401) for form_id in request.form.getlist('form_ids'): form = Form.que...
class OptionSeriesWordcloudSonificationContexttracksActivewhen(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)...
.parametrize('call_deployed_contract', (True, False)) .parametrize('api_style', ('v4', 'build_filter')) def test_on_filter_using_get_entries_interface(w3, emitter, emitter_contract_factory, wait_for_transaction, emitter_contract_event_ids, call_deployed_contract, api_style, create_filter): if call_deployed_contract...
def decompile_function(ghidra_analysis, func): if (func.name in ghidra_analysis.high_funcs): return ghidra_analysis.high_funcs[func.name] decompile_result = ghidra_analysis.decompiler.decompileFunction(func, ghidra_analysis.decompiler.getOptions().getDefaultTimeout(), ghidra_analysis.monitor) high_f...
def test_loop_to_sequence_rule_not_possible_break(): ast = AbstractSyntaxForest(condition_handler=condition_handler1(LogicCondition.generate_new_context())) root = ast.factory.create_endless_loop_node() body = ast.factory.create_seq_node() children = [ast.factory.create_code_node(stmts=[assignment_c_plu...
(scope='function') def storage_config(db: Session) -> Generator: name = str(uuid4()) storage_config = StorageConfig.create(db=db, data={'name': name, 'type': StorageType.s3, 'details': {StorageDetails.AUTH_METHOD.value: S3AuthMethod.SECRET_KEYS.value, StorageDetails.NAMING.value: FileNaming.request_id.value, St...
class OptionPlotoptionsBarSonificationDefaultinstrumentoptionsMappingLowpassResonance(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 SectionStructure(Structure): def __init__(self, *argl, **argd): if ('pe' in argd): self.pe = argd['pe'] del argd['pe'] self.PointerToRawData = None self.VirtualAddress = None self.SizeOfRawData = None self.Misc_VirtualSize = None Structur...
class ConcurrencyMetricsReporter(FLMetricsReporter): ACCURACY = 'Accuracy' def __init__(self, channels: List[Channel]) -> None: self.concurrency_metrics = [] self.eval_rounds = [] super().__init__(channels) def compare_metrics(self, eval_metrics, best_metrics): print(f'Curren...
class AsciiCardCollection(): def __init__(self, *cards, hide_cards: bool=False, term: Terminal=None): self.term = term self.cards = cards self.update(hide_cards) def __str__(self): return '\n'.join(self.lines) def update(self, hide_cards: bool): if hide_cards: ...
def extractSnowTimeTranslations(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol or frag)) or ('preview' in item['title'].lower())): return None if ('In Different World With Naruto System' in item['tags']): return buildReleaseMessageWith...
class OptionPlotoptionsWaterfallSonificationContexttracksMappingFrequency(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 TestGFMEncoded(util.MdCase): extension = ['markdown.extensions.toc'] extension_configs = {'markdown.extensions.toc': {'slugify': slugs.gfm_encoded}} def test_slug(self): with pytest.warns(DeprecationWarning): self.check_markdown('# Testing GFM unicode-slugs_headers I with encoding'...
class OptionPlotoptionsAreasplineSonificationContexttracksActivewhen(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: ...
class DatabaseManager(): Query = BaseQuery def __init__(self): self._db_url = None self._base: DeclarativeMeta = self._make_declarative_base(_Model) self._engine: Optional[Engine] = None self._session: Optional[scoped_session] = None def Model(self) -> _Model: return ...
class GptsMessagesDao(BaseDao): def append(self, entity: dict): session = self.get_raw_session() message = GptsMessagesEntity(conv_id=entity.get('conv_id'), sender=entity.get('sender'), receiver=entity.get('receiver'), content=entity.get('content'), role=entity.get('role', None), model_name=entity.g...
def test_beacon_from_bytes(beacon_x86_file): data = beacon_x86_file.read() bconfig = beacon.BeaconConfig.from_bytes(data) assert len(bconfig.domains) assert bconfig.xorencoded assert (bconfig.architecture == 'x86') assert (bconfig.watermark == ) assert (bconfig.pe_export_stamp == ) asser...
_set_stats_type(ofproto.OFPMP_PORT_DESC, OFPPort) _set_msg_type(ofproto.OFPT_MULTIPART_REQUEST) class OFPPortDescStatsRequest(OFPMultipartRequest): def __init__(self, datapath, flags=0, port_no=ofproto.OFPP_ANY, type_=None): super(OFPPortDescStatsRequest, self).__init__(datapath, flags) self.port_no...
def run_optics_clustering(features, names, args): optics = OPTICS(min_samples=10).fit(features) cluster_centroids = calculate_cluster_centroids(features, optics.labels_) clusters = defaultdict(list) for (num, label) in enumerate(optics.labels_): clusters[label].append((names[num], calculate_scor...
('llama_recipes.finetuning.train') ('llama_recipes.finetuning.LlamaForCausalLM.from_pretrained') ('llama_recipes.finetuning.LlamaTokenizer.from_pretrained') ('llama_recipes.finetuning.optim.AdamW') ('llama_recipes.finetuning.StepLR') def test_unknown_dataset_error(step_lr, optimizer, tokenizer, get_model, train, mocker...
def _test_correct_response_for_recipient_location_county_without_geo_filters(client): resp = client.post('/api/v2/search/spending_by_geography', content_type='application/json', data=json.dumps({'scope': 'recipient_location', 'geo_layer': 'county', 'filters': {'time_period': [{'start_date': '2018-10-01', 'end_date'...
class StrainTest(unittest.TestCase): def test_empty_sequence(self): self.assertEqual(keep([], (lambda x: ((x % 2) == 0))), []) def test_empty_keep(self): inp = [2, 4, 6, 8, 10] out = [] self.assertEqual(keep(inp, (lambda x: ((x % 2) == 1))), out) def test_empty_discard(self):...
class DailyLink(Base): __tablename__ = 'Daily_Links' daily_id = Column(Integer, ForeignKey('Dailies.id'), primary_key=True) daily = relationship(Daily, back_populates='link_relations', primaryjoin='DailyLink.daily_id==Daily.daily_id') link_id = Column(Integer, ForeignKey('Links.id'), primary_key=True) ...
class JsMaths(): def E(self) -> JsNumber.JsNumber: return JsNumber.JsNumber('Math.E', is_py_data=False) def LN2(self): return JsNumber.JsNumber('Math.LN2', is_py_data=False) def LN10(self): return JsNumber.JsNumber('Math.LN10', is_py_data=False) def LOG2E(self): return Js...
def test_serialize_exception_without_traceback(): e: Exception = Exception() assert (e.__traceback__ is None) f: Failure = serialize_exception(e) assert isinstance(f, Failure) s = failure_to_str(f) assert isinstance(s, str) f2: Failure = str_to_failure(s) assert isinstance(f2, Failure) ...
def extractMdanmeitranslationWordpressCom(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,...
.parametrize('gridder', [KNeighbors(), KNeighbors(k=1), KNeighbors(k=2), KNeighbors(k=10), KNeighbors(k=1, reduction=np.median)], ids=['k=default', 'k=1', 'k=2', 'k=10', 'median']) def test_neighbors(gridder): region = (1000, 5000, (- 8000), (- 6000)) synth = CheckerBoard(region=region) data_coords = grid_c...
class Solution(): def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: start = 0 stk = [] for a in popped: if (stk and (stk[(- 1)] == a)): stk.pop() continue idx = pushed.index(a) if (idx < start):...
class Migration(migrations.Migration): dependencies = [('awards', '0094_delete_covidfinancialaccountmatview')] operations = [migrations.AddField(model_name='award', name='total_indirect_federal_sharing', field=models.DecimalField(blank=True, decimal_places=2, help_text='The total of the indirect_federal_sharing...
_trainer('omnimatte') class OmnimatteTrainer(Trainer): def __init__(self, img_batch_size: int, output: str, pbar_update_frequency: int=0, writer_path: Optional[str]=None, ray_batch_size: int=0, fg_batch_size_fg: int=0, fg_batch_size_bg: int=0, use_writer: bool=True, fg_indexing_strategy: (str | None)=None, num_work...
('/swagger.json') ('/allure-docker-service/swagger.json', strict_slashes=False) def swagger_json_endpoint(): try: specification_file = 'swagger.json' if ENABLE_SECURITY_LOGIN: specification_file = 'swagger_security.json' if URL_PREFIX: spec = get_file_as_string('{}/sw...
def split_run_name_full(dirname): fields = os.path.basename(dirname).split('_') if ((len(fields) > 3) and fields[0].isdigit() and ((len(fields[0]) == 6) or (len(fields[0]) == 8))): date_stamp = fields[0] else: raise IlluminaDataError(("Unable to extract date stamp from '%s'" % dirname)) ...
class TestRangeEditor(HasTraits): x = Float() low = Float(123.123) high = Float(1123.123) list = List(Float(editor=RangeEditor(low_name='low', high_name='high', low=100.0, high=10000.123))) view = View(Item(name='x', editor=RangeEditor(low_name='low', high_name='high', low=100.0, high=10000.123)), I...
def test_list_features(): method_list = list_features() assert (len(method_list) != 0) for method in method_list: assert method assert ((len(method) == 3) or (len(method) == 4)) if (len(method) == 4): assert (('face_recognition' in method[2]) or ('search' in method[2]) or...
class K8sServiceAccountTokenAuthenticator(AbstractAuthenticator): _type = SupportedAuthProviders.KUBERNETES_SERVICE_ACCOUNT_TOKEN def authenticate(self, kf_endpoint: str, runtime_config_name: str) -> ServiceAccountTokenVolumeCredentials: request_history = [] service_account_token_path = os.envir...
class GenericLedgerApiHandler(Handler): SUPPORTED_PROTOCOL = LedgerApiMessage.protocol_id def setup(self) -> None: def handle(self, message: Message) -> None: ledger_api_msg = cast(LedgerApiMessage, message) ledger_api_dialogues = cast(LedgerApiDialogues, self.context.ledger_api_dialogues) ...
class KhalEvent(CalendarEvent): def __init__(self, khal_event): self.id = khal_event.uid self.start = khal_event.start_local self.end = khal_event.end_local self.title = khal_event.summary self.recurring = khal_event.recurring self._calendar = khal_event.calendar ...
def test_minimal_integration_2d_gps(): data = fetch_california_gps() proj_coords = projection(data.longitude.values, data.latitude.values) spacing = (12 / 60) (train, test) = train_test_split(coordinates=proj_coords, data=(data.velocity_east, data.velocity_north), weights=((1 / (data.std_east ** 2)), (1...
class BaseConnector(ABC): def __init__(self, host='127.0.0.1', port=3306, user=None, passwd=None, db=None, charset='utf8', *args, **kwargs): self._host = host self._port = port self._user = user self._passwd = passwd self._db = db self._conn = None self._curso...
class MF522(): CommandReg = (1 << 1) ComIEnReg = (2 << 1) DivIEnReg = (3 << 1) ComIrqReg = (4 << 1) DivIrqReg = (5 << 1) ErrorReg = (6 << 1) Status1Reg = (7 << 1) Status2Reg = (8 << 1) FIFODataReg = (9 << 1) FIFOLevelReg = (10 << 1) WaterLevelReg = (11 << 1) ControlReg = ...
def set_status(status): global metrics for worker in status: if ('workers_state' in metrics): metrics['workers_state'].labels(worker=worker, state=status[worker]['state']).inc() else: metrics['workers_state'] = Gauge('workers_state', 'State of workers', ['worker', 'state'...
class AmountViewSet(AwardTypeMixin, FabaOutlayMixin, DisasterBase): endpoint_doc = 'usaspending_api/api_contracts/contracts/v2/disaster/award/amount.md' count_only = False _response() def post(self, request): additional_models = [{'key': 'filter|award_type', 'name': 'award_type', 'type': 'enum',...
def _compute_padding_flops(tensor: Tensor, shapes: List[IntVar], padding_idx: int) -> int: if ((shapes[padding_idx].value() % 2) == 0): return 0 if can_be_constant_folded(tensor): return 0 elif _is_strided_tensor(tensor): return ((_matrix_shape_prod(shapes) * get_padding_length(shape...
def main(args=None): import eql parser = argparse.ArgumentParser(description='Event Query Language') parser.add_argument('--version', '-V', action='version', version=('%s %s' % (eql.__name__, eql.__version__))) subparsers = parser.add_subparsers(help='Sub Command Help') build_parser = subparsers.add...
def _merge_grouper(items, group_size): FileMergeGroup = namedtuple('FileMergeGroup', ['part', 'file_list']) if (len(items) <= group_size): (yield FileMergeGroup(None, items)) return group_generator = (items[i:(i + group_size)] for i in range(0, len(items), group_size)) for (i, group) in ...
('active', cls=FandoghCommand) ('--name', '-n', 'name', prompt='Namespace name', help='Namespace name that should be default', default=None) def active(name): namespaces = list_namespaces() if (name in map((lambda n: n['name']), namespaces)): click.echo('Setting the active namespace to {}'.format(name))...
class TestS3StorageService(unittest.TestCase): LOCAL_FILE = '/usr/test_file' LOCAL_FOLDER = '/foo' S3_FILE = ' S3_FILE_COPY = ' S3_FOLDER = ' S3_FOLDER_COPY = ' S3_FILE_WITH_SUBFOLDER = ' LOCAL_DIR = [('/foo', ('bar',), ('baz',)), ('/foo/baz', (), ('a', 'b'))] S3_DIR = ['test_folder/...
def scan(pkt): global offset global scanning global queue global target_addr head = [1, 3, 6, 10] queue.append((len(pkt) - offset)) if (len(queue) > 4): queue.pop(0) if equal(queue, head): scanning = False queue.clear() target_addr = pkt.ad...
def drop_noncanonical_contigs(accessible, targets, verbose=True): (access_chroms, target_chroms) = compare_chrom_names(accessible, targets) untgt_chroms = (access_chroms - target_chroms) if any((is_canonical_contig_name(c) for c in target_chroms)): chroms_to_skip = [c for c in untgt_chroms if (not i...
class TestBuildrootOverrideMessage(): def test_tag_v1(self): expected = {'topic': 'bodhi.buildroot_override.tag', 'summary': 'lmacken submitted a buildroot override for libxcrypt-4.4.4-2.fc28', '__str__': 'lmacken submitted a buildroot override for libxcrypt-4.4.4-2.fc28', 'app_icon': ' 'app_name': 'bodhi',...
def get_input_addr_calculator(func_attrs): input_a_batch_stride_dim = 'M * K' input_a_stride_k_dim = 'K' input_a_offset = 0 input_b_batch_stride_dim = 'K * N' input_b_stride_k_dim = 'N' input_b_offset = 0 if ('input_accessors' in func_attrs): input_a_accessor = func_attrs['input_acce...
def test_scan_structure_type(thr, exclusive): shape = (100, 100) dtype = dtypes.align(numpy.dtype([('i1', numpy.uint32), ('nested', numpy.dtype([('v', numpy.uint64)])), ('i2', numpy.uint32)])) a = get_test_array(shape, dtype) a_dev = thr.to_device(a) b_ref = numpy.empty(shape, dtype) b_ref['i1']...
def extractThejourneytotheskyWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Doro Doro', 'Doro Doro Obake Ouji-sama', 'translated')] for (tagname, name, tl_typ...
class OptionSeriesLineAccessibilityPoint(Options): def dateFormat(self): return self._config_get(None) def dateFormat(self, text: str): self._config(text, js_type=False) def dateFormatter(self): return self._config_get(None) def dateFormatter(self, value: Any): self._conf...
def attrs_help(input_classes: Union[(list, tuple)], module_name: str, extract_fnc: Callable, max_indent: int) -> None: other_list = handle_help_main(input_classes, module_name, extract_fnc, max_indent) handle_help_enums(other_list=other_list, module_name=module_name, extract_fnc=extract_fnc, max_indent=max_inde...
class Procs(Module): aliases = ['ps'] def init(self): self.register_info({'author': ['paddlesteamer'], 'license': 'GPLv3'}) def run(self, **kwargs): return PhpCode('\n class UIDMap {\n private $map = array();\n\n public function __construct() {\n ...
class Terminal(object): def __init__(self, kind=None, stream=None, force_styling=False): if (stream is None): stream = sys.__stdout__ try: stream_descriptor = (stream.fileno() if (hasattr(stream, 'fileno') and callable(stream.fileno)) else None) except IOUnsupportedOp...
_user.command() _context ('--first-name', help=MODULE_OPTIONS['first_name']['help']) ('--last-name', help=MODULE_OPTIONS['last_name']['help']) ('--email', help=MODULE_OPTIONS['email']['help']) ('--login', help=MODULE_OPTIONS['login']['help']) ('--group-ids', help=MODULE_OPTIONS['group_ids']['help']) def set(ctx, **kwar...
class TestCoprActionsGeneration(CoprsTestCase): ('u1') def test_createrepo_priority(self, f_users, f_mock_chroots, f_db): self.test_client.post('/coprs/{0}/new/'.format(self.u1.name), data={'name': 'foo', 'chroots': ['fedora-rawhide-i386'], 'arches': ['i386']}) copr = CoprsLogic.get(self.u1.user...
class EasyBike(BaseSystem): sync = True unifeed = True meta = {'system': 'EasyBike', 'company': ['Brainbox Technology', 'Smoove SAS']} feed_url = ' def __init__(self, tag, meta, city_uid, bbox=None): super(EasyBike, self).__init__(tag, meta) self.feed_url = EasyBike.feed_url.format(c...
class OptionPlotoptionsVariablepieSonificationDefaultinstrumentoptionsMappingHighpassResonance(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 m...
def shuffle_queue(): now = datetime.now() conn = _get_connection() nids = conn.execute('select id from notes where priority is not NULL and priority > 0').fetchall() inserts = [((now + timedelta(days=(- random.randint(1, 365)))).strftime('%Y-%m-%d-%H-%M-%S'), nid[0]) for nid in nids] conn.executeman...
class ConnectTo(): def __init__(self, connected_interface, config: ConfigParser): self.interface = connected_interface self.config = config self.connection = None def __enter__(self): self.connection = self.interface(self.config) return self.connection def __exit__(se...
def extractNinjacrosstranslationBlogspotCom(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, nam...
def test_MeshAdaptRestart_adaptiveTime_BackwardEuler(verbose=0): currentPath = os.path.dirname(os.path.abspath(__file__)) runCommand = (('cd ' + currentPath) + '; parun -C "gen_mesh=False usePUMI=True adapt=1 fixedTimeStep=False" -D "adapt_0" dambreak_Colagrossi_so.py;') subprocess.check_call(runCommand, sh...
class OptionSeriesWordcloudSonificationTracksMappingHighpassFrequency(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 SimulationContext(): def __init__(self, ert: 'EnKFMain', sim_fs: EnsembleAccessor, mask: npt.NDArray[np.bool_], itr: int, case_data: List[Tuple[(Any, Any)]]): self._ert = ert self._mask = mask if FeatureToggling.is_enabled('scheduler'): if (ert.ert_config.queue_config.queue...
def get_mouse_target(duration: float=INFINITE, position: POSITION_T=RANDOM, width: int=50, height: int=50, brush: QtGui.QColor=QtCore.Qt.cyan, pen: QtGui.QColor=QtCore.Qt.transparent, start_at: float=BEGINNING, hover_time: float=0.0) -> typing.List[Stimulus]: position = get_position(position, (width, height)) r...
def add_metaclass(metaclass): def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if (slots is not None): if isinstance(slots, text_type): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var)...
def downgrade(): op.execute('UPDATE feed_event SET start_time = start_time * 1000, end_time = end_time * 1000, timestamp = timestamp * 1000') op.execute('UPDATE kronos_device SET discoveredAt = discoveredAt * 1000, lastPingedAt = lastPingedAt * 1000') op.execute('UPDATE kronos_device_sensors SET timestamp =...
_frequency(timedelta(days=1)) def fetch_exchange(zone_key1: str, zone_key2: str, session: Session=Session(), target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)) -> list: if (target_datetime is None): target_datetime = datetime.now().replace(tzinfo=IE_TZ) sortedZoneKeys = '->'.jo...
class ICommandStack(Interface): clean = Bool() redo_name = Str() undo_manager = Instance(IUndoManager) undo_name = Str() def begin_macro(self, name): def clear(self): def end_macro(self): def push(self, command): def redo(self, sequence_nr=0): def undo(self, sequence_nr=0):
def unpack_function(file_path, tmp_dir): with TemporaryDirectory() as staging_dir: staged_path = str((Path(staging_dir) / '{}.arj'.format(Path(file_path).name))) symlink(file_path, staged_path) output = execute_shell_command('arj x -r -y {} {}'.format(staged_path, tmp_dir), timeout=600) ...
def centralize(context, udim_tile, column, row): selection_mode = bpy.context.scene.tool_settings.uv_select_mode bm = bmesh.from_edit_mesh(bpy.context.active_object.data) uv_layers = bm.loops.layers.uv.verify() islands = utilities_uv.getSelectionIslands(bm, uv_layers, extend_selection_to_islands=True) ...
.django_db def test_basic_data_set(client, monkeypatch, helpers, defc_codes, basic_ref_data, early_gtas, basic_faba): helpers.patch_datetime_now(monkeypatch, EARLY_YEAR, EARLY_MONTH, 25) helpers.reset_dabs_cache() resp = client.get(OVERVIEW_URL) assert (resp.data == {'funding': [{'amount': EARLY_GTAS_CA...
def test_delete_oidc_provider_config(sample_tenant): client = tenant_mgt.auth_for_tenant(sample_tenant.tenant_id) provider_config = _create_oidc_provider_config(client) client.delete_oidc_provider_config(provider_config.provider_id) with pytest.raises(auth.ConfigurationNotFoundError): client.get...
class Module(): def __init__(self, template_src, render_kwds=None): self.template = template_from(template_src) self.render_kwds = ({} if (render_kwds is None) else dict(render_kwds)) def create(cls, func_or_str, render_kwds=None): (signature, code) = extract_signature_and_value(func_or_...
class bsn_virtual_port_remove_request(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 17 def __init__(self, xid=None, vport_no=None): if (xid != None): self.xid = xid else: self.xid = None if (vport_no != None): self.vpor...
def ddram_io(): return [('ddram_sstl15', 0, Subsignal('a', Pins('R2 M6 N4 T1 N6 R7 V6 U7', 'R8 V7 R6 U6 T6 T8'), IOStandard('SSTL15')), Subsignal('ba', Pins('R1 P4 P2'), IOStandard('SSTL15')), Subsignal('ras_n', Pins('P3'), IOStandard('SSTL15')), Subsignal('cas_n', Pins('M4'), IOStandard('SSTL15')), Subsignal('we_n...
def query_from_string(s, input_variables=None, is_async=True, output_writer=None, **extra_args): if (input_variables is None): input_variables = [] import inspect temp_lmql_file = tempfile.mktemp(suffix='.lmql') with open(temp_lmql_file, 'w', encoding='utf-8') as f: f.write(s) module...
class CommonNotification(models.Model): notificationId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) notificationType = models.CharField(max_length=255, choices=NotificationType) eventTime = models.DateTimeField(auto_now=True) systemDN = models.CharField(max_length=255, null=Tr...