content
stringlengths
22
815k
id
int64
0
4.91M
def pytest_configure(config): """ Adds jsonpath to pytest config and additional markers to pytest ini. """ jsonpath = config.option.jsonpath if jsonpath: config.json = JiraJsonReport(jsonpath) config.pluginmanager.register(config.json) # register an additional marker config.a...
51,400
def assert_http_ok(resp, msg=None): """ Ensures the response is returning a HTTP 200. """ return assert_equal(resp.status_code, 200, resp.content if msg is None else msg)
51,401
def segnet_vgg13_bn(pretrained=False, progress=True, **kwargs): """Constructs a DeepLabV3+ model with a mobilenet backbone. """ model = SegNet(arch='segnet_vgg13_bn', **kwargs) if pretrained: state_dict = load_state_dict_from_url(model_urls['segnet_vgg13_bn'], progress=progress) model.lo...
51,402
def New_Dataframe(old_df,indicator_name): """ create a new dataframe that is composed of only one indicator Args: old_df (dataframe): general dataframe from which we extract the new one indicator_name (string): Name onf the indicator that will composed the new dataframe Re...
51,403
def get_long_description(): """Compose a long description for PyPI.""" long_description = None try: long_description = read_file('README.rst').decode('utf-8') changelog = read_file('CHANGES.rst').decode('utf-8') changelog = "\n".join(first_sections(changelog, '=', 4)) + """ Older ver...
51,404
def _create_matcher(utterance): """Create a regex that matches the utterance.""" # Split utterance into parts that are type: NORMAL, GROUP or OPTIONAL # Pattern matches (GROUP|OPTIONAL): Change light to [the color] {item} parts = re.split(r'({\w+}|\[[\w\s]+\] *)', utterance) # Pattern to extract nam...
51,405
def change_video_state(player_name, state): """ :param player_name: video_player or topic_player or live or vr_live or pic_player or local_player :param state: play or pause :return: """ response = context.agent.call('ChangeVideoState', player_name, state) if response.name == 'Fail': ...
51,406
def generate(converter, input_file, format='xml', encoding='utf8'): """ Given a converter (as returned by compile()), this function reads the given input file and converts it to the requested output format. Supported output formats are 'xml', 'yaml', 'json', or 'none'. :type converter: compiler.C...
51,407
def compute_SS_TAS(df, cpds_median_score, num_L1000_feats = n_L1000_feats): """ Computes both Transcriptional activity score (TAS) and signature strength per compound based on its replicates across all doses""" dose_list = list(set(df['dose'].unique().tolist()))[1:7] for dose in dose_list...
51,408
def main(): """ Main method to launch ARIIA """ ariia = Ariia() try: while True: ariia.interaction() except KeyboardInterrupt: print "exiting..." ariia.cleanStop()
51,409
def check_args(args): """ Checks validity of command line arguments and, in some cases modifies them a little bit. :param args: The command-line arguments. :type args: argparse.ArgumentParser Namespace :returns: argparse.ArgumentParser Namespace -- The updated command-line argumen...
51,410
def test_family_notes(family): """Test getting family notes""" bse.has_family_notes(family) bse.get_family_notes(family)
51,411
def GetIncludeGuardSymbol(file_name): """Returns include guard symbol for .h file. For example, returns 'SOME_EXAMPLE_H' for '/path/to/some_example.h' Args: file_name: a string indicating output file path. Returns: A string for include guard. """ return os.path.basename(file_name).upper().replace(...
51,412
def invalidate_entity_before_delete(sender, instance, **kwargs): """ RUS: Очищает буфер template_buffer после сохранения шаблонных тегов. """ invalidate_entity_after_save(sender, instance, **kwargs)
51,413
def build_contrastive_dataframe(df, save_location, num_samples, sample_fn, seed=None): """Builds a contrastive dataframe from scratch. Given a universe of examples and a rule for how to c...
51,414
def _get_ormclass_from_cls(cls: EntityClsType) -> Tuple[EntityTypes, Classifier]: """ Return the correct classifiers for the QueryBuilder from an ORM class. :param cls: an AiiDA ORM class or backend ORM class. :param query: an instance of the appropriate QueryBuilder backend. :returns: the ORM clas...
51,415
def norm_diff(a): """Calculate average of (a[i] - a[i+1]) / (a[i] + a[i+1]).""" if len(a) <= 1: return np.nan a = a.astype(float) if np.allclose((a[1:] + a[:-1]), 0.): return 0. norm_diffs = (a[1:] - a[:-1]) / (a[1:] + a[:-1]) norm_diffs[(a[1:] == 0) & (a[:-1] == 0)] = 0. w...
51,416
def expand_batch_dims(structure, batch_sizes): """Expands the first dimension of each tensor in structure to be batch_sizes. Args: structure: A structure (tuple, namedtuple, list, dictionary, ...). batch_sizes: A 1-D tensor of shapes describing the batch dims. Returns: A structure matching the input ...
51,417
def test_domain_negative_observable_does_not_exist(relay_api): """Perform testing for relay observe/observables. Make attempt to get observable which doesn't exist in Graph Security ID: CCTRI-354-432f0e0a-4806-4fda-906f-2d21e2015eee Steps: 1. Send request with domain type to endpoint observe o...
51,418
def VLBAAIPSName( project, session): """ Derive AIPS Name. AIPS file name will be project+session with project truncated to fit in 12 characters. * project = project name * session = session code """ ################################################################ Aname = Aname=projec...
51,419
def test_unbalanced_logging_with_multiple_optimizers(tmpdir): """This tests ensures reduction works in unbalanced logging settings.""" class TestModel(MultiOptModel): actual = {0: [], 1: []} def training_step(self, batch, batch_idx, optimizer_idx): out = super().training_step(batc...
51,420
def write_model_inputs( scenario_directory, scenario_id, subscenarios, subproblem, stage, conn ): """ Get inputs from database and write out the model input projects.tab file (to be precise, amend it). :param scenario_directory: string, the scenario directory :param subscenarios: SubScenarios ob...
51,421
def dot_general(lhs: Array, rhs: Array, dimension_numbers: DotDimensionNumbers, precision: PrecisionLike = None, preferred_element_type: Optional[DType] = None) -> Array: """More general contraction operator. Wraps XLA's `DotGeneral <https://www.tensorflow.org/xla/operation_semant...
51,422
async def post_requests(session, request_map, concurrent_requests=0): """ Parameters ---------- session: aiohttp.ClientSession dict: url -> request """ requests = [] for i, (url, request) in enumerate(request_map.items()): requests.append(asyncio.create_task(post_request(session,...
51,423
def get_system(ctx, system_id): """ Detail view of system. """ api1 = JumpcloudApiV1(ctx.obj.get('key')) response = api1.get_system(system_id=system_id) serialized_response = json.dumps(response, indent=2) click.echo(f"{serialized_response}")
51,424
def setBase24Theme( theme: str | list[str], darkTheme: str | list[str], pySimpleGui: Any, ) -> None: """Set the base24 theme to the application. Args: theme (Union[str, list[str]]): the light theme darkTheme (Union[str, list[str]]): the dark theme pySimpleGui (Any): pysimplegui module """ # Light theme t...
51,425
def test_utility_load(): """Test for label studio json loader.""" data = [ { "id": 191, "annotations": [ { "id": 130, "completed_by": {"id": 1, "email": "test@heartex.com", "first_name": "", "last_name": ""}, ...
51,426
def random(n: int, area: Tuple[float, float]): """ Generate random lines. By default, 10 lines are randomly placed in a square with corners at (0, 0) and (10mm, 10mm). Use the `--area` option to specify the destination area. """ lines = np.random.rand(n, 2) + 1j * np.random.rand(n, 2) line...
51,427
def check_path_in_dir(file_path, directory_path): """ Check if a file path is in a directory :param file_path: Full path to a file :param directory_path: Full path to a directory the file may be in :return: True if the file is in the directory """ directory = Path(directory_path) parent ...
51,428
def trace_eyes(im, wnd_pos, wnd_dim, threshold, image_scale, filter_size, color_invert): """ Parameters ---------- im : image (numpy array); win_pos : position of the window on the eyes (x, y); win_dim : dimension of the window on the eyes (w, h); threshold : ...
51,429
def get() -> DslContextRegistry: """Gets the current active registry that observes DSL definitions.""" return _registry_holder.current
51,430
def scalebar(length,slon='auto',slat='auto',az=90,label=True,ax=None,**kwargs): """ Plot scalebar of given length in meters. Parameters: length: Length of scalebar in meters slon: Starting longitude (decimal degrees) for scalebar slat: Starting latitude (decimal degrees) for sca...
51,431
def to_str(bytes_or_str): """ Return Instance of str """ if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode('utf-8') else: value = bytes_or_str return value
51,432
def fulfill_order_line(order_line, quantity): """Fulfill order line with given quantity.""" if order_line.variant and order_line.variant.track_inventory: decrease_stock(order_line.variant, quantity) order_line.quantity_fulfilled += quantity order_line.save(update_fields=["quantity_fulfilled"])
51,433
def flat_out(f, *a, **kw): """Flatten the output of target function.""" return f(*a, **kw).flatten()
51,434
def delete_question(id): """ Delete question. """ question = Question.query.get(id) if question is not None: question.delete() response = {"message": "Object deleted."} return make_response(jsonify(response), 200) abort(404)
51,435
def vgg16_cinic10_bn(pretrained=False, progress=True, **kwargs): """ VGG 16-layer model (configuration "D") with batch normalization Inspired by: https://github.com/geifmany/cifar-vgg/blob/master/cifar100vgg.py to follow https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=7486599 and then gave up on Dr...
51,436
def _parser(): """Take care of all the argparse stuff. :returns: the args """ parser = argparse.ArgumentParser( description='Interactively normalize fits spectra.') parser.add_argument("fitsname", type=str, help="Specturm to continuum normalize.") parser.add_ar...
51,437
async def f_fort_ws(): """ Yield fixture returns fort sheet. """ agcm = cog.sheets.init_agcm(PATHS['service_json']) cog.sheets.AGCM = agcm await agcm.authorize() sheet = cog.util.CONF.tests.hudson_cattle asheet = cog.sheets.AsyncGSheet(sheet['id'], sheet['page']) await asheet.init_s...
51,438
def create_app(config_name): """ 初始化Flask的应用对象,并初始化数据库等内容 :param config_name: str 配置模式的模式的名字 ("develop", "product") :return: """ # 创建app app = Flask(__name__) @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') i...
51,439
def test_spam_check(): """For now we are just testing our route to the Akismet API and whether we store submitted comments as spam or not. Later expand this into multiple tests to support multiple spam checking engines. Devs who want to run this test *must* add to their *test* settings: AKISMET_KEY = '...
51,440
def test_open_with_stdin_password(getpass: Mock, class_mock: Mock) -> None: """Test open door.""" api = MagicMock(spec=GogoGate2Api) class_mock.return_value = api api.open_door.return_value = True getpass.return_value = "my_password" runner = CliRunner() result = runner.invoke( cli...
51,441
def add_vote_and_redirect(event, _): """ Handle add vote requests and redirect to a info page :param event: event :return: redirect to a page explaining that the vote was added """ # Save the vote do_vote(event, None) redirect_url = "/voted" # Find the user and determine the redire...
51,442
def read_json_vectors(filename): """Return np array of vectors from json sources""" vectors = [] with open(filename) as json_file: json_data = json.load(json_file) for v in json_data: vectors.append(v) print("Read {} vectors from {}".format(len(vectors), filename)) np_array = np....
51,443
def optimize_density_and_bkg_scaling(data_pattern, bkg_pattern, composition, initial_density, initial_bkg_scaling, r_cutoff, iterations=2, use_modification_fcn=False): """ This function tries to find the optimum density in background scal...
51,444
def get_error_hint(ctx, opts, exc): """Get a hint to show to the user (if any).""" module = sys.modules[__name__] get_specific_error_hint = ( getattr(module, 'get_%s_error_hint' % exc.status, None)) if get_specific_error_hint: return get_specific_error_hint(ctx, opts, exc) return Non...
51,445
def detail(root, name, my, request, actie="", msg=""): """bouw het scherm met actiegegevens op. de soort user wordt meegegeven aan het scherm om indien nodig wijzigen onmogelijk te maken en diverse knoppen te verbergen. """ ## msg = request.GET.get("msg", "") if not msg: if request.u...
51,446
def define_areas( pixel_filtered_map: np.ndarray, district_heating_zone_threshold: float ): """ This function defines areas where the sum of the pixel values for a given area exceeds a certain threshold. Inputs : * pixel_filtered_map : pixel filtered map (MWh). * district_heating_zo...
51,447
def test_estimate_individual_ll(data): """ Tests whether participant-specific parameters are estimated correctly. """ params = start_params(spec=3) expected = np.array([0.809, 0.832, 1.063, 1.431, 53.219, 391.648]) actual = np.round(estimate_individual_ll(3, data, 3, params), 3) assert_almos...
51,448
def get_relation(filename): """read relation file, return rel2idx""" rel2idx = {} f = open(filename, 'r') lines = f.readlines() for (n, rel) in enumerate(lines): rel = rel.strip().lower() rel2idx[rel] = n f.close() return rel2idx
51,449
def eprint(*arg, **kwargs): """stdderr print wrapper""" print(*arg, file=sys.stderr, flush=True, **kwargs)
51,450
def id_for_base(val): """Return an id for a param set.""" if val is None: return "No base params" if "editor-command" in val: return "Long base params" if "ecmd" in val: return "Short base params" return "Unknown base params"
51,451
def __bilinear(lat, lon, table): """Return bilinear interpolated data from table""" try: lat = float(lat) lon = float(lon) except ValueError: return '' if _non_finite(lat) or _non_finite(lon): return '' if math.fabs(lat) > 90 or math.fabs(lon) > 180: return ...
51,452
def isNumber(s): """ 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100"、 "5e2"、"-123"、"3.1416"、"0123"及"-1E-16"都表示数值,但"12e"、"1a3.14"、"1.2.3"、"+-5" 及"12e+5.4"都不是 :param s: :return: """ s = s.strip() s = s.lower() flag = False for i in s: pass
51,453
def serialize_serializable(obj, spec, ctx): """ Serialize any class that defines a ``serialize`` method. """ return obj.serafin_serialize(spec, ctx)
51,454
def test_to_table(example_subarray): """ Check that we can generate astropy Tables from the SubarrayDescription """ sub = example_subarray assert len(sub.to_table(kind="subarray")) == sub.num_tels assert len(sub.to_table(kind="optics")) == len(sub.optics_types)
51,455
def train_baseline(train_loader, model, criterion, optimizer, epoch): """ :param train_loader: data loader with training images :param model: model used for training :param criterion: loss function :param optimizer: optimizer :param epoch: current training epoch :return: baseline training sc...
51,456
def best_match(supported, header): """Return mime-type with the highest quality ('q') from list of candidates. Takes a list of supported mime-types and finds the best match for all the media-ranges listed in header. The value of header must be a string that conforms to the format of the HTTP Accept: he...
51,457
def hourly_median(hours, series, all_hours=True): """ Calculate hourly binned medians of a time series. Parameters ---------- hours : array_like Time series of the hour number. Must be of the same length as `series`. series : array_like Time series of the data. all_hours : b...
51,458
def test_payment_put(session, client, jwt, app): """Assert that the endpoint returns 200.""" token = jwt.create_jwt(get_claims(), token_header) headers = {'Authorization': f'Bearer {token}', 'content-type': 'application/json'} rv = client.post(f'/api/v1/payment-requests', data=json.dumps(get_payment_re...
51,459
def connect(): """Connect to a MySQL database""" try: # Connect to the database connection = mysql.connector.connect( database=os.environ['MYSQL_DBNAME'], host=os.environ['MYSQL_HOST'], user=os.environ['MYSQL_USER'], password=os.environ['MYSQL_PAS...
51,460
def is_orthonormal_direct(basis): """ Returns True if the basis is orthonormal and direct: Parameters ---------- basis Returns ------- """ return is_orthonormal(basis) and np.allclose( np.cross(basis[0, :], basis[1, :]), basis[2, :] )
51,461
def matlab_style_gauss2D(shape=(3, 3), sigma=0.5): """ 2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma]) Acknowledgement : https://stackoverflow.com/questions/17190649/how-to-obtain-a-gaussian-filter-in-python (Author@ali_m) """ m, n = [(ss - 1.) / 2. fo...
51,462
def triangle2str(idx, triangle): """ converts a triangle to a string """ return f"shapes[{idx}] = makeShape(" + \ f"materials[{triangle['matid']}]," + \ f"makeTriangle({vec32str(triangle['a'])}," + \ f"{vec32str(triangle['b'])}," + \ f"{vec32str(triangle['c'])}));"
51,463
def cmd(version, require_canonical): """Ensure a version is a valid PEP 440 version.""" try: parsed_version = Version(version) except InvalidVersion: click.echo(f"{version!r} is not a valid PEP 440 version.", err=True) sys.exit(1) if require_canonical: canonical_version ...
51,464
def test_http_request_when_valid_response_is_returned(mocker, requests_mock, client): """Test case scenario for successful execution of http_request function""" from CofenseTriagev3 import URL_SUFFIX mocker.patch('CofenseTriagev3.Client.get_api_token', new=lambda x: False) mocker.patch('CofenseTriagev3...
51,465
def get_hosts_from_yaml(test_yaml, args, key_match=None): """Extract the list of hosts from the test yaml file. This host will be included in the list if no clients are explicitly called out in the test's yaml file. Args: test_yaml (str): test yaml file args (argparse.Namespace): comma...
51,466
def parse_labels_mapping(s): """ Parse the mapping between a label type and it's feature map. For instance: '0;1;2;3' -> [0, 1, 2, 3] '0+2;3' -> [0, None, 0, 1] '3;0+2;1' -> [1, 2, 1, 0] """ if len(s) > 0: split = [[int(y) for y in x.split('+')] for x in s.split(';')] e...
51,467
def test_get_breeds_random_images( api_client, get_expected_response, get_image_info, actual_images_count, expected_images_count, ): """ Display multiple random images from all dogs collection. """ r = api_client.get(path=f"/breeds/image/random/{actual_images_count}") actual_res...
51,468
def sraa_eedi3(clip: vs.VideoNode, rep: Optional[int] = None, **eedi3_args: Any)-> vs.VideoNode: """Drop half the field with eedi3+nnedi3 and interpolate them. Args: clip (vs.VideoNode): Source clip. rep (Optional[int], optional): Repair mode. Defaults to None. Returns: vs.VideoNod...
51,469
async def test_async_comp_month(aresponses, client: Efergy) -> None: """Test getting comparison data.""" aresponses.add( "engage.efergy.com", "/mobile_proxy/getCompMonth?token=ur1234567-0abc12de3f456gh7ij89k012&offset=300", "GET", aresponses.Response( status=200, ...
51,470
def _is_nested(x: Any) -> bool: """Returns whether a value is nested.""" return isinstance(x, dict) or dataclasses.is_dataclass(x)
51,471
def pedel(lsize, seq_len, mps, dist_fx=poisson): """ Pedel calculates library diversity given library size and mutational load. For poisson distribution use poisson (default). For pcr distribution, use first pcr_distribution_factory(efficiency, cycles) to obtain a function specific to those parameters. ...
51,472
def contains_pept(name): """Checks if the saccharide name contains the peptide fragment, such as EES, GS, SA etc""" contains_pept = False for pept_stub_name in ('_E', '_G', '_S', '_A'): if (pept_stub_name in name) and ('_NRE' not in name): contains_pept = True return contains...
51,473
def check_stacked_complex(data: torch.Tensor) -> torch.Tensor: """ Check if tensor is stacked complex (real & imag parts stacked along last dim) and convert it to a combined complex tensor. Args: data: A complex valued tensor, where the size of the final dimension might be 2. Returns: ...
51,474
def circle(x, y, a, b, width): """ widthで指定された直径の中に含まれているかを判定 :param x: :param y: :param a: :param b: :param width: :return: """ _x = round(((x - a) ** 2), 3) _y = round(((y - b) ** 2), 3) _r = round(((width/2) ** 2), 3) if (_x + _y) <= _r: return _r - (_x + _...
51,475
def fetch_representative_points( service_area_ids, include_census_data, engine=connect.create_db_engine() ): """ Fetch representative points for a list of service areas. Prepares responses for use by the frontend. """ if not service_area_ids: return [] query_params = { ...
51,476
def test_request_success(requests_mock): """ Testing sucessful HTTP Request """ test_body = {"test" : "test"} requests_mock.post(f'{ORCHESTRATOR}/portal/rest/test', json=test_body ) client = VcoClient(orchestrator_url=ORCHESTRATOR, api_key=APIKEY) ...
51,477
def get_most_similar(candidates, target_val, endpointService): """ select the entity from candidates that are most similar to the original one ties are broken by overall popularity """ closest_dist = float('inf') closest_matches = [] target_val = target_val.lower() for cand in candidat...
51,478
def dict_remove_none(starting_seq=None, extend_chained=True, chained=None, chained_status=None): """ Given a target sequence, look for dictionary keys that have values of None and remove them. By default, ``chained`` will have ``.extend()`` or ``.update()`` called on it with ``starting_seq`` as the onl...
51,479
def get_scoped_token(os_auth_url, access_token, project_id): """ Get a scoped token, will try all protocols if needed """ unscoped_token, protocol = get_unscoped_token(os_auth_url, access_token) url = get_keystone_url(os_auth_url, "/v3/auth/tokens") body = { "auth": { "identi...
51,480
def catch_error(method): """Decorator to catch and handle errors on handlers""" @wraps(method) def wrapper(self, *args, **kwargs): try: return method(self, *args, **kwargs) except Exception as e: self.statsd.incr(self.__class__.__name__+'.error') logger.wa...
51,481
def scenario_generator(nodes, twins, n_partitions, max_rounds, partition_limit, partition_leader_limit, max_testcases, seed, is_Faulty_Leader, is_Deterministic, file_path): """ Example : 1,2,3,4 => Non-faulty 5 => Faulty """ random.seed(seed) total_nodes = nodes +...
51,482
def create_tenant_users(no_of_users_to_create, tenant_name, cluster_name="ceph"): """ This function is to create n users with tenant on the cluster Parameters: no_of_users_to_create(int): users to create with tenant cluster_name(char): Name of the ceph cluster. defaults to 'ceph' Retur...
51,483
def get_data(args, opts, train=True, async_dataloader=False, return_remaining=False, fine_tuning=False): """ A factory method to create a dataload responsible for sending data to the IPU device. This build the appropriate dataset and wraps it in a dataloader. """ logging.info("Loading the data") ...
51,484
def split_feature_class(label: str, frame: pd.DataFrame): """ Split features and class from encode dataset. `label` is the class, and `frame` is the dataset which has been encoded. """ sub_cols = [attr for attr in frame.columns if attr.startswith(label)] if len(sub_cols) <= 1: return frame, ...
51,485
def user_form_test(): # <dev> """recommender user form. Returns: request: dictionary (json object) list of user's strain description schema: {"type_list": [""], "effect_list": [""], "flavor_list": [""]} """ return render_template("index.h...
51,486
def set_user_script(scriptID: int, script: ScriptModel, username: str = Depends(decode_token)): """ :param scriptID: The id of the script :type scriptID: int :param script: The object containing the script content and information :type script: ScriptModel ...
51,487
async def voice_connect(member, channel): """Informe d'une connexion à un salon vocal Discord dans Minecraft Args: member (discord.Member): le membre qui a rejoint le salon channel (discord.VoiceChannel): le salon rejoint Utilise ``/tellraw`` pour afficher du texte coloré et cliquable. ...
51,488
def bestfit_sphere_numpy(points): """Returns the sphere's center and radius that fits best through a set of points. Parameters ---------- points: list of points XYZ coordinates of the points. Returns ------- tuple: center, radius sphere center (XYZ coordinates) and sphere r...
51,489
def absupearson(a,b,weights): """Distance between two points based on the pearson correlation coefficient. By treating each data point as half of a list of ordered pairs it is possible to caluclate the pearson correlation coefficent for the list. The correlation coefficent is then converted into ...
51,490
def plot_met(data_df: pd.DataFrame, data_interp_df: pd.DataFrame, met_selection: list, scaled_conc: bool = False, x_scale: str = 'linear', y_scale: str = 'linear', x_lim: tuple = (10 ** -10, 1), y_lim: tuple = None): """ Plots a given metabolite across all models in altair. Uses line plots. Ar...
51,491
def get_data_files(): """Return data_files in a platform dependent manner""" if sys.platform.startswith('linux'): data_files = [('/usr/share/icons/hicolor/scalable/apps', ['icons/pysigview.svg']), ('/usr/share/applications', ['scripts/p...
51,492
def test_cpu_vulns_spectre_v2_exp1(): """ Here test the examples cause expections """ with pytest.raises(SkipException) as sc1: CpuVulns(context_wrap('')) assert "Input content is empty" in str(sc1)
51,493
def get_page(db: Session, name: str) -> models.Page: """ Get the page with the given name. :param db: The db session to check. :param name: The name of the page to find. :return: The desired page in the db, or None if DNE. """ return db.query(models.Page).filter(models.Page.name == name).fir...
51,494
def get_spider_queues(config): """Return a dict of Spider Queues keyed by project name""" dbsdir = config.get('dbs_dir', 'dbs') if not os.path.exists(dbsdir): os.makedirs(dbsdir) d = {} for project in get_project_list(config): dbpath = os.path.join(dbsdir, '%s.db' % project) ...
51,495
def test_public_umash_fprint(seed, multipliers, key, data): """Compare umash_fprint with two calls to the reference.""" expected = [ umash(UmashKey(poly=multipliers[0], oh=key), seed, data, secondary=False), umash(UmashKey(poly=multipliers[1], oh=key), seed, data, secondary=True), ] n_by...
51,496
def _dbms_utility_name_resolve( connection: oracle.Connection, name: str, context: int ) -> Tuple[str, str, str, str, int, int]: """Wrapper for Oracle DBMS_UTILITY.NAME_RESOLVE procedure""" with connection.cursor() as cursor: schema = cursor.var(str) part1 = cursor.var(str) part2 = c...
51,497
def func_call(instance: ARIA, func_name: str, command_name: str, demisto_arguments: list, args: dict): """ Helper function used to call different demisto command Args: instance: An ARIA instance. func_name: Name of the functions in the ARIA class. command_name: Related demisto command n...
51,498
def shutdown_session(exception=None): """ The last operation performed when the Sever shutdown """ db.session.remove() # TODO: send mail while application shutdown
51,499