content
stringlengths
22
815k
id
int64
0
4.91M
def _guess_filetype(filename): """Return a (filetype, encoding) tuple for a file.""" mimetypes.init() filetype = mimetypes.guess_type(filename) if not filetype[0]: textchars = bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray( range(0x20, 0x100)) with open(filename) as fd: ...
49,600
def inline_anchor_check(stripped_file): """Check if the in-line anchor directly follows the level 1 heading.""" if re.findall(Regex.INLINE_ANCHOR, stripped_file): return True
49,601
def test_pushing_different_many_values_to_priorities_add_to_queue(empty_queue): """Test that a pushing values to diff priorities adds all values.""" q = empty_queue q.push('a', 1) q.push('b', 2) q.push('c', 1) assert q.values == {1: ['a', 'c'], 2: ['b']}
49,602
def u_inverse(U, check=False, verbose=False): """invert a row reduced U """ m, n = U.shape #items = [] leading = [] for row in range(m): cols = numpy.where(U[row, :])[0] if not len(cols): break col = cols[0] leading.append(col) U1 = zeros2(n, m)...
49,603
def test_delete(client, indexd, entities): """ Test deleting a participant by id """ init = GenomicFile.query.count() r = _new_genomic_file(client) kf_id = r['results']['kf_id'] response = client.delete(url_for(GENOMICFILE_URL, kf_id=kf_id), ...
49,604
def highlight_symbol_in_DISASM(): """ Select a symbol in the DECOMP view, highlight the corresponding symbols in IDA DISASM view. """ # print("GhIDA:: [DEBUG] highlight_symbol_in_DISASM called") disasm_widget = idaapi.find_widget('IDA View-A') symbol = get_highlighted_identifier() if not...
49,605
def get_filters(component): """ Get the set of filters for the given datasource. Filters added to a ``RegistryPoint`` will be applied to all datasources that implement it. Filters added to a datasource implementation apply only to that implementation. For example, a filter added to ``Specs.ps_...
49,606
def parse_traffic_congestion(traffic): """Return parsed traffic congestion by regions.""" regions_distances = collections.defaultdict(list) regions_polygons = parse_regions_bounds() for route in traffic: trip_distance = route["trip_distance"] point = Point((route["trip_latitude"], route[...
49,607
def make_doc(f): """ Main routine for generating documentation. """ global h5gate_file # save in global variable for Id_doc routines (so do not have to pass it as parameter) h5gate_file = f doc_parts = { 'header': [], 'toc': [], # table of contents 'main': [], # main docu...
49,608
def batch_mean_metric_torch( base_metric: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], predictions: torch.Tensor, ground_truth: torch.Tensor, ) -> torch.Tensor: """During training, we may wish to produce a single prediction for each prediction request (i.e., just sample once from the ...
49,609
def produce_final_output(audio_file_name, video_file_name, final_video_file): """Merges video with audio""" subprocess.call(['ffmpeg', '-i', video_file_name, '-i', audio_file_name, '-shortest', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '128k', '-y', final_video_file])
49,610
def aggregate_tree(l_tree): """Walk a py-radix tree and aggregate it. Arguments l_tree -- radix.Radix() object """ def _aggregate_phase1(tree): # phase1 removes any supplied prefixes which are superfluous because # they are already included in another supplied prefix. For example, ...
49,611
def is_dag_acyclic(root_vertex): """Perform an acyclicity check for a given DAG. Returns: True -- If the DAG contains cycles. False -- If the DAG does not contain cycles. """ visited = set() for vertex in topological_traverse(root_vertex): if vertex in visited: # DAG ha...
49,612
def test_storage_close(storage: MemoryStorage): """ Тест закрытия стораджа :param storage: :return: """ storage.close() assert storage._data == {}
49,613
def nextPow2(length): """ Find next power of 2 <= length """ return int(2**np.ceil(np.log2(length)))
49,614
def convert_parameter_to_model_parameter(parameter, value, meta=None): """Convert a Cosmology Parameter to a Model Parameter. Parameters ---------- parameter : `astropy.cosmology.parameter.Parameter` value : Any meta : dict or None, optional Information from the Cosmology's metadata. ...
49,615
def check_decoder_output(decoder_output): """we expect output from a decoder is a tuple with the following constraint: - the first element is a torch.Tensor - the second element can be anything (reserved for future use) """ if not isinstance(decoder_output, tuple): msg = "FariseqDecode...
49,616
def _write_segmented_read( model, read, segments, do_simple_splitting, delimiters, bam_out ): """Split and write out the segments of each read to the given bam output file. NOTE: Assumes that all given data are in the forward direction. :param model: The model to use for the array segment information....
49,617
def lambda_handler(event: GetRecordsOutputTypeDef, _context): """ # How do entity counts work in HMA? Without blocking ddb edits. So we do it as a stream processor. Lambda ddb_stream_counter will do the following: a) listen to stream updates to all configured datastores b) determine if the upda...
49,618
def sphinx(**kwargs): """ Run sphinx """ prog = _shell.frompath('sphinx-build') if prog is None: _term.red("sphinx-build not found") return False env = dict(_os.environ) argv = [ prog, '-a', '-d', _os.path.join(kwargs['build'], 'doctrees'), '-b', 'html', ...
49,619
def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response(l...
49,620
def generate_all_overhangs(overhang_length=4): """Generate list Overhang class instances for all overhangs of given length. **Parameters** **overhang_length** > Length of overhangs (`int`). """ overhang_pairs = generate_overhang_pairs(overhang_length=overhang_length) overhang_strings = [n...
49,621
def save_dict(data, out_path): """Dumps a pickleable object to disk. Args: data (:obj:`dict`): A dictionary (containing pickleable values only). out_path (:obj:`str`): Path to the destination file. Returns: None """ with open(out_path, 'wb') as fh: pickle.dump(data,...
49,622
def main(): """ This function loads, cleans and saves data to a database Parameters: messages_filepath is the file with the messages categories_filepath is the file with the categories database_filepath is the name of the output database Return: None """ ...
49,623
def test_figure_opengraph(meta_tags: List[element.Tag]): """Test.""" og_image = [t for t in meta_tags if t.get("property", "") == "og:image"][0] assert og_image.get("content") == "https://i.imgur.com/611EovQh.jpg" og_image_alt = [t for t in meta_tags if t.get("property", "") == "og:image:alt"][0] as...
49,624
def sqrt(x: float) -> float: """ Return the square root of ``x``. """ ...
49,625
def csv_to_list(filename: str) -> list: """Receive an csv filename and returns rows of file with an list""" with open(filename) as csv_file: reader = csv.DictReader(csv_file) csv_data = [line for line in reader] return csv_data
49,626
def extract_link_from_set_cookie_header(http_response, header_name, header_value): """ Extract links from the "path" key of a cookie Example headers we can parse: set-cookie: __cfduid=...; path=/; domain=.w3af.org; HttpOnly :param http_response: The http response object :param header_name:...
49,627
def create_rlimits(): """ Create a list of resource limits for our jailed processes. """ rlimits = [] # No subprocesses. rlimits.append((resource.RLIMIT_NPROC, (0, 0))) # CPU seconds, not wall clock time. cpu = LIMITS["CPU"] if cpu: # Set the soft limit and the hard limit...
49,628
def run_script(module_path, function_name='main', *args, **kwargs): """ Run an arbitrary function, e.g. fab run_script:module.name,func_name,arg1,arg2 """ from django.utils.module_loading import import_string func = import_string("%s.%s" % (module_path, function_name)) func(*args, **kwargs)
49,629
def sqrt(x): """ Calculate the square root of argument x. """ #initial gues for square root z = x/2.0 #Continuously improve the guess #Adadapted from https://tour.golang.org/flowcontrol/8 while abs(x - (z*z)) > 0.0001: z = z-(z*z - x) / (2*z) return z
49,630
def create_french_dict_from(file_path): """Transform a text file containing (weight, word) tuples into python dictionnary.""" with open(file_path, 'r', encoding="ISO-8859-1") as file: lines = file.readlines() french_dict = {} for line in lines: couple = line.strip().replace('\n', '').sp...
49,631
def construct(data_dir, fname, Y=None, normalize=False, _type='sparse'): """Construct label class based on given parameters Arguments ---------- data_dir: str data directory fname: str load data from this file Y: csr_matrix or None, optional, default=None data is already ...
49,632
def test_NN_MUL_REDC1(op): """ Generate tests for NN_MUL_REDC1 """ # Odd modulus nn_mod = get_random_bigint(wlen, MAX_INPUT_PARAM_WLEN) | 1 nn_r, nn_r_square, mpinv = compute_monty_coef(nn_mod, getwlenbitlen(nn_mod, wlen)) # random value for input numbers modulo our random mod nn_in1 = get_rand...
49,633
def GetAzureStorageConnectionString(storage_account_name, resource_group_args): """Get connection string.""" stdout, _ = vm_util.IssueRetryableCommand( [AZURE_PATH, 'storage', 'account', 'show-connection-string', '--name', storage_account_name] + resource_group_args + AZURE_SUFFIX) response = json.lo...
49,634
def clean_data(answers, dupes, min_dupes, min_text, questions, show_output): """ :param answers: :param dupes: :param min_dupes: :param min_text: :param questions: :param show_output: :return: """ for dataframe in (questions, dupes, answers): dataframe["Text"] = datafram...
49,635
def on_intent(intent_request, session): """ Called when the user specifies an intent for this skill """ print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent_name = intent_request['intent']['name'] print(intent_request['intent']['name']) ...
49,636
def ta_adaptor(indicator_mixin: Type[IndicatorMixin], function_name: str, **kwargs) -> callable: """Wraps strategies from ta to make them compatible with infertrade's interface.""" indicator_parameters = inspect.signature(indicator_mixin.__init__).parameters allowed_keys = ["close", "open", "high", "low", "...
49,637
def get_addresses(inp, out): """get_addresses(inp, out): It will search for addresses from gdb. inp and out, are the gdb input and output respectively. Return value is a list of tuples. The tuples contain the filename and the address the filename was loaded.""" addr = [] nxad = 1 while nxad: if nxad == 1: o...
49,638
def flops(program, only_conv=True, detail=False): """Get FLOPs of target graph. Args: program(Program): The program used to calculate FLOPS. only_conv(bool): Just return number of mul-adds in convolution and FC layer if `only_conv` is true. default: True. detail...
49,639
def eq11 (A): """Chemsep equation 11 :param A: Equation parameter A""" return math.exp(A)
49,640
def extractor_to_question(extractor: str): """ return questions for a extractor in a tuple :param extractor: :return: """ if extractor == 'action': return ('who', 'what') elif extractor == 'cause': return ('why',) elif extractor == 'environment': return ('where', ...
49,641
def _post_step_reboot(task, step_type): """Reboots a node out of band after a clean/deploy step that requires it. If an agent step has 'reboot_requested': True, reboots the node when the step is completed. Will put the node in CLEANFAIL/DEPLOYFAIL if the node cannot be rebooted. :param task: a Tas...
49,642
def getpage(url): """ Downloads the html page :rtype: tuple :param url: the page address :return: the header response and contents (bytes) of the page """ http = httplib2.Http('.cache', disable_ssl_certificate_validation=True) headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 6...
49,643
def path_to_xpath(node_or_path: Union[str, ncs.maagic.Node]) -> str: """Get the XPath to a node (keypath or maagic Node) The input can be either: - string keypath (/devices/device{foo}/config/alu:port...), - maagic Node instance. The helper will start a new MAAPI read transaction if necessary. ...
49,644
def read(channel): """This function returns the state of a specified GPIO pin.""" GPIO.setup(channel, GPIO.IN) return GPIO.input(channel)
49,645
def sortmerna_indexdb(input_fp, output_fp, params="", HALT_EXEC=False): """ """ cmd = "indexdb_rna --ref %s,%s -v %s" % (input_fp, output_fp, params) return call_cmd(cmd, HALT_EXEC)
49,646
def _extract_original_opp_board(finished_board): """ This function removes all shots that have been fired on it, reverting sunken ships to normal. Notably, coordinates that have hits, but no sunk ship will be set to be empty as the position of the original ship is unclear. The motivation for this functi...
49,647
def pool(): """Fixture that returns a Pool object.""" return MagicMock()
49,648
def extended_gcd(a, b): """ ----- THIS FUNCTION WAS TAKEN FROM THE INTERNET ----- Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb """ # r = gcd(a,b) i = multiplicitive inverse of a mod b # or j = multiplicitive inverse of b mod a # Neg return values for i or j are made posi...
49,649
def get_interp_BmV_from_Teff(teff): """ Given an effective temperature (or an array of them), get interpolated B-V color. """ mamadf = load_basetable() mamadf = mamadf[3:-6] # finite, monotonic BmV mamarstar, mamamstar, mamateff, mamaBmV = ( nparr(mamadf['R_Rsun'])[::-1], n...
49,650
def print_first_and_last(sentance): """Prints the first and last word in a sentence.""" words = break_words(sentance) print_first_word(words) print_last_word(words)
49,651
def test_parametrization(): """Test parametrizing a capability.""" eq_(TestTerminal().cup(3, 4), unicode_parm('cup', 3, 4))
49,652
def get_upstream_pins(m, dependencies, index): """Download packages from specs, then inspect each downloaded package for additional downstream dependency specs. Return these additional specs.""" dependencies = [strip_channel(dep) for dep in dependencies] # Add _tmp here to prevent creating the build_pr...
49,653
def process_image(filepath, outpath, settings): """Process one image: resize, create thumbnail.""" logger = logging.getLogger(__name__) logger.info('Processing %s', filepath) filename = os.path.split(filepath)[1] outname = os.path.join(outpath, filename) ext = os.path.splitext(filename)[1] ...
49,654
async def _load_mfa_module(hass: HomeAssistant, module_name: str) -> types.ModuleType: """Load an mfa auth module.""" module_path = f"homeassistant.auth.mfa_modules.{module_name}" try: module = importlib.import_module(module_path) except ImportError as err: _LOGGER.error("Unable to load...
49,655
async def test_web_get_host(opsdroid): """Check the host getter.""" opsdroid.config["web"] = {} app = web.Web(opsdroid) assert app.get_host == "0.0.0.0" opsdroid.config["web"] = {"host": "127.0.0.1"} app = web.Web(opsdroid) assert app.get_host == "127.0.0.1"
49,656
def model_metrics(key,codes="",nb=None,with_doc=False): """ param1: dictionary : AutoAI steps data param2: string : Code syntaxs param3: boolean : Whether to includer documentation/meta description for the following section return: string : Code syntaxs The function adds code syntax related to ...
49,657
def so3_rotate_with_normal(batch_data): """ Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds """ rotated_da...
49,658
def test__get_disk_usage(): """ Test Command ------------ $ python run_tests.py --module_name plot_playground.tests.test_linux_stats_plot:test__get_disk_usage --skip_jupyter 1 """ disk_usage_gb = linux_stats_plot._get_disk_usage() assert_true(isinstance(disk_usage_gb, float)) ass...
49,659
def populate_from_file(filename, gap=0.1, pool_intensity=4, pool_capacity=None, eps_diff=1e-7, verbose=False): """ Runs populate on a model file. :param filename: the model file. :param gap: MIP gap to use for the p...
49,660
def test_flag_on(run_cli_command): """ scenario: flag "--on" detrmines if option opt is required action: invoke with --on behaviour: fails with Missing option message """ cmd = construct_simple_cmd('--on', is_flag=True) result = run_cli_command(cmd, ['--on'], raises=True) assert 'Error: ...
49,661
def delete_object(client, args): """Utility to delete a vineyard object based on object_id.""" if args.object_id is not None: try: client.delete(object_id=as_object_id(args.object_id), force=args.force, deep=args.deep) print(f'The vineyard object({args.object_id}) was deleted suc...
49,662
def dihedral(p): """Praxeolitic formula 1 sqrt, 1 cross product""" p0 = p[0] p1 = p[1] p2 = p[2] p3 = p[3] b0 = -1.0*(p1 - p0) b1 = p2 - p1 b2 = p3 - p2 # normalize b1 so that it does not influence magnitude of vector # rejections that come next b1 /= np.linalg.norm(b1) ...
49,663
def mangle_varname(s): """Append underscores to ensure that `s` is not a reserved Python keyword.""" while s in _PYTHON_RESERVED_KEYWORDS: s += "_" return s
49,664
def standard_prediction_error(x_data, y_data): """Return function to calculate standard prediction error. The standard prediction error of a linear regression is the error when predicting a new value which is not in the original data. Parameters ---------- x_data : numpy.array x coordi...
49,665
def test_wci3(): """ Test with jacobian=True """ pytest.importorskip("numdifftools") d = D([(0, 0), (1, 1)], [2/3, 1/3]) wci = WynerCommonInformation(d, bound=2) wci._jacobian = True wci.optimize() d = wci.construct_distribution() d_opt1 = D([(0, 0, 0), (1, 1, 1)], [2/3, 1/3]) ...
49,666
def Ascrape_json(search_term): """ """ headers = { 'User-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } proxies = { 'http': os.getenv('HTTP_PROXY') # or just type ...
49,667
def update_dict(original, new): """ Update nested dictionary (dictionary possibly containing dictionaries) If a field is present in new and original, take the value from new. If a field is present in new but not original, insert this field :param original: source dictionary :type original: di...
49,668
def parse() -> Tuple[Response, int]: """ Parse the inputs of a workflow. """ req_data = yaml.safe_load(request.get_data().decode("utf-8")) wf_location = req_data.get("wf_location", None) wf_content = req_data.get("wf_content", None) if wf_location is None and wf_content is None: retu...
49,669
async def test_bridge_cannot_connect(hass): """Test checking for connection and cannot_connect error.""" entry_mock_data = { CONF_HOST: "not.a.valid.host", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } with patch.object(Smartbridge, "create_tls") as create_t...
49,670
def test_set(namespaceable, namespace): """Set attributes on a namespace, at various points. You can set attributes on a Namespace after the class definition. The changes will be visible on both the class, and on instances. You can set attributes on an instance Namespace. This will not propagate up ...
49,671
def test_parse_args() -> None: """Test the parsing of command-line arguments.""" bind_address = "127.0.1.0" options = ("ssid", "password", "region", "token", "secret") args = ["--bind", bind_address] for option in options: args.append(f"--{option}") args.append(option) parsed_o...
49,672
def try_which(): """ Locate hmmsearch on path, if possible :return: """ try: return str(local["which"]["hmmsearch"]()).rstrip("\r\n") except ProcessExecutionError: return "None"
49,673
def getCountryClubCreditMultiplier(countryClubId): """ Returns the skill credit multiplier for a particular mint. mintId is the mint-interior zone defined in ToontownGlobals.py. """ return { BossbotCountryClubIntA: 2., BossbotCountryClubIntB: 2.5, BossbotCountryClubIntC: 3., ...
49,674
def get_world_rank() -> int: """Get the world rank of this worker. .. code-block:: python import time from ray.air import session def train_loop_per_worker(): for iter in range(100): time.sleep(1) if session.get_world_rank() == 0: ...
49,675
def solve(): """ Replace this with a nice docstring that describes what this function is supposed to do. :return: The answer required. """ return -1
49,676
def add_formatter_and_handler( logger: logging.Logger, handler: logging.Handler, level: int = logging.DEBUG, format_string: Optional[str] = None, ) -> None: """Add formatter defined by ``format_string``, and ``handler`` with ``level`` to ``logger``. Parameters ---------- logger: :class:...
49,677
def read_data(files, poscount, locidx): """Builds input data from a files list.""" locs = [] # One element per file; each is a list of location indexes. vals = [] # One element per file; each is a parallel list of values. labels = [] # One element per file: true for '.s', false for '.f'. for fnam...
49,678
def deterministic_dynamics(init_cond, dt, num_steps, init_time=0.0): """ Uses naive euler's method: x(t+dt) = x_k + F(x_k, t_k) * dt """ # prep arrays states = np.zeros((num_steps, STATE_DIM)) times = np.zeros(num_steps) # fill init cond states[0, :] = init_cond times[0] = init_time ...
49,679
def load_genres(): """Load genres into a separate table.""" print "Genres" Genre.query.delete() with open('seed_data/ign.csv') as csvfile: game_data = reader(csvfile, dialect='excel') next(game_data) for row in game_data: genres = row[6] genre_types = genres.split(',') for genre_type in gen...
49,680
def addDeConvModule(nnet, num_filters, filter_size, crop=0, W_init=None, bias=True, pool_size=(2,2), use_batch_norm=False, dropout=False, p_dropout=0.5, upscale=False, flip_filters=False, activationFlag=True): """ add a convolutional module (convolutional layer + (leaky) ReLU + MaxPool) to the...
49,681
def get_scope_and_reuse_disc(network_id, layer_id, num_separate_layers): """Return the scope and reuse flag. Args: network_index: an integer as the network index. layer_id: an integer as the index of the layer. num_separate_layers: an integer as how many layers are independent. Ret...
49,682
def groups_list(access_token): """List FlexVM Groups""" logging.info("--> List FlexVM Groups...") uri = FLEXVM_API_BASE_URI + "groups/list" headers = COMMON_HEADERS.copy() headers["Authorization"] = f"Bearer {access_token}" results = requests_post(uri, "", headers) return results
49,683
def get_data_for_run(butler, run_id, **kwargs): """Builds a dictionary of filenames or butler dataids for a particular run and test type, given a data access method, teststand Parameters ---------- butler : `Butler` or `None` The data Butler run_id : `str` The number number we a...
49,684
def files_from_folder(path, extension): """ Returns files within folder with given extension Args: path->str: path to input directory extension->str: file type to find Returns: List of paths """ files = [] for root, subfolders, some_files in os.walk(path): for some_file in so...
49,685
def install_site(): """Installs the site for the first time (assumes the account exists).""" print(green('Setting up venv...', True)) run('virtualenv ~/venv') print(green('Installing requirements...', True)) put('requirements.txt', '~/') run('~/venv/bin/pip install -r requirements.txt') pr...
49,686
def format_route(raw_route): """Cleans and formats route list into valid REXX input. Arguments: route {list} -- user input for route Returns: {bool} -- Flag indicating valid route. {str} -- Error message. {list} -- List of validated routes. """ raw_route_list = ...
49,687
def gamma_lnpdf(x, shape, rate): """ shape/rate formulation on wikipedia """ coef = shape * np.log(rate) - gammaln(shape) dterm = (shape-1.) * np.log(x) - rate*x return coef + dterm
49,688
def test_connection_kwargs(mock_sqlite): """A spot check to make sure optional connection kwargs gets passed to connection""" DbDict('test', timeout=0.5, invalid_kwarg='???') mock_sqlite.connect.assert_called_with('test', timeout=0.5)
49,689
def get_total_variation(variable_img, shape, smoothing=1.5): """Compute total variation regularization loss term given a variable image (x) and its shape. Args: variable_img: 4D tensor representing the variable image shape: list representing the variable image shape smoothing: smoot...
49,690
def dict_filter(d, keep): """ Remove all keys from dict except those specified in list 'keep'. Recurses over values to remove keys from nested dictionaries :param d: Dictionary from which to select key,value pairs :type d: dict :param remove: Keys to select :type remove: list :returns: dictionary with ke...
49,691
def tf_depthwise_conv2d(input, w): """Two-dimensional depthwise convolution using TF. Params same as in depthwise_conv2d. """ input_4d = tf.reshape(tf.constant(input, dtype=tf.float32), [1, input.shape[0], input.shape[1], input.shape[2]]) # Set channel_multiplier dimension...
49,692
def parse(puzzle_input): """Parse input""" return [tuple(line.split()) for line in puzzle_input.split('\n')]
49,693
def set_new_pw_extra_security_phone(email_code: str, password: str, phone_code: str) -> FluxData: """ View that receives an emailed reset password code, an SMS'ed reset password code, and a password, and sets the password as credential for the user, with extra security. Preconditions required for t...
49,694
def test_checksum(): """ Test if checksum validate as expected """ ret = { "file1.rpm": True, "file2.rpm": False, "file3.rpm": False, } mock = MagicMock(side_effect=[True, 0, True, 1, False, 0]) with patch.dict(rpm.__salt__, {"file.file_exists": mock, "cmd.retcode": ...
49,695
def get_driver_and_zones(driver_name, account_name): """ Get the DNS driver, authenticate, and get some zones. """ secret_site = "libcloud/" + driver_name cls = get_driver(driver_name) pw = get_password(secret_site, account_name) if not pw: pw = getpass("Password:") while True:...
49,696
def normalize(seed_url, link): """Normalize this URL by removing hash and adding domain """ link, _ = urldefrag(link) return urljoin(seed_url, link)
49,697
def multi_lab_segmentation_dilate_1_above_selected_label(arr_segm, selected_label=-1, labels_to_dilate=(), verbose=2): """ The orders of labels to dilate counts. :param arr_segm: :param selected_label: :param labels_to_dilate: if None all labels are dilated, in ascending order (algorithm is NOT orde...
49,698
def test_get_latest_snapshot_version(): """Integration test to make sure we can get the latest snapshot (library and sources) jars for an ST project that we've uploaded to the OSS instance of Artifactory that JFrog runs. """ from stac.api import new_maven_client client = new_maven_client(ARTIFAC...
49,699