content
stringlengths
22
815k
id
int64
0
4.91M
def test_level_print_large_tree(large_tree): """Confirm the result of level_order_print of large_tree.""" result = print_level_order(large_tree) assert result == '12 \n 9 2 11 \n 1 3 99 \n 13 14 \n '
5,351,100
def pp_date(dt): """ Human-readable (i.e. pretty-print) dates, e.g. for spreadsheets: See http://docs.python.org/tutorial/stdlib.html e.g. 31-Oct-2011 """ d = date_to_datetime(dt) return d.strftime('%d-%b-%Y')
5,351,101
def write_template_vars(template_path, cb): """Passes file contents through a callable and writes the result to the file. Modifies the template_path inplace with results from passing its content through the callable: cb. Args: template_path: The path to the file to be read, processed and then written. ...
5,351,102
def optimizer_p(cd, path, i, obs, path_penalty): """Optimizer of the current path. Reduce the piece-wise path length in the free space of the environment.""" p_tmp = copy.deepcopy(path) p_tmp[i].x = p_tmp[i].x + cd[0] p_tmp[i].y = p_tmp[i].y + cd[1] r1 = math.sqrt((p_tmp[i-1].x - p_tmp[i].x)**2...
5,351,103
def create_message(sender_address, receiver_address , subject, email_content): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An o...
5,351,104
def retry_on_error(num_tries=5, retriable_exceptions=(socket.error, socket.gaierror, httplib.HTTPException)): """ Retries on a set of allowable exceptions, mimicking boto's behavior by default. :param num_tries: number of times to try before giving up. ...
5,351,105
def _write_query_function(fid: TextIO) -> None: """ Write the function needed to translate query parameters into a string. :param fid: target :return: """ fid.write('{-| Translates a list of (name, parameter) and a list of (name, optional parameter) to a\n') fid.write('well-formatted query ...
5,351,106
def test_application_audit_creation(): """Test Application History Model creation""" instance1 = ApplicationHistory(id=1, application_id=10, application_status="New", form_url="https://testsample.com/api/form/6100fae7ba5ac0627e9eefe6/submission/6101131fc325d44c1d846c13") ...
5,351,107
def handle_view_errors(func): """ view error handler wrapper # TODO - raise user related errors here """ @functools.wraps(func) def wrapper(*args, **kwargs): debug: bool = current_app.config.get('DEBUG') try: return func(*args, **kwargs) exce...
5,351,108
def main(notebook_mode=False,config=None): """ USER CONTROLS """ # terminal mode if notebook_mode==False: parser = argparse.ArgumentParser() parser.add_argument('--config', help="Please give a config.json file with training/model/data/param details") pa...
5,351,109
def test_string_dunder(): """Test that the vetter's string method behaves as expected. Note: We may choose to improve the string representation at some point """ v = DefaultVetter() v_str = str(v) # No metrics gets returned as an empty dictionary assert v_str == "{}", v_str # A metri...
5,351,110
def run_workflow_tasks( context, tasks, config_name ): """Run given list of workflow tasks with provided configuration within given `invoke` context. :param context: Invoke context. :type context: Context :param tasks: List of workflow tasks to run. :type tasks: list[str] :param...
5,351,111
def get_latest_revision_number(request, package_id): """ returns the latest revision number for given package """ package = get_object_or_404(Package, id_number=package_id) return HttpResponse(simplejson.dumps({ 'revision_number': package.latest.revision_number}))
5,351,112
def _make_mesh_tensors(inputs: Mapping[K, np.ndarray]) -> Mapping[K, tf.Tensor]: """ Computes tensors that are the Cartesian product of the inputs. This is around 20x faster than constructing this in Python. Args: inputs: A mapping from keys to NumPy arrays. Returns: A mapping fro...
5,351,113
def main(): """ You should write your code to make Karel do its task in this function. Make sure to delete the 'pass' line before starting to write your own code. You should also delete this comment and replace it with a better, more descriptive one. """ while front_is_clear(): repai...
5,351,114
def make_counters(): """Creates all of the VariantCounters we want to track.""" def _gt_selector(*gt_types): return lambda v: variantutils.genotype_type(v) in gt_types return VariantCounters([ ('All', lambda v: True), ('SNPs', variantutils.is_snp), ('Indels', variantutils.is_indel), ...
5,351,115
def curse( snapshot: PathLike, output_zip: PathLike, packmodes=None, force=False, mpm_filepath=None, ): """ Creates a .zip of the same format as curse/twitch that can be used to do a fresh install of the pack. This will *not* contain mods, but creates a manifest that list them (same ...
5,351,116
def connect_registry_client(): """ connect the module client for the Registry implementation we're using return the client object """ client = adapters.RegistryClient() client.connect(environment.service_connection_string) return client
5,351,117
def get_group_average_score(gid=None, name=None): """ Get the average score of teams in a group. Args: gid: The group id name: The group name Returns: The total score of the group """ group_scores = get_group_scores(gid=gid, name=name) total_score = sum([entry['scor...
5,351,118
def delete_transport_entry(sender, instance, **kwargs): """Delete a transport entry.""" tr_models.Transport.objects.filter( pattern="autoreply.{}".format(instance)).delete()
5,351,119
def solve_with_cdd_for_II(A, verbose=False): """This method finds II's minmax strategy for zero-sum game A""" m = A.shape[0] # number of rows n = A.shape[1] # number of columns A = np.column_stack([[0]*m,-A,[1]*m]) I = np.eye(n) nn = np.column_stack([[0]*n,I,[0]*n]) # non-negativity cons...
5,351,120
def build_none() -> KeySetNone: """Returns NONE.""" return KeySetNone()
5,351,121
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] for row in csv.reader(file): va...
5,351,122
def flip_around_axis( coords: np.ndarray, axis: Tuple[float, float, float] = (0.2, 0.2, 0.2) ) -> np.ndarray: """Flips coordinates randomly w.r.t. each axis with its associated probability.""" for col in range(3): if np.random.binomial(1, axis[col]): coords[:, col] = np.negat...
5,351,123
def get_tc(name): """Determine the amount of tile columns to use.""" args = ["ffprobe", "-hide_banner", "-select_streams", "v", "-show_streams", name] proc = sp.run(args, text=True, stdout=sp.PIPE, stderr=sp.DEVNULL) lines = proc.stdout.splitlines() d = {} for ln in lines[1:-1]: key, val...
5,351,124
def get_my_nodes(): """Get nodes assigned to this host for computation """ if not os.path.exists("/etc/cluster-hosts"): raise Exception("No cluster hosts specified") #grab list of hosts in cluster, in order hosts = [] with open("/etc/cluster-hosts", "r") as fp: for line in fp: hosts.append(line.strip()) ...
5,351,125
def register_final_images(folder, gene='Nuclei', sub_pic_frac=0.2, use_MPI=False, apply_to_corners=True, apply_warping = False, region=None, compare_in_seq=False): """Register stitched images an in all HDF5 file in the folder Loops ...
5,351,126
def cmap_hex_color(cmap, i): """ Convert a Colormap to hex color. Parameters ---------- cmap : matplotlib.colors.ListedColormap Represents the Colormap. i : int List color index. Returns ------- String Represents corresponding hex string. """ return ...
5,351,127
def train_folds(X, y, fold_count, batch_size, get_model_func): """ K-Fold Cross-Validation for Keras Models Inspired by PavelOstyakov https://github.com/PavelOstyakov/toxic/blob/master/toxic/train_utils.py """ fold_size = len(X[0]) // fold_count models = [] for fold_id in range(0, fold_co...
5,351,128
def reset_password(request): """ View to handle password reset """ helper.log_entrace(logger,request) postEmail = request.POST.get('email', '') try: import socket user = User.objects.get(email = postEmail) import os, random, string chars = string.ascii_letters ...
5,351,129
def test_get_only_value(test: test_pair): """Test function `get_only_value`.""" original = copy.deepcopy(test.input) result = get_only_value(test.input) assert original == test.input assert result == test.expected
5,351,130
async def cancel(command: HALCommandType, script: str): """Cancels the execution of a script.""" try: await command.actor.helpers.scripts.cancel(script) except Exception as err: command.warning(text=f"Error found while trying to cancel {script}.") return command.fail(error=err) ...
5,351,131
def get_nodes_by_betweenness_centrality(query_id, node_number): """Get a list of nodes with the top betweenness-centrality. --- tags: - query parameters: - name: query_id in: path description: The database query identifier required: true type: integer ...
5,351,132
def dump(data, path): """ Serialize data dict and write to file given by path where serialization is given by path's extension of either JSON, MsgPack, or CBOR for extension .json, .mgpk, or .cbor respectively """ if ' ' in path: raise IOError(f"Invalid file path '{path}' contains space...
5,351,133
def preprocess(function): """ Converts a given function from type str to a Sympy object. Keyword arguments: function -- a string type representation of the user's math function """ import sympy expr = function while True: if '^' in expr: expr =...
5,351,134
def tot_changes(changes: str) -> int: """Add deletions and insertions.""" insertions_pat = re.compile(r"(\d+) insertion") deletions_pat = re.compile(r"(\d+) deletion") insertions = insertions_pat.search(changes) insertions = int(insertions.group(1)) if insertions else 0 deletions = deletions_p...
5,351,135
def update_from_mcd(full_table, update_table): # type: (pd.DataFrame, pd.DataFrame) -> pd.DataFrame """ Update the full table (aka the PDG extended-style table) with the up-to-date information from the PDG .mcd file. Example ------- >>> new_table = update_from_mcd('mass_width_2008.fwf', 'ma...
5,351,136
def resolve_hostname(host): """Get IP address of hostname or URL.""" try: parsed = urlparse.urlparse(host) except AttributeError as err: error = "Hostname `%s`is unparseable. Error: %s" % (host, err) LOG.exception(error) raise errors.SatoriInvalidNetloc(error) # Domain n...
5,351,137
def DeconRNASeq_main(rna_df, sig_df, patient_IDs='ALL', args={}): """ This function does the following: - parses the dictionary 'args' for the arguments to pass on to the DeconRNASeq method. - eliminates genes from rna_df and sig_df that are not present in both data sets - Runs DeconRNAS...
5,351,138
def test_datetime_to_isoformat(): """Test the ``datetime_to_isoformat`` function.""" assert timezone.datetime_to_isoformat(None) is None assert isinstance(timezone.datetime_to_isoformat(timezone.now()), str)
5,351,139
def parse_c_interface(c_interface_file): """ @brief Parses a c-interface file and generates a dictionary of function names to parameter lists. Exported functions are expected to be preceded by 'DLL_EXPORT'. Python keywords should not be used as variable names for the function names in the cpp-interface ...
5,351,140
def con_minimize(fun, bounds, constr=(), x0=None, args=(), callback=None, options={}, workers=None): """Constrained minimization of `fun` using Genetic Algorithm. This function is a wrapper over modetga.minimize(). The constraints are defined as a tuple of functions (`fcon1(x, *args)`, `...
5,351,141
def unique_v2(lst): """ Returns a list of all unique elements in the input list "lst." This algorithm runs in o(n), as it only passes through the list "lst" twice """ dd = defaultdict(int) # avoids blank dictionary problem (KeyError when accessing nonexistent entries) unique_list = [] for va...
5,351,142
def is_ip_network(network, strict=False): """Returns True/False if a string is a valid network.""" network = str(network) try: ipaddress.ip_network(network, strict) return True except ValueError: return False
5,351,143
def assign_point_of_contact(point_of_contact): """ Assign a user to be the point of contact in emails/letters :param point_of_contact: A string containing the user_guid if point of contact has been set for a request :return: A User object to be designated as the point of contact for a request """ ...
5,351,144
def response_with_pagination(guests, previous, nex, count): """ Make a http response for GuestList get requests. :param count: Pagination Total :param nex: Next page Url if it exists :param previous: Previous page Url if it exists :param guests: Guest :return: Http Json response """ ...
5,351,145
def put_object(request, old_pid): """MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier.""" if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE: d1_gmn.app.auth.assert_create_update_delete_permission(request) d1_gmn.app.util.coerce_put_post(request) d1_gmn.app.views.assert_db....
5,351,146
def _match_gelu_pattern(gf, entry_node): """ Return the nodes that form the subgraph of a GELU layer """ try: if not len(entry_node.outputs) == 3: return None pow_1, add_2, mul_3 = [gf[x] for x in entry_node.outputs] if not (pow_1.op == 'Pow' and add_2.op == 'Add' and mul...
5,351,147
def assign_obs_error(param, truth_mag, band, run): """ Assign errors to Object catalog quantities Returns ------- obs_err : float or np.array The error values in units defined in get_astrometric_error(), get_photometric_error err_type : str Type of observational error ...
5,351,148
def dir_frequency(dirname: str, amount=50) -> List[Tuple[str, int]]: """Pipeline of word_frequency from a directory of raw input file.""" md_list = md.collect_md_text(dirname) return compute_frequency(tokenize(normalize(" ".join(md_list))), amount)
5,351,149
def test_solver1(N, version='scalar'): """ Very simple test case. Store the solution at every N time level. """ def I(x): return sin(2*x*pi/L) def f(x,t): return 0 solutions = [] # Need time_level_counter as global variable since # it is assigned in the action function (that makes ...
5,351,150
def get_auth_data(): """ Create auth data. Returns: return: access token and token expiring time. """ payload = { 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'client_credentials', } api_url = '{0}/oauth/access_token'.format(API_BASE...
5,351,151
def datatable(module, tag): """Mapping for DataTable.""" if tag == "DataTable": return module, tag
5,351,152
def remove_prepending(seq): """ Method to remove prepending ASs from AS path. """ last_add = None new_seq = [] for x in seq: if last_add != x: last_add = x new_seq.append(x) is_loopy = False if len(set(seq)) != len(new_seq): is_loopy = True ...
5,351,153
def github_handle_error(e): """ Handles an error from the Github API an error example: Error in API call [401] - Unauthorized {"message": "Bad credentials", "documentation_url": "https://docs.github.com/rest"} The error might contain error_code, error_reason and error_message The error_reason an...
5,351,154
def test_get_df_max_value(): """ Test Command ------------ $ python run_tests.py --module_name plot_playground.tests.test_data_helper:test_get_df_max_value --skip_jupyter 1 """ df = pd.DataFrame(data=[{ 'a': 100, 'b': 200, 'c': 300, }, { 'a': 50, ...
5,351,155
def netmask_to_bits(net_mask): """ Convert netmask to bits Args: net_mask ('str'): Net mask IP address ex.) net_mask = '255.255.255.255' Raise: None Returns: Net mask bits """ return IPAddress(net_mask).netmask_bits()
5,351,156
def register_corrector(cls=None, *, name=None): """A decorator for registering corrector classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _CORRECTORS: raise ValueError(f'Already registered model with name: {local_name}...
5,351,157
def write_video(stream): """ Write the entire content of the circular buffer to disk. No need to lock the stream here as we're definitely not writing to it simultaneously. """ logger.info("write_video") with io.open("before.h264", "wb") as output: for frame in stream.frames: if f...
5,351,158
def fetch(word): """given a single word, fix plural and singular - returning graph picks""" pass
5,351,159
def _sample_perc_from_list(lst, perc=100, algorithm="cum_rand", random_state=None): """ Sample randomly a certain percentage of items from the given list. The original order of the items is kept. :param lst: list, shape = (n,), input items :param perc: scalar, percentage to sample :param algo...
5,351,160
def irods_setacls(path, acl_list, verbose=False): """ This function will add the ACLs listed in 'acl_list' to the collection or data object at 'path'. 'acl_list' is a list where each element itself is a list consisting of the username in name#zone format, and the access level ('read', 'write', ...
5,351,161
def add_years(date_to_change, years): """ Return a date that's `years` years after the date (or datetime) object `date_to_change`. Return the same calendar date (month and day) in the destination year, if it exists, otherwise use the following day (thus changing February 29 to March 1). Args: ...
5,351,162
def concurrency_update_done(client, function_name, qualifier): """wait fn for ProvisionedConcurrencyConfig 'Status'""" def _concurrency_update_done(): status = client.get_provisioned_concurrency_config( FunctionName=function_name, Qualifier=qualifier )["Status"] if status ==...
5,351,163
def test_if_endless_max_rounds_is_valid(db, market_update_form_data): """ If endless = True, max_rounds can be chosen smaller than current round of the market """ market = MarketFactory(round=8) market_update_form_data['endless'] = True market_update_form_data['max_rounds'] = 5 form = MarketUpdateF...
5,351,164
def googleapis_email(url, params): """Loads user data from googleapis service, only email so far as it's described in http://sites.google.com/site/oauthgoog/Home/emaildisplayscope Parameters must be passed in queryset and Authorization header as described on Google OAuth documentation at: http://gr...
5,351,165
def _compose_query_string(ctx, query_string, **args): """ Return the SQL for an ad-hoc named query on the given context. NOTE: This is a debug ONLY method, do NOT use this in production code. """ query = _construct_adhoc_query(ctx, query_string, **args) wrapped_ctx = _CtxWrapper.wrap(ctx) as...
5,351,166
def get_img_full_path(path): """ Checks if file can be found by path specified in the input. Returns the same as input if can find, otherwise joins current directory full path with path from input and returns it. :param path: Relative of full path to the image. :return: Relative of full path to the imag...
5,351,167
def max_pool_2x2(input_): """ Perform max pool with 2x2 kelner""" return tf.nn.max_pool(input_, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
5,351,168
def remove_numerals(df, remove_mixed_strings=True): """Removes rows from an ngram table with words that are numerals. This does not include 4-digit numbers which are interpreted as years. Arguments: df {Pandas dataframe} -- A dataframe of with columns 'word', 'count'. Keyword Arguments: ...
5,351,169
def test_split_buffer_csi_parameter_no_intermediate(): """Split based on CSI with parameters bytes but no intermediate bytes. Up to 3 bytes.""" csi_up_to_sgr = range(int('40', 16), int('6d', 16)) csi_above_sgr = range(int('6e', 16), int('7f', 16)) for char_id in itertools.chain(csi_up_to_sgr, csi_a...
5,351,170
def freq_analysis_plot(sup_data, unsup_data_epoch1, unsup_data_epoch49, data_dict): """ :param unsup_data_epoch1: Unsupervised data for 1 epoch(dtype:pandas dataframe) :param unsup_data_epoch49: Unsupervised data for 1 epoch(dtype:pandas dataframe) :param sup_data: Supervised data(dtype:pandas dataframe...
5,351,171
def generate_json(args, df, num_changes, start_dt, finish_dt, projects, projects_map, not_found_proj, group=None, groups=[]): """ Returns json report from a dataframe for a specific project """ log.debug('Generating %s report for %s', args.report_format, group) lo...
5,351,172
def b32_ntop(*args): """LDNS buffer.""" return _ldns.b32_ntop(*args)
5,351,173
def get_logger(filename, logger_name=None): """set logging file and format Args: filename: str, full path of the logger file to write logger_name: str, the logger name, e.g., 'master_logger', 'local_logger' Return: logger: python logger """ log_format = "%(asctime)s %(message...
5,351,174
def infer_feature_extraction_pytorch( model: PreTrainedModel, run_on_cuda: bool ) -> Callable[[Dict[str, torch.Tensor]], torch.Tensor]: """ Perform Pytorch inference for feature extraction task :param model: Pytorch model (sentence-transformers) :param run_on_cuda: True if should be ran on GPU :...
5,351,175
def editRole(userSource, oldName, newName): """Renames a role in the specified user source. When altering the Gateway System User Source, the Allow User Admin setting must be enabled. Args: userSource (str): The user source in which the role is found. Blank will use the default use...
5,351,176
def flatsSingle(processes=6): """ Generates normalised flats at several wavelengths. Use all input files. """ #search for the right files files = findFiles() #generate flats using multiprocessing pool = Pool(processes=processes) pool.map(generateFlatsSingle, [(key, files[key]) for key i...
5,351,177
def compute_bspline_dot_product_derivatives(basis_features, basis_dimension): """ Compute dot products of B-splines and their derivatives. Input: - basis_features: dict Contain information on the basis for each state - basis_dimension: dict Give the number of basis f...
5,351,178
def create(the_model, extend_lengths, Emod=1.0, nu=0.3, thickness=1.e-9): """Create a dummy region by extending the rail at each side. Assign it a membrane section with parameters, thickness 0.01, Emod, and nu. .. note:: Requires that the meshed part, the_model.parts[names.rail_part] co...
5,351,179
def test_regex_ldr_mtd2(): """TEST REGEX_LDR_MTD2.""" print(REGEX_LDR_MTD2.match("LDR R3, [R4,R3]"), "Should pass mtd2")
5,351,180
def buffer_to_file(filename, data): """ Expects two strings: filename and data which will be written to the file """ file = open(filename, "a") file.write(data) file.close()
5,351,181
def validate_table(config, table): """Run VALVE validation on a table. :param config: valve config dictionary :param table: path to table :return: list of errors """ errors = [] table_name = os.path.splitext(os.path.basename(table))[0] table_details = config["table_details"] fields...
5,351,182
def beam_hardening_correction(mat, q, n, opt=True): """ Correct the grayscale values of a normalized image using a non-linear function. Parameters ---------- mat : array_like Normalized projection image or sinogram image. q : float Positive number. Recommended range [0.005, ...
5,351,183
def cargar_recursos_vectores_transpuestos(): """ Se carga la informacion para poder calcular los vectores transpuestos """ # Se crea el df filename = 'csv/' + conf.data['env']['path'] + '/vectores_transpuestos.csv' recursos_v_transpuestos = pd.read_csv(filename) # Se cambia el nombre de los ...
5,351,184
def eric_authors_and_editors(): """Check «Автор(ы), редакторы и рецензенты (если есть) материалов источника(ов):».""" yield from eric_head( 'Автор(ы), редакторы и рецензенты (если есть) материалов источника(ов):')
5,351,185
def read_pdb(file_name, exclude=('SOL',), ignh=False, modelidx=1): """ Parse a PDB file to create a molecule. Parameters ---------- filename: str The file to read. exclude: collections.abc.Container[str] Atoms that have one of these residue names will not be included. ignh: ...
5,351,186
def sao_isomorficas(texto1: str, texto2: str) -> bool: """ >>> sao_isomorficas('egg', 'add') True >>> sao_isomorficas('foo', 'bar') False >>> sao_isomorficas('eggs', 'add') False """ # Algoritmo O(n) em tempo e memória letras_encontradas = {} if len(texto1) != len(texto2): ...
5,351,187
def _is_no_args(fn): """Check if function has no arguments. """ return getargspec(fn).args == []
5,351,188
def failure(parsed_args): """ :param :py:class:`argparse.Namespace` parsed_args: :return: Nowcast system message type :rtype: str """ logger.critical( f"{parsed_args.model_config} {parsed_args.run_type} FVCOM VH-FR run for " f'{parsed_args.run_date.format("YYYY-MM-DD")} ' ...
5,351,189
def headers_url_generator(resp, fuzzable_req): """ Yields tuples containing: * Newly found URL * The FuzzableRequest instance passed as parameter * The HTTPResponse generated by the FuzzableRequest * Boolean indicating if we trust this reference or not The newly found URLs a...
5,351,190
def good_AP_finder(time,voltage): """ This function takes the following input: time - vector where each element is a time in seconds voltage - vector where each element is a voltage at a different time We are assuming that the two vectors are in correspondance (meaning ...
5,351,191
def parse(excel_sheets: Dict[Any, pd.DataFrame], dictionary: Dict[str, Any], verbose: bool = False) -> pd.DataFrame: """Parse sheets of an excel file according to instructions in `dictionary`. """ redux_dict = recursive_traverse(dictionary) column_tuples = redux_dict.keys() ...
5,351,192
def build_LAMP(prob,T,shrink,untied): """ Builds a LAMP network to infer x from prob.y_ = matmul(prob.A,x) + AWGN return a list of layer info (name,xhat_,newvars) name : description, e.g. 'LISTA T=1' xhat_ : that which approximates x_ at some point in the algorithm newvars : a tuple of layer-...
5,351,193
def coeffVar(X, precision=3): """ Coefficient of variation of the given data (population) Argument: X: data points, a list of int, do not mix negative and positive numbers precision (optional): digits precision after the comma, default=3 Returns: float, the cv (measure of dispers...
5,351,194
def tostring(node): """ Generates a string representation of the tree, in a format determined by the user. @ In, node, InputNode or InputTree, item to turn into a string @ Out, tostring, string, full tree in string form """ if isinstance(node,InputNode) or isinstance(node,InputTree): return node.p...
5,351,195
def pick_char_from_dict(char: str, dictionary: Dict[str, str]) -> str: """ Picks a random format for the givin letter in the dictionary """ return random.choice(dictionary[char])
5,351,196
def bmeow_to_bilou(tags: List[str]) -> List[str]: """Convert BMEOW tags to the BILOU format. Args: tags: The BMEOW tags we are converting Raises: ValueError: If there were errors in the BMEOW formatting of the input. Returns: Tags that produce the same spans in the BILOU forma...
5,351,197
def site_sold_per_category(items): """For every category, a (site, count) pair with the number of items sold by the site in that category. """ return [(site, [(cat, total_sold(cat_items)) for cat, cat_items in categories]) for site, categories in categ...
5,351,198
def assert_(val: numpy.bool_): """ usage.scipy: 503 usage.skimage: 58 """ ...
5,351,199