content
stringlengths
22
815k
id
int64
0
4.91M
def test_edit_format(sp, tempfile, setup_edit_patches, cleandir, fake_db, funk_dict): """Tests that the edit command reformats command strings when needed.""" edited_cmd_string = 'EDITED CMD STRING' setup_edit_patches(sp, tempfile, edited_cmd_string) some_funk = list(funk_dict.keys())[0] cmd = com...
17,800
def test_alert_get_by_id_command(mocker, grafana_client): """ Given: - All relevant arguments for the command that is executed When: - alert-get-by-id command is executed Then: - The http request is called with the right arguments """ http_request = mocker.patch.object(...
17,801
def log(message, cmap="INFO", type=None, verbosity_check=False, **kwargs): """Utility function to log a `message` to stdout Args: message (typing.Any): an object that supports `__str__()` cmap (str, optional): what colormap to use. "INFO" corresponds to blue, "WARN" Defaults to "IN...
17,802
def get_psi_part(v, q): """Return the harmonic oscillator wavefunction for level v on grid q.""" Hr = make_Hr(v + 1) return N(v) * Hr[v](q) * np.exp(-q * q / 2.0)
17,803
def get_tempdir() -> str: """Get the directory where temporary files are stored.""" return next((os.environ[var] for var in ( 'XDG_RUNTIME_DIR', 'TMPDIR', 'TMP', 'TEMP' ) if var in os.environ), '/tmp')
17,804
def get_pij(d, scale, i, optim = "fast"): """ Compute probabilities conditioned on point i from a row of distances d and a Gaussian scale (scale = 2*sigma^2). Vectorized and unvectorized versions available. """ if optim == "none": # # TO BE DONE # re...
17,805
def print_stack_trace(): """Print the current stack trace""" for line in traceback.format_stack(): print(line.strip())
17,806
def makePlot(counts, files): """ It takes the list with files names and list with alle the counts. Then it loops through the count list and adds these to a bar object. The height calculates the bottom of the next bar so it gets stacked on top of each other. outside the loop the plt.bar object gets f...
17,807
def hash_file(path): """ Returns the hash of a file. Based on https://stackoverflow.com/questions/22058048/hashing-a-file-in-python """ # Return error as hash, if file does not exist if not os.path.exists(path): return f"error hashing file, file does not exist: {path}" # BUF_SIZE i...
17,808
def get_section_names(target_dir, dir_name, ext="wav"): """ Get section name (almost equivalent to machine ID). target_dir : str base directory path dir_name : str sub directory name ext : str (default="wav) file extension of audio files return : section_names :...
17,809
def get_user_input(prompt: str, current_setting: str): """ Get user input :param prompt: prompt to display :param current_setting: current value :return: """ if current_setting != '': print(f'-- Current setting: {current_setting}') use_current = '/return to use current' e...
17,810
def about(): """Provide a simple description of the package.""" msg =''' # ===== nbev3devsim, version: {__version__} ===== The `nbev3devsim` package loads a simple 2D robot simulator based on ev3devsim into a Jupyter notebook widget. You can test that key required packages are installed by running the command...
17,811
def storeCalibrationParams(summary, xyzOff, xyzSlope, xyzSlopeT): """Store calibration parameters to output summary dictionary :param dict summary: Output dictionary containing all summary metrics :param list(float) xyzOff: intercept [x, y, z] :param list(float) xyzSlope: slope [x, y, z] :param lis...
17,812
def class_is_u16_len(cls): """ Return True if cls_name is an object which uses initial uint16 length """ ofclass = loxi_globals.unified.class_by_name(cls) if not ofclass: return False if len(ofclass.members) < 1: return False m = ofclass.members[0] if not isinstance(m...
17,813
def uploadfile(ticket_id): """ Anexa um arquivo ao ticket. """ if "file" not in request.files: return "arquivo inválido" filename = request.files.get("file").filename maxfilesize = int(cfg("attachments", "max-size")) blob = b"" filesize = 0 while True: chunk = request...
17,814
def urlretrieve(url, path): """ Same as 'urllib.urlretrieve()', but with a nice reporthook to show a progress bar. If 'path' exists, doesn't download anything. Args: url (str): the url to retrieve path (str): the path where to save the result of the url """ if os.path.exist...
17,815
def split(data, train_ids, test_ids, valid_ids=None): """Split data into train, test (and validation) subsets.""" datasets = { "train": ( tuple(map(lambda x: x[train_ids], data[0])), data[1][train_ids], ), "test": (tuple(map(lambda x: x[test_ids], data[0])), data[...
17,816
def parse_value_file(path): """return param: [(value type, value)]""" data = {} samples = [x.strip("\n").split("\t") for x in open(path)] for row in samples: parameter = row[0] values = [x for x in row[1:] if x != SKIP_VAL] if values != []: if parameter not in data: ...
17,817
def fizzbuzz(num): """ >>> fizzbuzz(15) FizzBuzz 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz """ for num in range(num + 1): if num % 3 == 0 and num % 5 == 0: print('FizzBuzz') elif num % 3 == 0: ...
17,818
def WriteGroupedImages(info, group_name, images, blacklist = []): """ Write a group of partition images to the OTA package, and add the corresponding flash instructions to the recovery script. Skip any images that do not have a corresponding entry in recovery.fstab.""" for i in images: if i.name not in ...
17,819
def get_stop_words(stop_text, filename='ChineseStopWords.txt'): """读取指定停用词文件""" _fp = os.path.join(stopwords_path, filename) with open(_fp, 'r', encoding='utf-8') as f: lines = f.readlines() stop_words = [word.strip() for word in lines] if stop_text: input_stop_words = stop_text.stri...
17,820
def _is_comments_box(shape): """ Checks if this shape represents a Comments question; RECTANGLE with a green outline """ if shape.get('shapeType') != 'RECTANGLE': return False color = get_dict_nested_value(shape, 'shapeProperties', 'outline', 'outlineFill', 'solidFill', 'color', 'rgbColor') re...
17,821
def read_tree(path): """Returns a dict with {filepath: content}.""" if not os.path.isdir(path): return None out = {} for root, _, filenames in os.walk(path): for filename in filenames: p = os.path.join(root, filename) with open(p, 'rb') as f: out[os.path.relpath(p, path)] = f.read() ...
17,822
def test_solving_data_route_has_all_algorithms_at_each_complexity(testapp): """Test solving data route has all algorithms at each complexity.""" response = testapp.get("/api/data/solve") assert len(response.json) == 32 assert 'tree' in response.json['0'] assert 'greedy' in response.json['0'] ass...
17,823
def get_config(cfg, name): """Given the argument name, read the value from the config file. The name can be multi-level, like 'optimizer.lr' """ name = name.split('.') suffix = '' for item in name: assert item in cfg, f'attribute {item} not cfg{suffix}' cfg = cfg[item] ...
17,824
def get_current_frame_content_entire_size(driver): # type: (AnyWebDriver) -> ViewPort """ :return: The size of the entire content. """ try: width, height = driver.execute_script(_JS_GET_CONTENT_ENTIRE_SIZE) except WebDriverException: raise EyesError('Failed to extract entire size...
17,825
def conv_slim_capsule(input_tensor, input_dim, output_dim, layer_name, input_atoms=8, output_atoms=8, stride=2, kernel_size=5, padding='SAME', ...
17,826
def main(): """Main""" argument_spec = vmware_argument_spec() argument_spec.update( database=dict( type='dict', options=dict( max_connections=dict(type='int', default=50), task_cleanup=dict(type='bool', default=True), task_reten...
17,827
def p_op_mean0_update(prev_p_op_mean0: float, p_op_var0: float, op_choice: int): """0-ToM updates mean choice probability estimate""" # Input variable transforms p_op_var0 = np.exp(p_op_var0) # Update new_p_op_mean0 = prev_p_op_mean0 + p_op_var0 * ( op_choice - inv_logit(prev_p_op_mean0) ...
17,828
def register_deployable_on_tier(ts, deployable, attributes): """ Deployable registration callback. 'deployable' is from table 'deployables'. """ # Add a route to this deployable. pk = {'tier_name': deployable['tier_name'], 'deployable_name': deployable['deployable_name']} row = ts.get_table(...
17,829
def get_last_code(entry_point_name): """Return a `Code` node of the latest code executable of the given entry_point_name in the database. The database will be queried for the existence of a inpgen node. If this is not exists and NotExistent error is raised. :param entry_point_name: string :return...
17,830
def main(): """Primary S3 upload function.""" conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) # walk the source directory. Ignore .git and any file in IGNORE namelist = [] for root, dirs, files in os.walk(src_folder): dirs[:] = [d for d in dirs if d not in IGNORE_FOLDERS]...
17,831
def save_birthday_to_dynamodb(fields: dict) -> None: """ Saves birthday to dynamodb, with proper time and an auto generated unsubscribe key. :param fields: Fields to be saved in dynamodb. :return: None. """ dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('BirthdaysTable') t...
17,832
def digamma(x): """Digamma function. Parameters ---------- x : array-like Points on the real line out : ndarray, optional Output array for the values of `digamma` at `x` Returns ------- ndarray Values of `digamma` at `x` """ return _digamma(x)
17,833
def get_time_index_dataset_from_file(the_file: h5py.File) -> h5py.Dataset: """Return the dataset for time indices from the H5 file object.""" return the_file[TIME_INDICES]
17,834
def get_database_connection(): """Возвращает соединение с базой данных Redis, либо создаёт новый, если он ещё не создан.""" global _database if _database is None: database_password = os.getenv("DB_PASSWORD", default=None) database_host = os.getenv("DB_HOST", default='localhost') data...
17,835
def main(): """ Create the hdf5 file + datasets, iterate thriough the folders DICOM imgs Normalize the imgs, create mini patches and write them to the hdf5 file system """ with h5py.File(PREPROCESSED_PATH + str(PATCH_DIM) + 'x' + str(PATCH_DIM) + 'x' + str(NUM_SLICES) + '-patch.hdf5', 'w') as HDF5: # Datasets fo...
17,836
def is_feature_enabled(feature_name): """A short-form method for server-side usage. This method evaluates and returns the values of the feature flag, using context from the server only. Args: feature_name: str. The name of the feature flag that needs to be evaluated. Returns: ...
17,837
def str_to_size(size_str): """ Receives a human size (i.e. 10GB) and converts to an integer size in mebibytes. Args: size_str (str): human size to be converted to integer Returns: int: formatted size in mebibytes Raises: ValueError: in case size provided in invalid ...
17,838
def point_line_distance(point, line): """Distance between a point and great circle arc on a sphere.""" start, end = line if start == end: dist = great_circle_distance(point, start, r=1)/np.pi*180 else: dist = cross_track_distance(point, line, r=1) dist = abs(dist/np.pi*180) r...
17,839
def experiment(save_key, model, data_splits_file, batch_size, active_str, muxrate): """ This should be common code for all experiments """ exper_dir = config.exper_output (save_path, _, plot_save_path, model_scores_path, _, _ ) = utils_train.get_paths(exper_dir, save_key) model_sav...
17,840
def uniq_by(array, iteratee=None): """This method is like :func:`uniq` except that it accepts iteratee which is invoked for each element in array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array. The iteratee is invo...
17,841
def process_lvq_pak(dataset_name='lvq-pak', kind='all', numeric_labels=True, metadata=None): """ kind: {'test', 'train', 'all'}, default 'all' numeric_labels: boolean (default: True) if set, target is a vector of integers, and label_map is created in the metadata to reflect the mapping to th...
17,842
def StrToPtkns(path_string): """ The inverse of PtknsToStr(), this function splits a string like '/usr/local/../bin/awk' into ['usr','local','..','bin','awk']. For illustrative purposes only. Use text.split('/') directly instead.""" return orig_text.split('/')
17,843
def _check_symmgroup(autom, symmgroup): """Asserts that symmgroup consists of automorphisms listed in autom and has no duplicate elements.""" for el in symmgroup.to_array(): assert group.Permutation(el) in autom.elems assert symmgroup == symmgroup.remove_duplicates() assert isinstance(symmgrou...
17,844
def load_key(file, callback=util.passphrase_callback): # type: (AnyStr, Callable) -> EC """ Factory function that instantiates a EC object. :param file: Names the filename that contains the PEM representation of the EC key pair. :param callback: Python callback object that will be...
17,845
def glob_path_match(path: str, pattern_list: list) -> bool: """ Checks if path is in a list of glob style wildcard paths :param path: path of file / directory :param pattern_list: list of wildcard patterns to check for :return: Boolean """ return any(fnmatch(path, pattern) for pattern in pat...
17,846
def sample_df(df, col_name='family', n_sample_per_class=120, replace = False): """ samples the dataframe based on a column, duplicates only if the number of initial rows < required sample size """ samples = df.groupby(col_name) list_cls = df[col_name].unique() df_lst = [] for cls in li...
17,847
def inventory_user_policies_header(encode): """generate output header""" if encode == 'on': return misc.format_line(( base64.b64encode(str("Account")), base64.b64encode(str("UserName")), base64.b64encode(str("PolicyName")), base64.b64encode(str("Policy")) ...
17,848
def you_rock(N, R, d): """ N: int, number of samples, e.g., 1000. R: int, maximum feature value, e.g., 100. d: int, number of features, e.g., 3. """ numpy.random.seed() # re-random the seed hits = 0 for _ in range(N): X = numpy.random.randint(1, R, (8, d)) # generate...
17,849
def fields_dict(cls): """ Return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` cla...
17,850
def cdlxsidegap3methods( client, symbol, timeframe="6m", opencol="open", highcol="high", lowcol="low", closecol="close", ): """This will return a dataframe of upside/downside gap three methods for the given symbol across the given timeframe Args: client (pyEX.Client): Cl...
17,851
def add_execution_path(new_path): """ Add a path to sys.path With a given path - verify if path already in sys.path - if not add it With a given list of paths - do the same for each path :param path: a path or a list of paths to add :type path: str or unicode or list :return: N...
17,852
def process_triggers_task(**kwargs): """Task form - wraps call to testable function `fire_trigger_events` """ # Include within function as not all applications include the blueprint from portal.trigger_states.empro_states import fire_trigger_events fire_trigger_events()
17,853
def finditer(pattern, string, flags=0): """Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a match object. Empty matches are included in the result.""" return _pyre().finditer(pattern, string, flags)
17,854
def nufft_j(x, y, freq = None, period_max=1., period_min=.5/24, window=False, oversamp=10.): """ nufft_j(x, y, period_max=1., period_min=.5/24, window=False, oversamp=10.): Basic STFT algorithm for evenly sampled data """ srt = np.argsort(x) x = x[srt] # get sorted x, y arrays y =...
17,855
def logger(verbosity=levels['error'], log_file=None): """Create a logger which streams to the console, and optionally a file.""" # create/get logger for this instance logger = logging.getLogger(__name__) logger.setLevel(levels['debug']) fmt = logging.Formatter('%(asctime)s - %(levelname)s - %(messa...
17,856
def head(input_file, in_format, nrows): """ Convert tables between formats, optionally modifying column names in the tables """ # Guess format if not specified: if in_format.upper() == "AUTO": in_format = utils.guess_format(input_file) # Read PARQUET: if in_format.upper() == "PARQU...
17,857
def getNamespacePermissions(paths): """Get L{Namespace}s and L{NamespacePermission}s for the specified paths. @param paths: A sequence of L{Namespace.path}s to get L{Namespace}s and L{NamespacePermission}s for. @return: A C{ResultSet} yielding C{(Namespace, NamespacePermission)} 2-tuples fo...
17,858
def serialize_engine(engine, output_path: str): """ Serializes engine to store it on disk :param engine: engine to serialize :param output_path: path to save the engine :return: None """ assert os.path.exists(output_path) trt.utils.write_engine_to_file(output_path, engine.serialize()) ...
17,859
def plot(x, y, ey=[], ex=[], frame=[], kind="scatter", marker_option=".", ls="-", lw=1, label="", color="royalblue", zorder=1, alpha=1., output_folder="", filename=""): """ Erstellt einen Plot (plot, scatter oder errorbar). Parameters ---------- x : array-like x-Wert...
17,860
def find_nominal_hv(filename, nominal_gain): """ Finds nominal HV of a measured PMT dataset Parameters ---------- filename: string nominal gain: float gain for which the nominal HV should be found Returns ------- nominal_hv: int nominal HV """ f = h5py.File...
17,861
def parse_match(field, tokens): """Parses a match or match_phrase node :arg field: the field we're querying on :arg tokens: list of tokens to consume :returns: list of match clauses """ clauses = [] while tokens and tokens[-1] not in (u'OR', u'AND'): token = tokens.pop() ...
17,862
async def test_nersc_mover_do_work_no_results(config, mocker): """Test that _do_work goes on vacation when the LTA DB has no work.""" logger_mock = mocker.MagicMock() dwc_mock = mocker.patch("lta.nersc_mover.NerscMover._do_work_claim", new_callable=AsyncMock) dwc_mock.return_value = False p = NerscM...
17,863
def get_filesystem(namespace): """ Returns a patched pyfilesystem for static module storage based on `DJFS_SETTINGS`. See `patch_fs` documentation for additional details. The file system will have two additional properties: 1) get_url: A way to get a URL for a static file download 2) expire...
17,864
def sym_normalize_adj(adj): """symmetrically normalize adjacency matrix""" adj = sp.coo_matrix(adj) degree = np.array(adj.sum(1)).flatten() d_inv_sqrt = np.power(np.maximum(degree, np.finfo(float).eps), -0.5) d_mat_inv_sqrt = sp.diags(d_inv_sqrt) return adj.dot(d_mat_inv_sqrt).transpose().dot(d_...
17,865
def prepare_label(input_batch, new_size): """Resize masks and perform one-hot encoding. Args: input_batch: input tensor of shape [batch_size H W 1]. new_size: a tensor with new height and width. Returns: Outputs a tensor of shape [batch_size h w 21] with last dimension comprised of...
17,866
def test_quantity_pickelability(): """ Testing pickleability of quantity """ q1 = np.arange(10) * u.m q2 = pickle.loads(pickle.dumps(q1)) assert np.all(q1.value == q2.value) assert q1.unit.is_equivalent(q2.unit) assert q1.unit == q2.unit
17,867
def find_index_halfmax(data1d): """ Find the two indices at half maximum for a bell-type curve (non-parametric). Uses center of mass calculation. :param data1d: :return: xmin, xmax """ # normalize data between 0 and 1 data1d = data1d / float(np.max(data1d)) # loop across elements and sto...
17,868
def format_autoupdate_jira_msg( message_body: str, header_body: Optional[str] = None ) -> str: """ Format a JIRA message with useful headers. An "Automated JIRA Update" title will be added, as well as either a URL link if a ``BUILD_URL`` env variable is present, or a note indicating a manual ru...
17,869
def unbind_contextvars(*args): """ Remove keys from the context-local context. Use this instead of :func:`~structlog.BoundLogger.unbind` when you want to remove keys from a global (context-local) context. .. versionadded:: 20.1.0 """ ctx = _get_context() for key in args: ctx.po...
17,870
def _unescape_token(escaped_token): """Inverse of _escape_token(). Args: escaped_token: a unicode string Returns: token: a unicode string """ def match(m): if m.group(1) is None: return "_" if m.group(0) == "\\u" else "\\" try: return chr(int(m...
17,871
def create_option_learner(action_space: Box) -> _OptionLearnerBase: """Create an option learner given its name.""" if CFG.option_learner == "no_learning": return KnownOptionsOptionLearner() if CFG.option_learner == "oracle": return _OracleOptionLearner() if CFG.option_learner == "direct_...
17,872
def close() -> None: """ Should be called at the end of the program - however, not required unless Tensorboard is used """ global summary_writer if summary_writer: summary_writer.close()
17,873
def parse_foochow_romanized_phrase(phrase, allow_omit_ingbing = True): """Parse a dash-separated phrase / word in Foochow Romanized.""" syllables = phrase.strip().split('-') result = [] for syllable in syllables: try: parsed = FoochowRomanizedSyllable.from_string(syllable, allow_omi...
17,874
def set_surf_file(filename): """ Function prepares h5py file for storing loss function values :param filename: Filename of a surface file """ xmin, xmax, xnum = -1, 2, 20 ymin, ymax, ynum = -1, 2, 20 if filename.exists(): return with h5py.File(filename, 'a') as fd: xco...
17,875
async def kick(ctx, member : discord.Member): """| Kicks a member. Don't try this!""" try: await member.kick(reason=None) await ctx.send("🦵 Get lost, "+member.mention) # Kickee kickee, heheee XD except: await ctx.send("""Why should I? 🤷‍♂️""")
17,876
def _update(dict_merged: _DepDict, dict_new: _DepDict) -> _DepDict: """ Merge a dictionary `dict_new` into `dict_merged` asserting if there are conflicting (key, value) pair. """ for k, v in dict_new.items(): v = dict_new[k] if k in dict_merged: if v != dict_merged[k]: ...
17,877
def date_convert(value): """ 日期字符串转化为数据库的日期类型 :param value: :return: """ try: create_date = datetime.strptime(value, '%Y/%m/%d').date() except Exception as e: create_date = datetime.now().date() return create_date
17,878
def discriminator_txt2img_resnet(input_images, t_txt, is_train=True, reuse=False): """ 64x64 + (txt) --> real/fake """ # https://github.com/hanzhanggit/StackGAN/blob/master/stageI/model.py # Discriminator with ResNet : line 197 https://github.com/reedscot/icml2016/blob/master/main_cls.lua w_init = t...
17,879
def get_img_content(session, file_url, extension=None, max_retry=3, req_timeout=5): """ Returns: (data, actual_ext) """ retry = max_retry while retry > 0: try: response = session.get(file_url,...
17,880
def nextbus(a, r, c="vehicleLocations", e=0): """Returns the most recent latitude and longitude of the selected bus line using the NextBus API (nbapi)""" nbapi = "http://webservices.nextbus.com" nbapi += "/service/publicXMLFeed?" nbapi += "command=%s&a=%s&r=%s&t=%s" % (c,a,r,e) xml = minidom.parse...
17,881
def xml_translate(callback, value): """ Translate an XML value (string), using `callback` for translating text appearing in `value`. """ if not value: return value try: root = parse_xml(value) result = translate_xml_node(root, callback, parse_xml, serialize_xml) ...
17,882
def check_sc_sa_pairs(tb, pr_sc, pr_sa, ): """ Check whether pr_sc, pr_sa are allowed pairs or not. agg_ops = ['', 'MAX', 'MIN', 'COUNT', 'SUM', 'AVG'] """ bS = len(pr_sc) check = [False] * bS for b, pr_sc1 in enumerate(pr_sc): pr_sa1 = pr_sa[b] hd_types1 = tb[b]['ty...
17,883
def translate_resource_args(func): """ Decorator that converts Issue and Project resources to their keys when used as arguments. """ @wraps(func) def wrapper(*args, **kwargs): arg_list = [] for arg in args: if isinstance(arg, (Issue, Project)): arg_list.ap...
17,884
def nan_jumps_dlc(files, max_jump=200): """Nan stretches in between large jumps, assuming most of the trace is correct""" # copy the data corrected_trace = files.copy() # get the column names column_names = corrected_trace.columns # run through the columns for column in column_names: ...
17,885
def index(): """View: Site Index Page""" return render_template("pages/index.html")
17,886
def view( ctx, pathspec, hash=None, type=None, id=None, follow_resumed=False, ): """ View the HTML card in browser based on the pathspec.\n The pathspec can be of the form:\n - <stepname>\n - <runid>/<stepname>\n - <runid>/<stepname>/<taskid>\n """ car...
17,887
def export_transformed_profile(kind, scenario_info, grid, ct, filepath, slice=True): """Apply transformation to the given kind of profile and save the result locally. :param str kind: which profile to export. This parameter is passed to :meth:`TransformProfile.get_profile`. :param dict scenario_inf...
17,888
def test_multisurfstar_pipeline_cont_endpoint(): """Ensure that MultiSURF* works in a sklearn pipeline with continuous endpoint data""" np.random.seed(320931) clf = make_pipeline(MultiSURFstar(n_features_to_select=2, n_jobs=-1), RandomForestRegressor(n_estimators=100, n_jobs=-1)) ...
17,889
async def get_latest_digest_from_registry( repository: str, tag: str, credentials: Optional[meadowrun.credentials.RawCredentials], ) -> str: """ Queries the Docker Registry HTTP API to get the current digest of the specified repository:tag. The output of this function should always match the out...
17,890
def test_list_repository_contents(capsys, folder_data): """Test the `list_repository_contents` method.""" list_repository_contents(folder_data, path='', color=True) assert capsys.readouterr().out == 'file.txt\nnested\n'
17,891
def histogram(x, bins, bandwidth, epsilon=1e-10): """ Function that estimates the histogram of the input tensor. The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter. """ pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon) return p...
17,892
def revisions_upload(deployment_name, version_name, zip_path, format_): """Create a revision of a deployment version by uploading a ZIP. Please, specify the deployment package `<zip_path>` that should be uploaded. """ project_name = get_current_project(error=True) client = init_client() revis...
17,893
def file_deal(paths, set_list: list, list_search: list, list_enter: list, file_path: dict, clear_list: bool = False, pattern=r'^[.\n]*$', is_file=True, replace_str: str = '', names: dict = None): """ :param clear_list: is need clear the list :param paths: DirPicker path or FilePicker fil...
17,894
def load_variables(data, nvariables, variables): """TODO.""" for i in range(nvariables): # TODO: read types from struct? # TODO: byteswap only if system is little-endian buf = data[(27 * i):(27 * i + 8)] reverse_array(buf) variableId = np.frombuffer(buf, dtype=np.int64)[...
17,895
def generate_kam( kam_path: str ) -> nx.DiGraph: """ Generates the knowledge assembly model as a NetworkX graph. :param kam_path: Path to the file containing the source, relationship and the target nodes of a knowledge assembly model (KAM). :return: KAM graph as a NetworkX DiGraph. """ ...
17,896
def toDrive(collection, folder, namePattern='{id}', scale=30, dataType="float", region=None, datePattern=None, extra=None, verbose=False, **kwargs): """ Upload all images from one collection to Google Drive. You can use the same arguments as the original function ee.batch.export.imag...
17,897
def area(box): """Computes area of boxes. B: batch_size N: number of boxes Args: box: a float Tensor with [N, 4], or [B, N, 4]. Returns: a float Tensor with [N], or [B, N] """ with tf.name_scope('Area'): y_min, x_min, y_max, x_max = tf.split( value=box, num_or_size_splits=4, axis=-1...
17,898
def read(fn): """ return a list of the operating systems and a list of the groups in the given fingerbank config file """ cfg = parse_config_with_heredocs(fn) return create_systems_and_groups(cfg)
17,899