content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def access_token(*args, **kwargs): # pylint: disable=unused-argument """ This endpoint is for exchanging/refreshing an access token. Returns: response (dict): a dictionary or None as the extra credentials for creating the token response. """ return None
afce25c658e11f31d86b4feecabb5cb27bc1e0f0
668,773
def cohens_d_multiple(xbar1, xbar2, ms_with): """ Get the Cohen's-d value for a multiple comparison test. Parameters ---------- > `xbar1`: the mean of the one of the samples in the test. > `xbar2`: the mean of another of the samples in the test. > `ms_with`: the mean-squared variability of the samples Returns...
53b04da90a440f4026a20f8e11bccd824412da62
668,774
def new_capacity_rule(mod, g, p): """ New capacity built at project g in period p. Returns 0 if we can't build capacity at this project in period p. """ return ( mod.GenNewBin_Build[g, p] * mod.gen_new_bin_build_size_mw[g] if (g, p) in mod.GEN_NEW_BIN_VNTS else 0 )
6ccd299aef7296124df5554ed5894fc8d03c6e4b
668,775
def find_key(d, nested_key): """Attempt to find key in dict, where key may be nested key1.key2...""" keys = nested_key.split('.') key = keys[0] return (d[key] if len(keys) == 1 and key in d else None if len(keys) == 1 and key not in d else None if not isinstance(d[key], dict) el...
1d3ae404a598103968dacdce2706d1fc7f4ac71e
668,776
def box_area(box): """the area of a box Args: box: (left, top, right, bottom) """ left, top, right, bottom = box return (right-left+1) * (bottom-top+1)
ccc7bc148455896d497cbf1a1d55cf799e1317e1
668,777
import re def is_number(num_str): """ Determine whether the string can be converted to a number (int and float) :param num_str: :return: """ if not re.compile(r"^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$").match(num_str): return False return True
774d0efce085e2dccc7737848951a36a45461449
668,778
def _form_c_loop_beg(ctx): """Form the loop beginning for C.""" return 'for({index}={lower}; {index}<{upper}, {index}++)'.format( index=ctx.index, lower=ctx.lower, upper=ctx.upper ) + ' {'
d5ceb045c1c5c6463846a858e488fbc22511364e
668,779
def return_one(): """Function level Docstring.""" return 1
42fc8c856200d04dfe48adba76c670dc34355eb8
668,780
def _find_known(row): """Find variant present in known pathogenic databases. """ out = [] clinvar_no = set(["unknown", "untested", "non-pathogenic", "probable-non-pathogenic", "uncertain_significance", "uncertain_significance", "not_provided", "benign", "likel...
8b043504a4df27b0928d975d81ee129c6a984c9b
668,782
def _advance_years(dt, years): """ Advance a datetime object by a given number of years. """ return dt.replace(year=dt.year + years)
00780f2d12edff3531213ccd881d5cbced3d8f2e
668,783
def drop_cols_with_null(df): """ Drops all columns with null value. :param df: Data Frame Object :return: Data Frame Object """ return df.dropna(axis=1)
86c00d4eaff7c94d4e24183038befcd19a103d1c
668,784
import requests from bs4 import BeautifulSoup def get_page_contents(URL): """Scrape the contents based on the h2 headers and structure they use for a web page. URL: string, absolute URL to the page returns --- page_contents: dict, with key=subject, value=list of all paragraphs """ page ...
5c427ad3f58558a2f96401914f5e44d64a296fd9
668,785
import os def create_clip_file_name(row, clip_file_format="mp4"): """ Create the output clip file name. :param row: pandas.Series. One row of the video annotation output from the VIA tool. This function requires the output from VIA tool contains a column '# CSV_HEADER = metadata_id'. ...
be8084e379469c5663bb22da552d60364a7eb8a5
668,786
def GenerateConfig(context): """Generate configuration.""" resources = [] # template to enable api resources.append({ 'name': context.env['project'] + '-enable-' + context.properties['api'], 'type': 'deploymentmanager.v2.virtual.enableService', 'properties': { 'consumerId': 'project:...
ce617417edb384a6597efa84e0996ca95562912c
668,787
def determine_message_topic(message): """ Determines whats in the message and returns a string with the name of the topic. """ if "[[" not in message: return "text" lookup_dict = {"Document": "file", "Photo": "pic", "Voice": "voice_msg", "Sticker": "sticker", ...
6150dc1fe157aca31458dd606384f59ebcd93a6b
668,789
import os def _expand_dirs(local_services): """Gives a list of paths that have a quest yaml file in them. Notes: If any dir ends in * then walk the subdirectories looking for quest.yml Args: local_services (list): A list of avaliable paths. Returns: A list of avaliable paths ...
d477f443d55243595b81f9679ed16e699c904847
668,792
import os def checkExists(path): """ Check is directory exists Args: path (string): directory path Returns: **boolean** (boolean) - is directory exists """ return os.path.exists(path)
8a383d8743af792358ba628f703428540157b2ac
668,793
import os def validate_file_exists(filenames): """Check if an input filename exists Args: filenames(list of str): a list of filenames to read Returns: bool: False if one of the names does not exist, True if all names exist """ for file in filenames: if not os.path.exist...
7714e423fd57b2fa201ce98f076f95f213022f4c
668,794
def max_sub_array_sum(array): """Implementation of the Kadane's algorithm to solve the maximum sub-array problem in O(n) time and O(1) space. It finds the maximum contiguous subarray and print its starting and end index. Here it will return the indexes of the slices between which there is the maximum hy...
90e9468093a008a9a8466e77f5500365e74d4d48
668,796
from typing import Union from typing import Dict def nvl_attribute(name: str, obj: Union[None, Dict], default): """ Given an name and a value return the dictionary lookup of the name if the value is a dictionary. The default is returned if not found. @param name: name to lookup @param...
cd2b4a383d88caf8d6900199ae352b6ac83303c2
668,797
def bootstrap_bop_data(): """ Sets up the data structure for the balance of power calculations. """ return { 'house': { 'democrats': {'total': 0, 'needed_for_majority': 218}, 'republicans': {'total': 0, 'needed_for_majority': 218}, 'other': {'total': 0, 'neede...
4ac2b77c56596e4e764ec132cdba3c18baf43d1a
668,799
def _fk(feature_name, channel, target): """Construct a dict key for a feature instance""" return "{}::{}::{}".format(feature_name, channel, target)
80ec588fc801210c8d4598359bde6891b73e73da
668,800
def calculate_viscosity_simple(C, T=20.0): """ Calculate viscosity using a simplified function with fixed temperature at T=20 degr. linear fit to Batzle (1992) eq. over range of C=0.0 to 0.035 (ie, fresh to seawater range) """ viscosity = 9.8080e-04 + 2.6515e-03 * C return viscosity
8a4f35918c60beec80501234d39cdfa45a2e208b
668,801
from datetime import datetime def begin_of_day(dt: datetime, tz): """ 将时间设置为当日开始(00:00:00) """ return dt.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=tz)
9c9c97f2cc5e449d88b40bc0bea7df96840698ed
668,802
import re def _get_module_doc(module): """Get and format the documentation for a module""" doc = module.__doc__ or "" # Replace headlines with bold text doc = re.sub(r"([\w ]+:)\n-+", r"**\1**", doc) num_hash = min(2, module.__name__.count(".")) return f"{'#' * num_hash} {module.__name__}\n{...
63583e38bd91f748572b350091b20c5f73da6ffe
668,803
def prod(seq): # pylint: disable=anomalous-backslash-in-string """Product of a sequence of numbers. Parameters ---------- seq : sequence A sequence of numbers. Returns ------- float or int Product of numbers. Notes ----- This is defined as: .. math:: ...
a9f81b78e90410713f805cb5b2ecae6c0270009c
668,804
def has_source_files( self ): """Checks if there are source files added. :return: bool """ return bool(self._source_files)
2350569b5411aa480e81109a0ce57da768ed51a3
668,805
def dms2decimal(decString, delimiter): """Converts a delimited string of Degrees:Minutes:Seconds format into decimal degrees. @type decString: string @param decString: coordinate string in D:M:S format @type delimiter: string @param delimiter: delimiter character in decString @rtype: float ...
771cd14a031b2c266b86488387c8179c668d9ffe
668,806
def get_fill(st, starttime=None, endtime=None): """ Subroutine to get data fill @rtype: float """ if len(st) == 0: # no trace return 0.0 ststart = min(tr.stats.starttime for tr in st) stend = max(tr.stats.endtime for tr in st) dttot = (stend if not endtime else endtime) ...
0dcbf6c9b122eb0ed6211570c4f153dff059455a
668,807
import re def remove_tags(text): """Remove html tags from a string""" clean = re.compile('<.*?>') return re.sub(clean, '', text)
b5bb38c10c99ec7979b0d740717e60f87cfccb9d
668,808
from typing import List def build_on_conflict_do_nothing_query( columns: List[str], dest_table: str, temp_table: str, unique_constraint: str, dest_schema: str = "data", ) -> str: """ Construct sql query to insert data originally from `df` into `dest_schema.dest_table` via the temporary...
dbeeba72cec7be0a4ee24ad30044b12fec60e27d
668,809
def get_token_segments(labels, word_ids): """ Function to extract correctly formatted answers Input: array of labels (can be predicted labels, or true labels) Output: array of tuples; (start index of answer, length of answer) """ prev_word_id = None labels_stats = [] for idx, label ...
81ae667a488d71f71576e29e34a573b9122cd601
668,810
import socket import os import collections def initPath(): """initial shortcut for some import paths """ hostName = socket.gethostname() dirDB = 'UNKNOWN' dirOut = 'UNKNOWN' dirResult = 'UNKNOWN' if hostName == 'smallLinux': dirDB = os.path.join(os.path.sep, 'mnt', 'sdc', 'rnnSMAP'...
5da689b15d61b31e03593ba5e63e8850807d8f72
668,812
import random import string def create_discount_code(): """ Create a new discount code """ n = random.randrange(1000, 9000) s = random.choice(string.ascii_uppercase) return f'NAW{n}{s}'
bc21b6a88866c6c210ab65a8c62c8caaea77385d
668,813
def dirac(pred, gt): """ Chechks whether pred == gt. :param pred: Prediction :param gt: Ground-truth. :return: """ return int(pred == gt)
ebf768321a585fdc3501b70146fb706cb66b1132
668,814
import argparse def parse_args(): """ Parse command-line arguments. Returns ------- WRITEME : WRITEME Parsed arguments """ # The global program parser. parser = argparse.ArgumentParser( description='Obtain versions of relevant Python modules.') parser.add_argum...
07c61b11db4758a36173b7c4dc32929f21a6d3d0
668,815
import numpy def metrics(exe, train_test_program, train_test_feed, train_test_reader, fetch_list): """ Return the metric values on other data Arguments: exe : executor train_test_program: test program of the model train_test_feed: feed of the new data ...
bdc6aadf438f6f7f676354f35bd6d01114656f2b
668,817
def _etsz(rn, g, tmean, u2, vpd, es_slope, psy, cn, cd): """Standardized Reference ET [mm] (Eq. 1) Parameters ---------- rn : scalar or array_like of shape(M, ) Net radiation [MJ m-2 d-1 or MJ m-2 h-1]. g : scalar or array_like of shape(M, ) Ground heat flux [MJ m-2 d-1 or MJ m-2 h-...
440b4917517f6f4291b92525b67560347f486b8b
668,818
import os def write_env_file(output_dir, job_name, envs): """Writes envs into a file in output_dir, and returns the file name.""" output_file = os.path.join(output_dir, '%s.env' % job_name) with open(output_file, 'w') as fp: fp.write('\n'.join(envs)) fp.write('\n') return output_file
ccf57376a16ad27d69c4af8d5c4b5d91b5425a6e
668,819
def selection_sort(nums_array: list) -> list: """ Selection Sort Algorithm :param nums_array: list :return nums_array: list """ for i in range(len(nums_array)): min_index = i for j in range(i + 1, len(nums_array)): if nums_array[j] < nums_array[min_index]: ...
be0fb5c04aee7258215e8740f54e93c7d5680681
668,820
def remove_slug(path): """ Return the remainin part of the path >>> remove_slug('/test/some/function/') test/some """ if path.endswith('/'): path = path[:-1] if path.startswith('/'): path = path[1:] if "/" not in path or not path: return None parts = ...
c35cd9417cf1517732e9fb775f236e5ed693de87
668,821
import socket def is_v4(address): """Determines if the supplied address is a valid IPv4 address""" try: socket.inet_pton(socket.AF_INET, address) return True except socket.error: return False
5f4eb02e9e7b6d3ccf772a3eaa5df4b727c6e5c5
668,822
def get_description(params): """ :type params: dict """ return "List all commands"
029897f830266e4b10c944922068454ca7898d56
668,823
from pathlib import Path def find_campaign_root(): """ Determine the base campaign directory Walks up the directory tree until it finds the '.npc' campaign config directory, or hits the filesystem root. If the `.npc` directory is found, its parent is assumed to be the campaign's root directory. O...
a326e993a62d63da36a34dd7756658747fb660af
668,824
def year_cv_split(X, year_range): """Split data by year for cross-validation for time-series data. Makes data from each year in the year_range a test set per split, with data from all earlier years being in the train split. """ return [ ((X["year"] < year).to_numpy(), (X["year"] == year).to...
f5c7348a6589c180281de35bc9893f1de00252f1
668,825
def is_list_of_valid_elem(value, elem_validator): """ Is the given value a list whose each element is checked by elem_check to be True? :param value: The value being checked :type value: Any :param elem_validator: The element checker :type elem_validator: Any -> bool :return: True if the given v...
8464aa82835022930d3efe2148e148d457099c63
668,826
def return_period_earth(energy_mttnt): """ Return period of Asteroid/Comet of a given energy (Megatons TNT) in Years. :param energy_mttnt: Energy in Megatons TNT :returns: Return period of given energy level in years :Reference: EarthImpactEffect.pdf, Equation 3* """ return 109 * (energy_mt...
e54bc9b79add1c9efef8710fd3d047097aff6180
668,827
def repl_num(s:str, sub="xxnum") -> str: """Removed digits""" if s.isdigit(): return sub return s
88575c272e1eacac24bd2db5285d9ddfb16f7d69
668,828
import re def FixServerImplementation(implementation): """Rewrites a MIG-generated server implementation (.c) file. Rewrites the file at |implementation| by replacing “mig_internal” with “mig_external” on functions that begin with “__MIG_check__”. This makes these functions available to other callers outside...
028889accb193ea1a16625477e2b4bc626e32aa2
668,829
from pathlib import Path from typing import List import subprocess def git_command(repository: Path, args: List[str]) -> str: """ Run a git command in a repository. Crashes with a CalledProcessError :param repository: Path to the repository :param args: the rest of the git arguments :return: a str...
c3c765c07d3b0c6951a305afcc54f0d302747fd2
668,830
from typing import Iterable def _table_cell(items: Iterable[str]) -> str: """Make a row of table cell.""" return '|' + '|'.join(f" {t} " for t in items) + '|'
4b489283126900cdd371eb99c4ae3bd114232966
668,832
def triangle_up_to(*, index=None, value=None): """ [NP] Returns all triangle numbers up to the `index`-th member, or until the value exceeds `value`. :param index: integer :param value: integer :returns: list of integers, with the desired triangle sequence numbers """ assert index is no...
658d4068fc200138c61b3cb3449643de581b14c2
668,833
def expected_ic_m_acc_roundwise_values(): """m_acc value for a round.""" return { "top1_accuracy_round_0": 0.39922, "top3_accuracy_round_0": 0.49062, }
93f6de42fab6619adc83647e1005178d7bdf75c0
668,834
import argparse def parse_arguments(): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--project', type=str, required=True, help='Your project ID.') parser.add_argument('--endpoint', type=str, required=True, help='Your en...
74bc60aedba9b2b18647119836cd2a581c3c0577
668,835
def portfolio_vol(weights,covmat): """ Weights -> Vol """ return (weights.T @ covmat @ weights)**0.5
9f78341668e7497c34b73fc04995340a2375fca3
668,836
from typing import OrderedDict def list_visible_columns_for_schemas(request, schemas): """ Returns mapping of default columns for a set of schemas. """ columns = OrderedDict({'@id': {'title': 'ID'}}) for schema in schemas: if 'columns' in schema: columns.update(schema['columns'...
f90559aeddb877ce9bee3b57cbddcfc92f7dd05e
668,837
def position_case_ligne_motif(pos_ligne_motif, sens, colonne, ligne): """ renvoie la position de la case en fontion du sens des lignes """ x_debut, y_debut = pos_ligne_motif if sens=="gauche": x_case = x_debut-colonne*25 else: x_case = x_debut+colonne*25 return x_case, y_debu...
efa2c97c903333a2a3ef8596134659a35bc547f7
668,838
def denumpify(arg): """Converts numpy datatypes to python datatypes bool_ and bool8 are converted to Python bool float64, float32 and float16's are converted to Python float() intc, intp, int8, int16, int32, int64, uint8, uint16, uint32 and uint64 are converted to Python int() complex_, complex64 a...
885c4d8ca285ef5a0564e0b14c52de52ce87a704
668,839
def identity(x): """Return exactly what was provided.""" return x
ee6152b046b55e2044b67c4afed07ccc7c6cc471
668,841
def get_widths_balancer(widths, minmax_ratio=0.02): """ Given a list of positive numbers, find a linear function, such that when applied to the numbers, the maximum value remains the same, and the minimum value is minmax_ratio times the maximum value. :param widths: list of numbers :param minmax_rat...
e0f929125e513576e8420f005abc351aaceca45b
668,842
import torch def point_line_distance_range(lines:torch.Tensor, points:torch.Tensor): """calculate the maximal distance between the points in the direction perpendicular to the line methode: point-line-distance Args: lines (torch.Tensor): (..., 24, 2, 2) points (torch.Tensor): (..., 24, 6,...
d75fb13434a80d58486f80a7f965df09b3edb2d9
668,843
def calc_nth_prime(location): """ THis will try to calculate the nth prime :param location: int :return: """ return None
a911bef63e437082216f232079e793681460e0c0
668,844
def factorials(number: int, iteratively=True) -> int: """ Calculates factorials iteratively as well as recursively. Default iteratively. Takes linear time. Args: - ``number`` (int): Number for which you want to get a factorial. - ``iteratively`` (bool): Set this to False you want...
d4af8b05d91b9ac9fba9f852564e8043cf231e40
668,845
def distance_point_segment(ps1, ps2, external_p): """Returns the distance between segment and point. Don't ask why.""" x3, y3 = external_p x1, y1 = ps1 x2, y2 = ps2 px = x2-x1 py = y2-y1 norm = px*px + py*py u = ((x3 - x1) * px + (y3 - y1) * py) / float(norm) if u > 1: u...
982a8a31020c84c65300aec8f30833132f84eb75
668,846
def mean_percentage_error(y_true, y_pred): """Compute the mean percentage error (MPE). Parameters ---------- y_true : array-like, shape (n_samples,) Ground truth (correct) target values. y_pred : array-like, shape (n_samples,) Estimated target values. Returns ------- m...
35206143e42c68d900fc3e692039fb0dd1343032
668,847
def match_prio_rule(cz, pr: dict) -> bool: """Match a priority rule to citizenlab entry""" for k in ["category_code", "cc", "domain", "url"]: if pr[k] not in ("*", cz[k]): return False return True
48028308ae6f67242a17041c9d0fc9e6ecd1d306
668,848
def estimated_bigram_probability(bigram, unigram_dict, bigram_dict): """ estimate the probability of bigram (= (syll_1,syll_2)) by: (count (syll_1,syll_2)) / (count syll_1) """ # set the count to zero count = 0 # check if bigram is actually in our dict if bigram in bigram_dict: # i...
adf5d3830118da86b4e9a7981bfda4210f47b7f9
668,849
def get_all_components_by_permission(xml, permission): """ Return: (1) activity (2) activity-alias (3) service (4) receiver (5) provider who use the specific permission """ find_tags = ["activity", "activity-alias", "service", "re...
9e0bd9004fea488dc5cd6a4c2b5033659e53a352
668,850
def monkeypatch_readline(request, monkeypatch, readline_param): """Patch readline to return given results.""" def inner(line, begidx, endidx): if readline_param == "pyrepl": readline = "pyrepl.readline" else: assert readline_param == "readline" readline = "rea...
eef729f50cf58da47d474a40a64eed647e345127
668,851
from typing import Union from typing import Callable from typing import Any def add_docstring(input_func: Union[Callable[[], Any], Callable[[Any], Any]], doc_to_add: str) -> Union[Callable[[], Any], Callable[[Any], Any]]: """ Helper function to add docstrings to other functions. """ ...
0cd9969267a1909585bd09ef96aaac2436bc73d8
668,852
import re def remove_algorithm_info(out): """Remove information about algorithms which may differ from system to system.""" filter_patterns = ("Algorithm: .*\n",) for filter_pattern in filter_patterns: out = re.sub(filter_pattern, "", out) return out
aa6125930c2e8c23ade1abd7d895f4de218c6b4a
668,853
import os def authentication_headers_raw(): """Get authentication headers without renku user identification.""" headers = { "Content-Type": "application/json", "Authorization": "Bearer {0}".format(os.getenv("IT_OAUTH_GIT_TOKEN")), } return headers
2dba1c5fd7bfd29585b50ab080ffd606a13ece7e
668,854
import os def get_file_with_parents(filepath, levels): """function to get file with parents and return parents along with file upto level 2""" common = filepath for i in range(levels + 2): common = os.path.dirname(common) return os.path.relpath(filepath, common)
2f3e120bbd75b9052290b0031a18d9ab7d35d5cb
668,855
def _is_idempotence_error(status_code, errors, context): """ Determines if an idempotence error has occurred based on the status code, errors and context """ return status_code == 409 \ and context is not None \ and context.idempotence_key is not None \ and len(errors) == 1 \ ...
e7c42c86cfd03a92a679528a17923625b1e268ba
668,858
def format_verify_msg(status): """Format validation message in color""" OK = '\033[92m OK \033[0m' FAIL = '\033[91mFAIL\033[0m' if status: return OK else: return FAIL
b20fb9ffd375ee9faac08198997f39f090b89d20
668,859
import os def IsChromiumRoot(path): """Returns True if |path| exists and is the root of the Chromium source tree. The root of the Chromium tree is the directory above 'src'. I.e. '<root_path>/src/.gn' is the top level .gn file.""" paths_to_check = ['.gn', 'chrome', 'content', 'net'] return all( ...
e05c417542b36330b18dab237d6f4de86337a65f
668,861
import re def golang_duration_to_seconds(d: str) -> int: """ Convert values like "276h41m7s" to number of seconds """ add = "" for c in ["s", "m", "h"]: if d.endswith(c): break add += "0" + c d += add hms = [int(x) for x in re.split(r"\D", d)[:-1]] res = hm...
37a4cf681ae8e065e417361813cd9a58dcef1436
668,863
def _WrapLogicOp(op_fn, sentences, ctx, item): """Wrapper for logic operator functions. """ return op_fn(fn(ctx, item) for fn in sentences)
0242466ecfd3e56e99c3fed0cee22bc4b99d9537
668,864
def split_chain(chain): """ Split the chain into individual certificates for import into keystore :param chain: :return: """ certs = [] if not chain: return certs lines = chain.split('\n') cert = [] for line in lines: cert.append(line + '\n') if line =...
4367c29cdd2059d513ef642c61fa761dd8485412
668,866
def class_labels(column): """ Takes in target column and creates list of binary values. 1 (>=0.5) being in the positive class (toxic), 0 (<0.5) being in the negative class (Not toxic) """ class_label = [] for row in column: if row < 0.5: class_label.append(0) else...
3b94e6fbc918abb50a932550544408acca42843a
668,867
def make_data(data, **kw): """ Customize basic data structure on remote nodes """ def update(dictionary=None): base = data() if not dictionary: return base base.update(dictionary) return base return update
5e9c174812c197fd7e185ecfd8b00f605e543b4e
668,869
def _slugify(text: str) -> str: """Turns the given text into a slugified form.""" return text.replace(" ", "-").replace("_", "-")
78a034e07215e7964ebf1fc66162942d7b4ae85e
668,870
def deformat_var_key(key: str) -> str: """ deformat ${key} to key :param key: key :type key: str :return: deformat key :rtype: str """ return key[2:-1]
a74b0d5d96dbf365da502bd478ee8efb07e7f7cd
668,871
import glob def _GetSequentialFileName(base_name): """Returns the next sequential file name based on |base_name| and the existing files.""" index = 0 while True: output_name = '%s_%03d' % (base_name, index) if not glob.glob(output_name + '.*'): break index = index + 1 return output_name
943583418b2bac1b8a42c61f5f33b0bc4f38f519
668,873
def normalize(expr): """Pass through n-ary expressions, and eliminate empty branches. Variadic and binary expressions recursively visit all their children. If all children are eliminated then the parent expression is also eliminated: (& [removed] [removed]) => [removed] If only one child is ...
299406a05912421d411e5ad5c1ced2ad45e64a4d
668,874
def is_valid_machine(*args, **kwargs) -> bool: """ 判断是否为机器类型是否可用 """ # NOTE ce 版本不做判断 return True
66e61ecd93f103ad8ec819749f6546bf4ae1f18f
668,875
def get_package(config): """ Returns the package associated with this device Args: config (dictionary): configuration dictionary Return: (string) package Raises: Nothing """ #split the device string with "-" and get the second value package = config["devi...
5a13e28eafceaaab018373141108d2f8e75f2a37
668,876
from typing import OrderedDict def _getFields(obj, tree=None, retval=None, fileobj=None): """ Extracts field data if this PDF contains interactive form fields. The *tree* and *retval* parameters are for recursive use. :param fileobj: A file object (usually a text file) to write a report to on...
ad123a3eb865b1e85c4485452d7d06f84f18cb6b
668,877
def ruled_out(mun_list): """组合数字变成横竖斜对角都相加等于15的九宫格,组合的可能性,添加到列表中""" ruled_list = [] for m1 in mun_list: for m2 in mun_list: for m3 in mun_list: if len(set(m1) | set(m2) | set(m3)) == 9: u1 = m1[0]+m2[0]+m3[0] u2 = m1[1]+m2[1]+m3[1] ...
4dc086292f8dc9d79a770d27ba3c4314f424b340
668,879
import os def _parse_orion(cfg): """ Parse the config for 'not yet supported' Orion flags and inject the appropriate value. Note: This function should be remove when Orion add support for them. """ for name in cfg: if type(cfg[name]) is str and cfg[name].startswith("orion#"): ...
a39dca708b5c677361e43bc9773dcf28b7aac219
668,880
import requests def GetExternalIp(): """Gets External IP from web API.""" return requests.get('https://api.ipify.org').text
af5079dcf8d7e4c092a5a85e1416a309dd9ffed7
668,881
def path(tree, v): """returns the path in the tree from v to the root Complexity: O(V) """ P = [] while not P or P[-1] != v: P.append(v) v = tree[v] return P
01523cd71d174331021d66ceaa1764510844e009
668,882
def get_repo_dname(repo_url): """ Break url into a dirname """ slashpos = repo_url.rfind('/') colonpos = repo_url.rfind(':') if slashpos != -1 and slashpos > colonpos: pos = slashpos else: pos = colonpos repodir = repo_url[pos + 1 :].replace('.git', '') return repodir
e9e658c38fe1f4b86062780554a91f50ea402abc
668,883
def decode_dos_msg(msg): """ expand DOS exception text for readability """ msg = str(msg).replace('||r:','Role:').replace('||','').replace('|f','').replace('|l:',' ').replace('|t:','@').replace('|m:',' Message:') msg = msg.replace(' )',')') return msg
2bb08447fbcf3081e56b7f230b35a68268b33c9f
668,884
def pos_to_num(x, y): """ Essa função mapeia uma tupla (x,y) dentro do domínio para um valor z Como os passos são de 0.2, entre -2 e 2, então irei mapear os 2 primeiros digitos para o valor em y e os 2 maiores digitos para o valor de x ou seja [-1.8, -1.8] se transformara em [1,1] os pon...
6f0db0a7acaa8d4385eff773cc3766a2de7a26b3
668,885
import time def timeit(method): """ Decorator to time execution of transformers :param method: :return: """ def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() if 'log_time' in kw: name = kw.get('log_name', method.__nam...
774a62131de67427613dea0d5f6a1740721a0595
668,886
def stations_by_river(stations): """Takes a list of MonitoringStation objects and maps each station object (value) to its respective river (key). """ station_map = {} for station in stations: if station.river in station_map: station_map[station.river].add(station) els...
4972736fadbd6b3c545497f9bcf57d997551557e
668,888
import hashlib def sha1_hex_file(filepath, max_bytes=None): """ Returns the SHA1 of a given filepath in hexadecimal. Opt-args: * max_bytes. If given, reads at most max_bytes bytes from the file. """ sha1 = hashlib.sha1() f = open(filepath, 'rb') try: if max_bytes: ...
bf2b59eb9774dc5a4eb3c1bee26cebc7a3f84730
668,889
import argparse def parseArgs(): """ parse user input and return arguments """ parser = argparse.ArgumentParser(description = "Receive EIGER ZMQ frames and print receive time") parser.add_argument("-i", "--ip", help="EIGER host ip", type=str, required=True) parser.add_argument("-a", "--apiPor...
60272d14ac676646022b3c9cdf238f1fb0177183
668,890
def load_categories(file_name): """ Loads the category index from file. Each category label is the name of a class specified on a separate line. The entry order is the index of the class. """ labels = [] with open(file_name) as f: labels = f.read().splitlines() categories = {} ...
54bcd375c2e5b9d5d9078d6f0a75b9cebce03702
668,891