content
stringlengths
22
815k
id
int64
0
4.91M
def add_to_table(axis, table, regions): """Add selected regions to a table.""" regions_to_add = table[table['region'].isin(regions)] regions_to_add['Trend'] = regions_to_add['Trend'].replace(np.nan, 0.00042) regions_to_add.sort_values(by=['region', 'Value'], ascending=[True, False], inplace=True) ad...
5,323,300
def test_apifail_inventory_dictimport_toomanysrcargs(): """Confirm error if >1 sources passed.""" with pytest.raises(RuntimeError): soi.Inventory(source="foo", plaintext="bar")
5,323,301
def reduce_to(n): """processor to reduce list""" def reduce(list): if len(list) < n: return n else: return list[0:n] return reduce
5,323,302
def render(renderer_name, value, request=None, package=None): """ Using the renderer ``renderer_name`` (a template or a static renderer), render the value (or set of values) present in ``value``. Return the result of the renderer's ``__call__`` method (usually a string or Unicode). If the ``rendere...
5,323,303
def write_cnn_weights(model, source_path, target_path, split, selection="best_acc"): """ Write the weights to be loaded in the model and return the corresponding path. :param model: (Module) the model which must be initialized :param source_path: (str) path to the source task experiment :param targ...
5,323,304
def validate(number): """Check if the number provided is a valid NCF.""" number = compact(number) if len(number) == 13: if number[0] != 'E' or not isdigits(number[1:]): raise InvalidFormat() if number[1:3] not in _ecf_document_types: raise InvalidComponent() elif ...
5,323,305
def upsampling_d1_batch_normal_act_subpixel(input_tensor, residual_tensor, filter_size, layer_number, active_function=tf.nn.relu, ...
5,323,306
def search_ws(sheet, search_term, distance=20, warnings=True, origin=[0,0], exact = False): """ Searches through an excel sheet for a specified term. The function searches along the bottom left to top right diagonals. The function starts at the "origin" and only looks for values below or to ...
5,323,307
def readfiles(meta): """ Reads in the files saved in datadir and saves them into a list Parameters ----------- meta metadata object Returns ---------- meta metadata object but adds segment_list to metadata containing the sorted data fits files Notes: ----------...
5,323,308
def obs_all_table_target_pairs_one_hot(agent_id: int, factory: Factory) -> np.ndarray: """One-hot encoding for each table target, NOT summed together; length: number of tables x number of nodes""" num_nodes = len(factory.nodes) num_tables = len(factory.tables) table_target_pair = np.zeros(num_nodes * nu...
5,323,309
def clean_up(text): """ This function clean up you text and generate list of words for each document. It also corrects for unicode problems with python version 2. """ import sys, spacy removal=['ADV','PRON','CCONJ','PUNCT','PART','DET','ADP','SPACE'] text_out = [] if sy...
5,323,310
def test_validate_valid_logfile(): """Call validate with a valid log file.""" log_file = "scratch/example.log" result = logtailor.validate_log(False, log_file, {}) assert result == [Path(log_file)]
5,323,311
def logger(name): """ This method is the preferred way to obtain a logger. Example: >>> from qiutil.logging import logger >>> logger(__name__).debug("Starting my application...") :Note: Python ``nosetests`` captures log messages and only reports them on failure. :...
5,323,312
def severe_obesity_wfl(gender, length, weight, units='metric', severity=1): """ Returns a boolean indicator for a zscore determining if the reading is classified as severely obese from: https://jamanetwork.com/journals/jamapediatrics/fullarticle/2667557. NOTE: This should only be used for children under...
5,323,313
def calc_Flesh_Kincaid_Grade_rus_flex(n_syllabes, n_words, n_sent): """Метрика Flesh Kincaid Grade для русского языка с константными параметрами""" if n_words == 0 or n_sent == 0: return 0 n = FLG_X_GRADE * (float(n_words) / n_sent) + FLG_Y_GRADE * (float(n_syllabes) / n_words) - FLG_Z_GRADE return n
5,323,314
def advance_coaching_staff(team, year): """ Takes an existing coaching staff, minus any who have an end_date value, and creates new CollegeCoach records for them in the provided year. Usage: >>> from fumblerooski.utils import advance_coaching_staff >>> from fumblerooski.college.models impor...
5,323,315
def psd(x: np.ndarray, delf: float, type_psd: list, n: float = None) -> np.ndarray: """Returns 2d array of PSD computed with specified method Args: x (np.ndarray): Values in time domain delf (float): Sampling Rate type (list): [x, y] x=0 psd, x=1 psd density && y=0 standard psd, y=1 wel...
5,323,316
def comment(request): """留言功能""" if request.method == "POST": form = CommentForm(request.POST) blog_id = request.POST["blog_id"] user = request.user if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = user new_commen...
5,323,317
def calculate_height_filtration( graph, direction, attribute_in='position', attribute_out='f', ): """Calculate height filtration of a graph in some direction. *Note*: This function works for *all* vector-valued attributes of a graph, but in the following, it will be assumed that those a...
5,323,318
def read_file(file_name, encoding='utf-8'): """ 读文本文件 :param encoding: :param file_name: :return: """ with open(file_name, 'rb') as f: data = f.read() if encoding is not None: data = data.decode(encoding) return data
5,323,319
def test_event_manager_publish(): """Test that EventManager publishing to clients works""" saved_data = { "user_id": None, "title": "asdf", "content": "asdf", "team_id": None, "user": None, "team": None, "date": "2019-01-28T01:20:46.017649+00:00", ...
5,323,320
def cbf_qei(gm, wm, csf, img, thresh=0.8): """ Quality evaluation index of CBF base on Sudipto Dolui work Dolui S., Wolf R. & Nabavizadeh S., David W., Detre, J. (2017). Automated Quality Evaluation Index for 2D ASL CBF Maps. ISMR 2017 """ def fun1(x, xdata): d1 = np.exp(-(x[0])*np.po...
5,323,321
def test_rpt(prt=sys.stdout): """Read in a small obo, print list of GO terms and plot.""" png = "i86_godag.png" gosubdag = _get_gosubdag() _prt_goids(gosubdag, prt) goobjplt = _get_goobjplt(gosubdag) goobjplt.plt_dag(png)
5,323,322
def print_log(value_color="", value_noncolor=""): """set the colors for text.""" HEADER = '\033[92m' ENDC = '\033[0m' print(HEADER + value_color + ENDC + str(value_noncolor))
5,323,323
def plot_perplexity(perplexities): """plot perplexities""" plt.title("Perplexity per Epoch") plt.xlabel("Epoch") plt.ylabel("Perplexity") plt.plot(perplexities)
5,323,324
def calendar(): """page for all events""" events = get_all_events(sqlite3.connect(DB_NAME).cursor()) return render_template("calendar.html", events=events)
5,323,325
def test_symmetric_extension_hierarchy_three_bell_with_resource_state(): """Symmetric extension hierarchy for three Bell and resource state.""" e_0, e_1 = basis(2, 0), basis(2, 1) e_00, e_11 = np.kron(e_0, e_0), np.kron(e_1, e_1) eps = 1 / 2 eps_state = np.sqrt((1 + eps) / 2) * e_00 + np.sqrt((1 - ...
5,323,326
def _ui_device_family_plist_value(ctx): """Returns the value to use for `UIDeviceFamily` in an info.plist. This function returns the array of value to use or None if there should be no plist entry (currently, only macOS doesn't use UIDeviceFamily). Args: ctx: The Skylark context. Returns: ...
5,323,327
def map_amplitude_grid( ds_ind, data_columns, stokes='I', chunk_size:int=10**6, return_index:bool=False ): """ Map functions to a concurrent dask functions to an Xarray dataset with pre-computed grid indicies. Parameters ---------- ds_ind : xarray.dataset An...
5,323,328
def fetch_query(query, columns): """ Creates a connection to database, returns query from specified table as a list of dictionaries. Input: query: a SQL query (string) Returns: pairs: dataframe of cursor.fetchall() response in JSON pairs """ # Fetch query response = fetch_query_records(q...
5,323,329
def fetch(key): """Gets snapshots referenced by the given instance template revision. Args: key: ndb.Key for a models.InstanceTemplateRevision entity. Returns: A list of snapshot URLs. """ itr = key.get() if not itr: logging.warning('InstanceTemplateRevision does not exist: %s', key) retur...
5,323,330
def run_train(): """run train""" args = parse_args() # INIT device_id = int(os.getenv('DEVICE_ID', '0')) device_num = int(os.getenv('RANK_SIZE', '1')) rank_id = int(os.getenv('RANK_ID', '0')) if args.platform == "Ascend": context.set_context(mode=context.GRAPH_MODE, device_target="...
5,323,331
def CreateNameToSymbolInfo(symbol_infos): """Create a dict {name: symbol_info, ...}. Args: symbol_infos: iterable of SymbolInfo instances Returns: a dict {name: symbol_info, ...} If a symbol name corresponds to more than one symbol_info, the symbol_info with the lowest offset is chosen. """ ...
5,323,332
def test_read_huge_file(): """ Verifies if read_file function can read a big file and return its size """ x = read_file('tests/huge_net_tcp') assert len(x) == 49801
5,323,333
def EFI(data, period=13): """ Elder Force Index EFI is an indicator that uses price and volume to assess the power behind a move or identify possible turning points. :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :param int period: period used for indicator calcula...
5,323,334
def Gdelta(GP, testfunc, firstY, delta=0.01, maxiter=10, **kwargs): """ given a GP, find the max and argmax of G_delta, the confidence-bounded prediction of the max of the response surface """ assert testfunc.maximize mb = MuBound(GP, delta) _, optx = cdirect(mb.objective, testfunc.bounds, m...
5,323,335
def xirrcal(cftable, trades, date, startdate=None, guess=0.01): """ calculate the xirr rate :param cftable: cftable (pd.Dateframe) with date and cash column :param trades: list [trade1, ...], every item is an trade object, whose shares would be sold out virtually :param date: string of date...
5,323,336
def calc_synch_kappa(b, ne, delta, sinth, nu, E0=1.): """Calculate the relativstic synchrotron absorption coefficient κ_ν. This is Dulk (1985) equation 41, which is a fitting function assuming a power-law electron population. Arguments are: b Magnetic field strength in Gauss ne The den...
5,323,337
async def app_init(): """Initialize application services""" # Init Database client = AsyncIOMotorClient(CONFIG.mongo_uri) app.db = client[CONFIG.database] await init_beanie(app.db, document_models=[Addon, Plan, TokenUsage, User]) # Init error logging if CONFIG.log_key: rollbar.init(C...
5,323,338
def random_rotation(): """Generate a 3D random rotation matrix. Returns: np.matrix: A 3D rotation matrix. """ x1, x2, x3 = np.random.rand(3) R = np.matrix([[np.cos(2 * np.pi * x1), np.sin(2 * np.pi * x1), 0], [-np.sin(2 * np.pi * x1), np.cos(2 * np.pi * x1), 0], ...
5,323,339
def visualize(G, bqm, sampleset, problem_filename, solution_filename): """ Creates and saves plots that show the problem and solution returned in the lowest energy sample in the sampleset. It also prints the solution in a bipartite layout with the filename bipartite_solution_filename. Args: G: ...
5,323,340
def plot_channel_slopes_uniform_lithology(DataDirectory, fname_prefix, river_csv, labels_csv, stream_order): """ Read in the channel slope csv file and plot the slopes separated by lithology """ # csv with the river profiles river_df = pd.read_csv(river_csv) #remove negative channel slopes ...
5,323,341
def outdir_project(outdir, project_mode, pd_samples, mode): """ """ # Group dataframe by sample name sample_frame = pd_samples.groupby(["new_name"]) dict_outdir = {} for name, cluster in sample_frame: if (project_mode): #print ("Create subdir for every sample: ", mode) sample_dir = create_subfolder('dat...
5,323,342
def _get_percentage_bid_offer(df_with_positions, day, daily_spread_percent_override): """Defines the daily spread used in computation.""" if daily_spread_percent_override is not None: daily_spread_percentage = daily_spread_percent_override else: try: daily_spread_percentage = df_...
5,323,343
def getChoice(options: list): """ Only for Windows and MacOS """ # showOptions = '\n'.join(options) # print(showOptions) print("操作選項") for i in range(len(options)): print(f"{i+1}. {options[i]}") choice = input(': ') clearScene() return choice
5,323,344
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean IU - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += fast_hist(lt.flatten(), lp...
5,323,345
def get_storcli_dall_show(c): """ Gets data from json resource :param c: unused :return: """ del c with open(os.path.join(os.path.dirname(__file__), '../resources/storcli_dall_show.json')) as fp: data = json.load(fp) controller_list = [] for c...
5,323,346
def unblock(**kwargs): """Unblock an API key.""" _validate_filters_or_die(kwargs, unblock) _toggle_api_key_block(False, **kwargs)
5,323,347
def test_sharpness(): """Test function for the sharpness calculation of an audio signal Test function for the function "comp_roughness" with 'din' method. The input signals come from DIN 45692_2009E. The compliance is assessed according to chapter 6 of the standard. One .png compliance plot is gene...
5,323,348
def test_single_text_to_text(): """ Just make sure the test_plot function doesn't crash. """ class MockTextExplanation: # pylint: disable=too-few-public-methods """ Fake explanation object. """ def __init__(self, data, values, output_names, base_values, clustering, hierarchical_valu...
5,323,349
def Update(name, notification_emails, enrolled_services, update_mask): """Get the access approval settings for a resource. Args: name: the settings resource name (e.g. projects/123/accessApprovalSettings) notification_emails: list of email addresses enrolled_services: list of services update_mask: ...
5,323,350
def main(): """ Calculates and prints the mean values for the RGB channels in a dataset """ dataset_builder = DatasetBuilder() dataset = dataset_builder.build_kitti_dataset( dataset_builder.KITTI_TRAIN # dataset_builder.KITTI_TRAIN_MINI ) # Options debug_print = True ...
5,323,351
def merge(inputs: Sequence[str], output: TextIO, reconcile: bool = True): """Merge msdf2 into msdf1. if reconcile=True, then dedupe(remove redundant lower confidence mappings) and reconcile (if msdf contains a higher confidence _negative_ mapping, then remove lower confidence positive one. If c...
5,323,352
def training(request): """Renders the training page.""" assert isinstance(request, HttpRequest) return render( request, 'magic/training.html', { 'title':'Training', 'year':datetime.now().year, } )
5,323,353
def main(source: str, remove: bool = False, export_meshblock: bool = False) -> None: """ Instantiates and executes the CRN class. :param str source: abbreviation for the source province / territory. :param bool remove: remove pre-existing output file (validations.log), default False. :param bool ex...
5,323,354
def compute_similarity(): """ Computes Cosine Similarity between movies. Yields ------ cosine_similarity_scores.csv """ movie_data = pd.read_csv("movie_recsys/datasets/movie_data.csv") # Compute TF-IDF representation. tfidf = TfidfVectorizer(stop_words="english") tfidf_matr...
5,323,355
def MOP( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2022-02-01", **kwargs ) -> Graph: """Ret...
5,323,356
def stetson_sharpness(temp, middle, mask, d): """Stetson compute of sharpness.""" mask = np.array(mask) # work with a copy mask[middle, middle] = 0 sharp = temp[middle, middle] - (np.sum(mask*temp))/np.sum(mask) with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning)...
5,323,357
def add_variant_to_variant_set(prim, variant_set_name, variant_name): """ Adds a new variant to given variant set in prim :param prim: Usd.Prim :param variant_set_name: str :param variant_name: str :return: Usd.Variant """ variant_set = get_variant_set(prim, variant_set_name) if not...
5,323,358
def load_data(messages_filepath, categories_filepath): """ Load messages_file and categories_file Args: messages_filepath: csv file with the disaster messages categories_filepath: csv file with the categories for disaster messages Returns: a file that is merge of the two input files ...
5,323,359
def writeUnusedEntries(dictionary, outFile): """ Write all entries in a dictionary that are not marked 'used'.""" if (len(dictionary.keys()) == 0): return for key in dictionary.keys(): for entry in dictionary[key]: if not entry.used: outFile.write(entry.origLine)
5,323,360
def _cmd(cmd): """Utility function to run commands.""" result = __salt__["cmd.run_all"](cmd) if result["retcode"]: raise CommandExecutionError(result["stdout"] + result["stderr"]) return result["stdout"]
5,323,361
def min( x: Union[ivy.Array, ivy.NativeArray], axis: Union[int, Tuple[int]] = None, keepdims: bool = False, out: Optional[Union[ivy.Array, ivy.NativeArray]] = None, ) -> ivy.Array: """Calculates the minimum value of the input array x. .. note:: When the number of elements over which to comp...
5,323,362
def bkg_3d(): """Example with simple values to test evaluate""" energy = [0.1, 10, 1000] * u.TeV energy_axis = MapAxis.from_energy_edges(energy) fov_lon = [0, 1, 2, 3] * u.deg fov_lon_axis = MapAxis.from_edges(fov_lon, name="fov_lon") fov_lat = [0, 1, 2, 3] * u.deg fov_lat_axis = MapAxis.f...
5,323,363
def pd_read_pickle(fname): """ Read the :class:`.PupilData`-object `pdobj` from file using :mod:`pickle`. Parameters ---------- fname: str filename or URL to load data from Returns ------- pdobj: :class:`.PupilData` loaded dataset """ if f...
5,323,364
def migrate( ctx, ): """Migrate an old loqusdb instance to 1.0""" adapter = ctx.obj["adapter"] start_time = datetime.now() nr_updated = migrate_database(adapter) LOG.info( "All variants updated, time to complete migration: {}".format(datetime.now() - start_time) ) LOG.info("Nr...
5,323,365
def checkLevel(n): """ Check if a level, identified by its name, exists return : - Boolean call example : chechLevel(1) """ levelsList = getLevelsList() levelExists = False for level in levelsList: if "natas"+str(n) == level["name"]: levelExists = True break return levelExists
5,323,366
async def cmd_settings_set_autodaily_channel(ctx: Context, text_channel: TextChannel = None): """ Set the auto-daily channel for this server. This channel will receive an automatic /daily message at 1 am UTC. You need the 'Manage Server' permission to use this command. This command can only be used on ...
5,323,367
def generate_wave_graph(source, peaks): """ Generate a plot from a wave file source. Optionally, include peak calculations. Source: https://github.com/MonsieurV/py-findpeaks/blob/master/tests/vector.py :param source: :param peaks: :return: """ i...
5,323,368
def generatePSSMProfile(fastas, outDir, blastpgp, db): """ Generate PSSM file by using the blastpgp program in NCBI blast-2.2.18 package. Parameters ---------- file : file the file, which include the protein sequences in fasta format. blastpgp: string the path of blastpgp program. db: string the unir...
5,323,369
def create(): """ creates metadata for current dataset """ md = MetaData() dataset_basics = describe_dataset() print(dataset_basics) md.template.update(dataset_basics) dataset_folder = where_is_dataset() print(f"Looking into the folder {dataset_folder} for data files...") dat...
5,323,370
def get_payload(dataset, site_code, year): """returns payload needed for a post request to get EANET csv files""" if dataset == "dry_deposition_auto": item_code = 2 elif dataset == "dry_deposition_filter_pack": item_code = 3 elif dataset == "dry_deposition_passive_sampler": ...
5,323,371
def safe_encode(s, coding='utf-8', errors='surrogateescape'): """encode str to bytes, with round-tripping "invalid" bytes""" return s.encode(coding, errors)
5,323,372
def test_tflite_model_u3_usecase_two_external_pools(model_url, usmp_algo): """This checks for inference using two external pools placed in the application""" pytest.importorskip("tflite") import tvm.relay.testing.tf as tf_testing use_unpacked_api = True interface_api = "c" target = tvm.target...
5,323,373
def group_required(*group_names): """ Requires user membership in at least one of the groups passed in. """ def in_groups(u): if u.is_authenticated: if u.is_superuser or bool(u.groups.filter(name__in=group_names)): return True return False return user_p...
5,323,374
def initialize_service(storage_socket, logger, service_input, tag=None, priority=None): """Initializes a service from a API call. Parameters ---------- storage_socket : StorageSocket A StorageSocket to the currently active database logger A logger for use by the service service_...
5,323,375
def shutdown(prompt=False): """Deprecated.""" _check_connection() cluster().shutdown(prompt)
5,323,376
def validate_ok_for_replace(replacement): """Validate a replacement document.""" validate_is_mapping("replacement", replacement) # Replacement can be {} if replacement and not isinstance(replacement, bson.RawBSONDocument): first = next(iter(replacement)) if first.startswith('$'): ...
5,323,377
def extract_stats(output): """Extract stats from `git status` output """ lines = output.splitlines() return collections.Counter([x.split()[0] for x in lines])
5,323,378
def daily_validation_job(name, user_id, cron_string, start_td, end_td, base_url, timeout, **kwargs): """ Create a daily observation validation job named NAME to be executed by the USER_ID user on a scheduled according to CRON_STRING. Validation is performed from job_time + START...
5,323,379
def initParser(): """ Initialize the parser for the CLI """ parser = argparse.ArgumentParser(description='Convert SDF file to CSV', formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--key', '-k', metavar='keyCol', default=None, dest='keyCol') parser.ad...
5,323,380
def save_csv(filename, shape_features, centroid_features, label_features=None, mode='w'): """ Create and save a .csv file containing all the features (shapes, centroids and labels) Parameters ---------- filename : string full name (path and name) of the .c...
5,323,381
def test_strict_vars1(monkeypatch): """Check that cli works correctly with strict vars.""" monkeypatch.setenv('SOM_TT_VALUE', '1') monkeypatch.setenv('SOM_TT_KEY', '2') variables = delegator.run('dump-env -p SOM_TT_ --strict=SOM_TT_KEY') assert variables.out == 'KEY=2\nVALUE=1\n' assert variabl...
5,323,382
def turn_connect(start: Port, end: Port, radius: float, radius_end: Optional[float] = None, euler: float = 0, resolution: int = DEFAULT_RESOLUTION, include_width: bool = True) -> Union[Pattern, Curve]: """Turn connect. Args: start: Start port end: End port radius: Start...
5,323,383
def GoogleAuth(key): """ 谷歌验证码 # RFC 协议下有HOTP和TOTP 前者是计数 后者是计时 生成验证码 # hopt 由 RFC 协议 RFC4266 # google auth 用的是TOTP 而TOTP是在HOTP的基础上计时 :return: """ def get_hotp_token(secret, intervals_no): """This is where the magic happens.""" key = base64.b32decode(normali...
5,323,384
def compress_image(path, thresh=0.2): """Compress Image """ file_stat = os.stat(path) basename = os.path.basename(path) file_type = basename.split('.')[-1] # dont compress gif file if file_type == 'gif': return path file_size = file_stat.st_size / 1024.**2 # if file is...
5,323,385
def adjust_opts(in_opts, config): """Establish JVM opts, adjusting memory for the context if needed. This allows using less or more memory for highly parallel or multicore supporting processes, respectively. """ memory_adjust = config["algorithm"].get("memory_adjust", {}) out_opts = [] for ...
5,323,386
def load_images(image_name_to_label): """ Returns (images, labels), where each image is from a file name present in the image_name_to_label dictionary """ images = [] labels = [] image_names = os.listdir(DEFAULT_IMG_PATH_EDITED) # Remove directories image_names.remove("COVID-19") ...
5,323,387
def from_address(text, v4_origin=ipv4_reverse_domain, v6_origin=ipv6_reverse_domain): """Convert an IPv4 or IPv6 address in textual form into a Name object whose value is the reverse-map domain name of the address. *text*, a ``str``, is an IPv4 or IPv6 address in textual form (e.g. '12...
5,323,388
def blog_claim(): """Blog info If the user (check the username) has already bought the item or its author, To display the content of the article . :param blog_id ,token , address :return: { "msg": { "author": "0x035EB55d4260455075A8418C4B94Ba618C445537", ...
5,323,389
def get_task_flow_results_as_dataframe(task_id: int, flow_id: int, num_runs: int, raise_few_runs: bool, configuration_space: ConfigSpace.ConfigurationSpace, evaluation_measures: typing.List[str], ...
5,323,390
def _expr_rshift_as_multiplication_of_reverse_order(lhs, rhs): """The multiply express will reverse order. """ return rhs * lhs
5,323,391
def pathsuboption(option, attr): """Decorator used to declare a path sub-option. Arguments are the sub-option name and the attribute it should set on ``path`` instances. The decorated function will receive as arguments a ``ui`` instance, ``path`` instance, and the string value of this option from ...
5,323,392
def CalculateHarmonicTopoIndex(mol): """ ################################################################# Calculation of harmonic topological index proposed by Narnumi. ---->Hato Usage: result=CalculateHarmonicTopoIndex(mol) Input: mol is a molecule object Output: resul...
5,323,393
def get_random(args): """Get random item from db""" peon = Peon() if not args.with_usages: item = peon.random(args.category) else: item = peon.random_with_usages(args.category) print item.value, '\nUsages:' for usage in item.usages(): print usage.value()
5,323,394
def record_metrics(func): """ The metrics decorator records each time a route is hit in redis The number of times a route is hit and an app_name query param are used are recorded. A redis a redis hash map is used to store each of these values. NOTE: This must be placed before the cache decorator in...
5,323,395
def is_long_path(path: PathOrString) -> bool: """ A long path is a path that has more than 260 characters """ return len(str(path)) > MAX_PATH_LENGTH
5,323,396
def build_model(): """ Builds up the SoundNet model and loads the weights from a given model file (8-layer model is kept at models/sound8.npy). :return: """ model_weights = np.load('models/sound8.npy').item() model = Sequential() model.add(InputLayer(batch_input_shape=(1, None, 1))) fil...
5,323,397
def strip_elements(root, elements_to_strip=set(), text=None, standoffs=None): """ Removes initial and terminal space from elements that either have surrounding space or belong to given set of elements to strip. """ if text is None or standoffs is None: text, standoffs = text_and_standoffs(r...
5,323,398
def open( urlpath, mode="rb", compression=None, encoding="utf8", errors=None, protocol=None, newline=None, **kwargs ): """ Given a path or paths, return one ``OpenFile`` object. Parameters ---------- urlpath: string or list Absolute or relative filepath. Prefix w...
5,323,399