content
stringlengths
22
815k
id
int64
0
4.91M
def cluster_by_best_antecedent(document, predictions, threshold=0.5): """ Clusters the document's mentions by matching each with its best antecedent with a score above the 0.5 threshold. @arg predictions Mention-pair predictions. @arg threshold The classification threshold, above this value mention...
5,309,800
def test_clean_up_not_clean_up_with_negative_argument(nparray, tensor_key): """Test that clean_up don't remove if records remove_older_than is negative.""" db = TensorDB() db.cache_tensor({tensor_key: nparray}) db.tensor_db['round'] = 2 db.clean_up(remove_older_than=-1) db.tensor_db['round'] = ...
5,309,801
def max_pooling(x, pool_h, pool_w, stride): """Max pooling.""" validator.check_integer("stride", stride, 0, Rel.GT, None) num, channel, height, width = x.shape out_h = (height - pool_h)//stride + 1 out_w = (width - pool_w)//stride + 1 col = im2col(x, pool_h, pool_w, stride) col = col.reshap...
5,309,802
def multiple_process(distribute_list, partition_func, task_func, n_jobs, reduce_func, parameters): """ Args: distribute_list(list): The "data" list to be partitioned, such as a list of files which will be distributed among different tasks and each task process a part of the files. ...
5,309,803
def get_unique_pairs(pairs, return_indices=False) -> np.array: """Extract unique pairs.""" # idx: Indices in triples of unique pairs _, idx = np.unique(pairs, return_index=True, axis=0) sorted_indices = np.sort(idx) # uniquoe pairs where original order of triples is preserved unique_pairs = pai...
5,309,804
def test_correct_visa_kwarg(): """Confirm that the query_delay kwargs gets passed through to the VISA connection.""" instr = Instrument(adapter='ASRL1::INSTR', name='delayed', query_delay=0.5, visa_library='@sim') assert instr.adapter.connection.query_delay == approx(0.5)
5,309,805
def preprocess_data(tokenizer, task, batch_size, dev_batch_size, max_len, vocab, world_size=None): """Train/eval Data preparation function.""" label_dtype = 'int32' if task.class_labels else 'float32' truncate_length = max_len - 3 if task.is_pair else max_len - 2 trans = partial(convert_examples_to_feat...
5,309,806
def revSequence(channels, n_block): """Make a sequence of multiple reversible block Arguments: channels {[int]} -- [number of channels fixed] n_block {[int]} -- [Number of blocks] Returns: [nn.Module] -- [The reversible sequence] """ sequence = [] for i in range(n_block): sequence.append(revBlock(chan...
5,309,807
def main(): """Command line interface for echoing what is this all about""" print("trace-simexp version {}" .format(__version__)) print("Conduct simulation experiment for TRACE") print("") print("Please use the driver scripts for each of the desired phases:") print(" trace_simexp_prepro ...
5,309,808
def calculate_angle(v1, v2): """ Calculate the angle ([0, Pi]) between two vectors according to: p = u * v = |u||v|cos(a) Parameters ---------- v1 : arr v2 : arr Returns ------- angle : float The angle ([0, Pi]) between these two given vectors """ product = np...
5,309,809
def range_overlap(a_min, a_max, b_min, b_max): """ Neither range is completely greater than the other """ return (a_min <= b_max) and (b_min <= a_max)
5,309,810
async def test_form(hass): """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["handler"] == "ialarm_xr" assert result["data_sche...
5,309,811
def open_url(url): """ Opens a URL in a the default browser, no matter the platform. """ if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except ...
5,309,812
def add_arguments(parser): """Helper function to fill the parser object. Args: parser: Parser object Returns: None """ parser.add_argument('-m', '--model', help='which model?', default="NoisyGRUSeq2SeqWithFeatures", type=str) parser.add_argument...
5,309,813
def flip_errors(data): """Flip sign for lower boundary responses. :Arguments: data : numpy.recarray Input array with at least one column named 'RT' and one named 'response' :Returns: data : numpy.recarray Input array with RTs sign flipped wher...
5,309,814
def predict(patches, DEBUG): """ predict zebra crossing for every patches 1 is zc 0 is background """ #print(len(patches)) labels = np.zeros(len(patches)) index = 0 for Amplitude, theta in patches: mask = (Amplitude>25).astype(np.float32) h, b = np.histogram(theta[mask.astype(np....
5,309,815
def is_clone(nickname, hostmask, withdate=False): """ Checks whether a nickname is considered a clone by the bot. :param withdate: Whether to return a tuple containing both matches and the last timestamp of connection :param hostmask: Hostmask of user :param bot: bot instance :param nickname: Ni...
5,309,816
def test_online_reads_checkpoint(): """Test that online analysis reads the checkpoint correctly in all cases""" current_log_level = logger.level logger.setLevel(logging.ERROR) # Temporarily suppress some of the logging output raw_template_script = get_template_script() # Pair down the processing ...
5,309,817
def preview(df,preview_rows,preview_max_cols): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ assert type(df) is pd.DataFrame if preview_rows <= 0: preview_rows = 1 initial_max_cols = pd.get_option('display.max_columns') pd.set_option('displa...
5,309,818
def read_json(json_file_path: str) -> dict: """Takes a JSON file and returns a dictionary""" with open(json_file_path, "r") as fp: data = json.load(fp) return data
5,309,819
def _log10_cumulative_shmf(logmp, y0, m, xc, x0, kc, dy): """Differentiable kernel of the cumulative subhalo mass function.""" y = y0 + m * (logmp - x0) return _jax_sigmoid(logmp, xc, kc, y, y - dy)
5,309,820
def main_CL(): """ Command line parsing and and defaults methods """ parser = OptionParser(usage=usage(), version='%s'%version) parser.add_option("-c", "--cmd", dest="cmd", default="walk", help="Command type to use.") parser.add_option("-p", "--parm", dest="parm", default="", ...
5,309,821
def metric_prefix(input_width, input_height): """ output the calculation of you model :param input_width: :param input_height: :return: """ import tensorflow as tf from networks import get_network import os os.environ['CUDA_VISIBLE_DEVICES'] = '' input_node = tf.placeholder(...
5,309,822
def internal_token_encoder() -> TokenEncoder[InternalToken]: """Return InternalToken encoder with correct secret embedded.""" return TokenEncoder( schema=InternalToken, secret=INTERNAL_TOKEN_SECRET, )
5,309,823
def verify_and_renew_license(driver, license_num, valid_from_date, valid_to_date): """ Verify if the driver of the given license and update the license with the given dates. :type driver: :py:class:`pyqldb.driver.qldb_driver.QldbDriver` :param driver: An instance of the QldbDriver class. :type lic...
5,309,824
def _get_user_guide_directory(): """Returns absolute path to docs/ directory""" docsdir = os.path.join("docs", "user_guide") return os.path.abspath(docsdir)
5,309,825
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False): """ Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir ex...
5,309,826
def index(request): """ Serve view for home page """ return render(request, "index.html")
5,309,827
def get_env(pathname=None, *, profile_dir=None, prefix=None): """Read the BASH file and extract the variables. Currently this is done with pattern matching. Another way would be to run the BASH script as a subshell and then do a printenv and actually capture the variables :param pathname: if provided, use this ...
5,309,828
def integrate_procss_on_p4(): """Create scripte and run it. """ run_p4_integrate_content = "echo integrate_procss_on_p4()\n" for part in PARAM_BOX['parts']: from_path = "//components/%s/%s/..."% (part, PARAM_BOX["branch_from"]) to_path = "//components/%s/%s/..."% (part, PARAM_BOX["bra...
5,309,829
def dispatch_queue(loader): # type: (DataLoader) -> None """ Given the current state of a Loader instance, perform a batch load from its current queue. """ # Take the current loader queue, replacing it with an empty queue. queue = loader._queue loader._queue = [] # If a maxBatchSize...
5,309,830
def _get_property_types(layer: Layer) -> Tuple[str, ...]: """Given a GDAL Layer, return the non-geometry field types.""" layer_definition = layer.GetLayerDefn() type_codes = tuple( layer_definition.GetFieldDefn(index).GetType() for index in range(layer_definition.GetFieldCount()) ) r...
5,309,831
def TInt_GetKiloStr(*args): """ TInt_GetKiloStr(int const & Val) -> TStr Parameters: Val: int const & """ return _snap.TInt_GetKiloStr(*args)
5,309,832
def _PrintSymbolized(asan_input, arch): """Print symbolized logcat output for Asan symbols. Args: asan_input: list of input lines. arch: Target CPU architecture. """ asan_libs = _FindASanLibraries() # Maps library -> [ AsanParsedLine... ] libraries = collections.defaultdict(list) asan_log_lines...
5,309,833
def linear(x, n_units, scope=None, stddev=0.02, activation=lambda x: x): """Fully-connected network. Parameters ---------- x : Tensor Input tensor to the network. n_units : int Number of units to connect to. scope : str, optional Variable scope to use. stdd...
5,309,834
def version_control(conf): """ Place a database under migration control :param conf: conf dict """ sql_connection = conf.sql_connection try: _version_control(conf) except versioning_exceptions.DatabaseAlreadyControlledError, e: msg = (_("database '%(sql_connection)s' is alre...
5,309,835
def RadialSymmetryFunction(R, rc, rs, e): """Calculates radial symmetry function. B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_filters Parameters ---------- R: tf.Tensor of shape (B, N, M) Distance matrix. rc: float Interaction cutoff [Angstrom]. rs: float Gaussian dista...
5,309,836
def plot_curve(axis, params, train_column, valid_column, linewidth = 2, train_linestyle = "b-", valid_linestyle = "g-"): """ Plots a pair of validation and training curves on a single plot. """ model_history = np.load(Paths(params).train_history_path + ".npz") train_values = model_history[train_colu...
5,309,837
def set_magmoms( atoms: Atoms, elemental_mags_dict: Optional[Dict] = None, copy_magmoms: bool = True, mag_default: Optional[float] = 1.0, mag_cutoff: float = 0.05, ) -> Atoms: """ Sets the initial magnetic moments in the Atoms object. This function deserves particular attention. The fol...
5,309,838
def copy_distro_logo(distro_id): """Copy specific logo.png to distro folder.""" try: copyfile(f"{distros_dir}/{distro_id}/logo.png", f"{output_dir}/logos/{distro_id}.png") except FileNotFoundError: copyfile(f"{working_dir}/misc/fallback_logo.png", f"{output...
5,309,839
def round_list(x, digits=6): """helper for approximate tests, round a list""" if isinstance(x, csr_matrix): x = sparse_to_dense(x) return [round(_, digits) for _ in list(x)]
5,309,840
def iter_to_table(value): """Convert raw API responses to response tables.""" if isinstance(value, list): return _format_list(value) if isinstance(value, dict): return _format_dict(value) return value
5,309,841
def test_no_validator_defined(): """Check result value of decorated function is returned.""" assert decorated_f() == 'not a number'
5,309,842
def get_last_line(fn): """Returns the last line of a file Args: fn (str): File name of the file to read from """ with open(fn, 'r') as fin: for line in fin: pass return line
5,309,843
def _gen_tinynet(variant_cfg, channel_multiplier=1.0, depth_multiplier=1.0, depth_trunc='round', pretrained=False, **kwargs): """Creates a TinyNet model. """ arch_def = [ ['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'], ['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'...
5,309,844
def full_sdssmatch(img1,img2,inst,gmaglim=19): """ This function requires two stacked images, one each filter that will be used in solving the color equations. The purpose of this function is to first collect all of the SDSS sources in a given field using the ``odi.sdss_coords_full`` function. After...
5,309,845
def calcula_menor_caminho(nome, origem, destino): """Retorna o menor caminho entre os dois pontos.""" mapa = Mapa() rotas = Rota.objects.filter(nome=nome) for rota in rotas: mapa.add_ponto(rota.origem) mapa.add_rota(rota.origem, rota.destino, ...
5,309,846
def test_BC_left_extrap(fin_diff): """Tests for turbopy.computetools.FiniteDifference's BC_left_extrap method.""" N = fin_diff.owner.grid.num_points diag = np.append(0, np.ones(N-1)) above = np.append([0.0, 2.0], np.zeros(N-2)) above2 = np.append([0.0, 0.0, -1.0], np.zeros(N-3)) d = fin_diff.B...
5,309,847
def p_item(p): """asconfig_item : uag | hag | asg rule_item : uag_ref | hag_ref | calc_head """ p[0] = p[1]
5,309,848
def _main(provider, output_dir, group_by): """Generate RST docs for a given cloud provider's resources """ env = init(provider) logging.basicConfig(level=logging.INFO) output_dir = os.path.abspath(output_dir) provider_class = clouds[provider] # group by will be provider specific, supports ...
5,309,849
def dump_stack(region, profile, stack, force): """ Dump one stack to files :param region: aws region :param profile: aws profile name :param stack: stack type :param force: force overwrite :return: """ LOG.info("Loading remote stack %s", stack) remote = RemoteStack(stack, region,...
5,309,850
def init(): """ The root entrypoint for the ``wa_cli`` is ``wa``. This the first command you need to access the CLI. All subsequent subcommands succeed ``wa``. """ # Main entrypoint and initialize the cmd method # set_defaults specifies a method that is called if that parser is used parser = arg...
5,309,851
def configure_logging(): """ Initialization of the logging system for the framework :return: """ global LOG debug = ConfigHelper.get(CFS_GENERAL, "debug") if debug.lower() == "true": file_level = logging.DEBUG else: file_level = logging.INFO # Clean logs warnings...
5,309,852
def HasServices(proto_path): """Does a .proto file have any service definitions? Args: proto_path: path to .proto. Returns: True iff there are service definitions in the .proto at proto_path. """ with open(proto_path, 'r', encoding='utf8') as f: for line in f: if re.match(SERVICE_REGEX, li...
5,309,853
def test_update_job_schedule(mocker, test_update_job_schedule_fixture, test_get_job_schedule_fixture, test_io_job_fixture): # noqa: E501 """testing update_job_schedule.py""" mocker.patch("requests.Session.post", new=mock_response(test_io_job_fixture)) # noqa: E501 mocker.patch("requests.Session.get", new=...
5,309,854
def _remote_file_size(url=None, file_name=None, pn_dir=None): """ Get the remote file size in bytes. Parameters ---------- url : str, optional The full url of the file. Use this option to explicitly state the full url. file_name : str, optional The base file name. Use th...
5,309,855
def estimate_compression(model, data, nsamples, context, batch_size, verbose=False): """ Estimates the compression by sampling random subsequences instead of predicting all characters. NB: This doesn't work for GPT-2 style models with super-character tokenization, since the tokens and number of charact...
5,309,856
def test_get_retrying_requests_session(times): """ Test that retries are set properly for http(s):// adapters Most arguments are simply passed to Retry.__init__, test only basic functionality """ if times is not None: session = get_retrying_requests_session(times=times) else: se...
5,309,857
def brnaseq_no_sample_groups(): """Call this function when a user supplies a groups CSV that does not have any information for the samples in the FASTQ directory.""" msg = CREDITS + """---------- ERROR The groups CSV file that you supplied does not contain any information about the samples that were found ...
5,309,858
def OptionalLibraryDefines(): """ Work out what optional libraries have been asked for, and return the appropriate #define names, as a list. """ # Todo #2367 take out adaptivity, and replace with warning/error? possible_flags = {'cvode': 'CHASTE_CVODE', 'vtk': 'CHASTE_VTK', 'adaptivity': 'CHASTE...
5,309,859
def start_transfer(context, read_file_handle, data_size, write_file_handle=None, image_id=None, image_meta=None): """Start the data transfer from the reader to the writer. Reader writes to the pipe and the writer reads from the pipe. This means that the total transfer time boils down to the slower o...
5,309,860
def filter_by_distance(points, mindist=4): """Evaluate the distance between each pair os points in @points and return just the ones with distance gt @mindist Args: points(set of tuples): set of positions mindist(int): minimum distance Returns: set: set of points with a minimum distance be...
5,309,861
def read_point_cloud_log(path: str, row_size: int, double_precision: bool = True) -> np.ndarray: """Reads a .pcl file and containing x, y, z values specifying a point cloud.""" with open(path, 'rb') as f: data_type = np.double if double_precision else np.single data = np.fromfile(f, data_type) ...
5,309,862
def HLRBRep_CurveTool_Parabola(*args): """ :param C: :type C: Standard_Address :rtype: gp_Parab2d """ return _HLRBRep.HLRBRep_CurveTool_Parabola(*args)
5,309,863
def unique_variable_name(): """Creates a unique variable name. Useful when attempting to introduce a new token to see if it can fix specific cases of SyntaxError.""" name = uuid.uuid4() return "_%s" % name.hex
5,309,864
def impersonated_session_status(request): """ Adds variable to all contexts :param request: :return bool: """ return {"is_impersonated_session": is_impersonated_session(request)}
5,309,865
def random_dates(start, end, size): """ Generate random dates within range between start and end. Adapted from: https://stackoverflow.com/a/50668285 """ # Unix timestamp is in nanoseconds by default, so divide it by # 24*60*60*10**9 to convert to days. divide_by = 24 * 60 * 60 * 10**9 st...
5,309,866
def cleaner_unicode(string): """ Objective : This method is used to clean the special characters from the report string and place ascii characters in place of them """ if string is not None: return string.encode('ascii', errors='backslashreplace') else: return string
5,309,867
def transform_stamped_to_pq(msg): """Convert a C{geometry_msgs/TransformStamped} into position/quaternion np arrays @param msg: ROS message to be converted @return: - p: position as a np.array - q: quaternion as a numpy array (order = [x,y,z,w]) """ return transform_to_pq(msg.transform)
5,309,868
def test_match_complex_recursive_peg_rule_resolve(): """ Test that recursive match rules are properly resolved. """ grammar = """ calc: expression; factor: INT | ('(' expression ')'); term: factor (term_op factor)*; term_op: '*' | '/'; expressio...
5,309,869
def parse_args(): """Parsing command line arguments. """ parser = ArgumentParser() parser.add_argument('--postgres-pass', dest='postgres_pass', type=str, help='PostgreSQL user password', default='') parser.add_argument('--postgres-user', dest='postgres_user', type=str, ...
5,309,870
def run(bsuite_id: Text) -> Text: """Runs a BDQN agent on a given bsuite environment, logging to CSV.""" env = bsuite.load_and_record( bsuite_id=bsuite_id, save_path=FLAGS.save_path, logging_mode=FLAGS.logging_mode, overwrite=FLAGS.overwrite, ) num_features = 32 #fixed param now, TODO: ...
5,309,871
def recursive_module_dict(model: nn.Module) -> OrderedDict: """Recursively generates an OrderedDict representing the module structure in a nn.Module. :param model: The (sub-)module for which to generate the structure :type model: torch.nn.Module :return: Structure of the module :rtype: OrderedDict ...
5,309,872
def reduce_min(value, axis=0, name=None): """ For axis < rank computes the minimum of a tensor along the specifed axis. In the result the corresponding axis is dropped, i.e. the rank of the result tensore is smaller that the rank of the input tensor. if axis==rank, then the minimum will be computed over all...
5,309,873
def sparse_js_distance(p, q): """Compute the Jensen-Shannon distance between two discrete distributions. NOTE: JS divergence is not a metric but the sqrt of JS divergence is a metric and is called the JS distance. Parameters ---------- p : np.array probability mass array (sums to 1) ...
5,309,874
def key_or_none(value): """ Attempts to parse a value into an instance of an `ndb.Key`. :returns: None if value cannot be converted to an `ndb.Key`. """ if not value: return None if isinstance(value, str) and len(value) < 1: return None return ndb.Key(urlsafe=value)
5,309,875
def get_training_dataset(workspace, class_count, vocab, max_chapter_len=50, max_para_len=50): """ Get the GB h2 chapter training dataset. :param workspace: The workspace directory where the TFRecords are kept. :param class_count: The number of classes to be classified. :param vocab: the set of vocab...
5,309,876
def get_https_host(request): """Common enabler code for returning https urls This is to map links to HTTPS to avoid Mixed Content warnings from Chrome browsers SECURE_PROXY_SSL_HEADER is referenced because it is used in redirecting URLs - if it is changed it may affect this code. Using relative lin...
5,309,877
def copy_add_one(lst): """ Returns: copy of lst with 1 added to every element Example: add_one([1,2,3,1]) returns [2,3,4,2] Parameter lst: The list to copy Precondition: lst is a list of all numbers (either floats or ints) """ # Create an empty list accumulator # For each element x...
5,309,878
def start(action: QueryAction) -> Callable: """Initialize the query for a given action, ensuring no action has started.""" def wrapper(fn): def wrapped(self, *args, **kwargs): if self._action != QueryAction.unset: raise BuildError(f"query already started with {self._action.n...
5,309,879
def xtea_decrypt_all(data, key, endian="!"): """Decrypt a entire string using XTEA block cypher""" newdata = '' data_s = len(data) data_p = data_s%8 if data_p: data_pl = 8-data_p data+=(data_pl*chr(0)) data_s+=data_pl for i in xrange(data_s/8): block = data[i*8:(i*8)+8] newdata+=xtea_decrypt(...
5,309,880
def connect(): """ Connect to MySQL database """ global dbName global conn global cursor #Get MySQL Auth from Heroku ClearDB url urlparse.uses_netloc.append('mysql') url = urlparse.urlparse(os.environ['DATABASE_URL']) dbName = url.path[1:] try: conn = mysql.connector.connec...
5,309,881
def subprocess_call(args, cwd, capture_output=False, **kwargs): """Calls a subprocess, possibly capturing output.""" try: if capture_output: return subprocess.check_output(args, cwd=cwd, **kwargs) else: return subprocess.check_call(args, cwd=cwd, **kwargs) except subprocess.CalledProcessError:...
5,309,882
def _assert_and_sample(keys, actuals): """ Input: key - key for assert values, basename (+ '_sample') for sampled values. Output: None; asserts actuals then and assigns into global test_dict If key exists, assert dict expected value against provided actual value. Sample actual value ...
5,309,883
def enthalpy_Shomate(T, hCP): """ enthalpy_Shomate(T, hCP) NIST vapor, liquid, and solid phases heat capacity correlation H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 + 1/4*D*t^4 - E*1/t + F - H t (K) = T/1000.0 H_ref is enthalpy in kJ/mol at 298.15 K...
5,309,884
def test_downloads_only_once(toolchain_db, feed): """ Test Download Only Once """ boost_package = qitoolchain.qipackage.QiPackage("boost", version="1.42") feed.add_package(boost_package, with_path=False, with_url=True) with mock.patch.object(qisys.remote, "download") as mock_dl: with mock.patch....
5,309,885
def hz_to_mel(frequencies: Union[float, List[float], array], htk: bool = False) -> array: """Convert Hz to Mels This function is aligned with librosa. """ freq = np.asanyarray(frequencies) if htk: return 2595.0 * np.log10(1.0 + freq / 700.0) # Fill in the linear part ...
5,309,886
def _std_to_grib1_field_name(field_name, pressure_level_mb=None): """Converts field name from standard to grib1 format. :param field_name: Field name in standard format (must be accepted by `processed_narr_io.check_field_name`). :param pressure_level_mb: Pressure level (millibars). For surface fie...
5,309,887
def test_validator_entrypoint_expanded(tmp_path): """'entrypoint' param: expands the user-home prefix.""" tmp_path = pathlib.Path(str(tmp_path)) # comparisons below don't work well in Py3.5 fake_home = tmp_path / 'homedir' fake_home.mkdir() testfile = fake_home / 'testfile' testfile.touch(mod...
5,309,888
def toggle_mouse(key, value): """ I handle this outside of the original update_key() function, because I'm not sure otherwise how to handle key debouncing. If you hold down "m", you get a stream of "m" events, but when you release the key, you get an "m" event instead of an "m-up" event. ...
5,309,889
def get_package_index(url, session=setup_session()): """Return the Elm package index and also store it in PACKAGE_ROOT.""" logger.info('Fetching package index...') data = session.get(url).text with open(os.path.join(PACKAGE_ROOT, 'all-packages'), 'w') as out: out.write(data) return json.load...
5,309,890
def test_smokevirt_set_ham(): """Test --set-ham Note: Do a factory reset after this setting so it is very short-lived. """ return_value, out = subprocess.getstatusoutput('meshtastic --host localhost --set-ham KI1234') assert re.search(r'Setting Ham ID', out, re.MULTILINE) assert return_value ...
5,309,891
def remove_all_links(): """Remove (unlink) all link groups liked by create_links().""" for link_group, refcount in _refcounter.items(): if refcount == 0: continue _unlink_group(link_group) _refcounter.clear()
5,309,892
def delete_storage(conn, cluster): """Delete all storage objects in the cluster. This function uses RELEASE storage-requests to attempt to delete the CSP volumes corresponding to the storage objects. A DETACH operation is added to storage-requests for storage objects whose state reflects that they are a...
5,309,893
def get_acres(grid, coordinates): """Get acres from coordinates on grid.""" acres = [] for row, column in coordinates: if 0 <= row < len(grid) and 0 <= column < len(grid[0]): acres.append(grid[row][column]) return acres
5,309,894
def test_graph_nodes(new_graph): """Check to see if the nodes() method returns all nodes.""" assert new_graph.nodes() == [] new_graph.add_node('test') assert new_graph.nodes() == ['test'] new_graph.add_node('test2') new_graph.add_node('test3') new_graph.add_node('test18') new_graph.add_n...
5,309,895
def get_path_infos(path): """Get basic informations from a path""" path = fspath(path) path = os.path.abspath(path) path = pathlib.PurePath(path) return PathInfos( path.drive, str(path.parent), path.name, path.stem, path.suffix, os.path...
5,309,896
def key2num( objs: Iterable[Hashable], reverse_map: Optional[Dict[int, Any]] = None ) -> Iterator[int]: """ Given a sequence of hashable objects return sequence of numeric ids starting from 0. For example ``'A' 'B' 'A' 'A' 'C' -> 0 1 0 0 2`` """ o2id: Dict[Any, int] = {} c = 0 for obj i...
5,309,897
def reset_customization(page): """Reset workspace customizations for a user Args: page (string): Name of the page to be reset """ page_doc = get_custom_workspace_for_user(page) page_doc.delete()
5,309,898
def parse_noj(): """ Parsing Nojabrsk (NOJ) airport arrivals and departure data :return: list [list of dicts arrivals, list of dicts departures] """ print('parse_noj') json_data = get_json(NOJ_URL).get('result').get('response').get('airport').get('pluginData').get('schedule') arr_data = get...
5,309,899