content
stringlengths
22
815k
id
int64
0
4.91M
def find_best_classifier(data, possible_classifiers, target_classifier): """Given a list of points, a list of possible Classifiers to use as tests, and a Classifier for determining the true classification of each point, finds and returns the classifier with the lowest disorder. Breaks ties by preferrin...
23,300
def get_product_type_name(stac_item): """ Create a ProductType name from a STAC Items metadata """ properties = stac_item['properties'] assets = stac_item['assets'] parts = [] platform = properties.get('platform') or properties.get('eo:platform') instruments = properties.get('instruments'...
23,301
def get_show_default(): """ gets the defaults """ return SHOW_DEFAULT
23,302
def test_can_build_lookup_table_and_use_it_for_known_values(): """Functional (a.k.a acceptance) test for LookupTable""" # John prepares data to be looked up ts = array([0.1, 1.1, 2.1]) x1 = array([10.2, -1.4, 4.1]) x2 = array([0.1, 0.01, 0.4]) # John calculates "trajectory" for his data ta...
23,303
def sample_langevin_v2(x, model, stepsize, n_steps, noise_scale=None, intermediate_samples=False, clip_x=None, clip_grad=None, reject_boundary=False, noise_anneal=None, spherical=False, mh=False, temperature=None, norm=False, cut=True): """Langevin Monte Carlo x: torch.Te...
23,304
async def dump(self, chan, source, msg): """ dump the contents of self to a file for debugging purposes. """ if len(msg) < 1: await out.msg(self, modname, chan, ["need filename"]) return with open(msg, "w") as f: pprint.pprint(vars(self), stream=f) pprint.pprint(...
23,305
def fpoly(x, m): """Compute the first `m` simple polynomials. Parameters ---------- x : array-like Compute the simple polynomials at these abscissa values. m : :class:`int` The number of simple polynomials to compute. For example, if :math:`m = 3`, :math:`x^0`, :math:`x^1` ...
23,306
def get_custom_logger(context): """ Customizable template for creating a logger. What would work is to have the format and date format passed """ # Initialize Custom Logging # Timestamps with logging assist debugging algorithms # With long execution times manifest = context.gear_dict['ma...
23,307
def get_torch_core_binaries(module): """Return required files from the torch folders. Notes: So far only tested for Windows. Requirements for other platforms are unknown. """ binaries = [] torch_dir = module.getCompileTimeDirectory() extras = os.path.join(torch_dir, "lib") ...
23,308
def _function_fullname(f): """Return the full name of the callable `f`, including also its module name.""" function, _ = getfunc(f) # get the raw function also for OOP methods if not function.__module__: # At least macros defined in the REPL have `__module__=None`. return function.__qualname__ ...
23,309
def dists2centroids_numpy(a): """ :param a: dist ndarray, shape = (*, h, w, 4=(t, r, b, l)) :return a: Box ndarray, shape is (*, h, w, 4=(cx, cy, w, h)) """ return corners2centroids_numpy(dists2corners_numpy(a))
23,310
def heatmap(data_df, figsize=None, cmap="Blues", heatmap_kw=None, gridspec_kw=None): """ Plot a residue matrix as a color-encoded matrix. Parameters ---------- data_df : :class:`pandas.DataFrame` A residue matrix produced with :func:`~luna.analysis.residues.generate_residue_matrix`. figsize...
23,311
def combined_loss(x, reconstructed_x, mean, log_var, args): """ MSE loss for reconstruction, KLD loss as per VAE. Also want to output dimension (element) wise RCL and KLD """ # First, binary data loss1 = torch.nn.BCEWithLogitsLoss(size_average=False) loss1_per_element = torch.nn.BCEWithLogit...
23,312
def isfloat(string: str) -> bool: """ This function receives a string and returns if it is a float or not. :param str string: The string to check. :return: A boolean representing if the string is a float. :rtype: bool """ try: float(string) return True except (ValueErro...
23,313
def parse_path_kvs(file_path): """ Find all key-value pairs in a file path; the pattern is *_KEY=VALUE_*. """ parser = re.compile("(?<=[/_])[a-z0-9]+=[a-zA-Z0-9]+[.]?[0-9]*(?=[_/.])") kvs = parser.findall(file_path) kvs = [kv.split("=") for kv in kvs] return {kv[0]: to_number(kv[1]...
23,314
def user_count_by_type(utype: str) -> int: """Returns the total number of users that match a given type""" return get_count('users', 'type', (utype.lower(),))
23,315
async def test_availability_without_topic(hass, mqtt_mock): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock, switch.DOMAIN, DEFAULT_CONFIG )
23,316
def create_stellar_deposit(transaction_id): """Create and submit the Stellar transaction for the deposit.""" transaction = Transaction.objects.get(id=transaction_id) # We can assume transaction has valid stellar_account, amount_in, and asset # because this task is only called after those parameters are ...
23,317
def test_parameter_file_proper_toml(): """Tells you what line of the TOML has an error""" ll = pkg_resources.resource_string("cascade.executor", "data/parameters.toml").decode().split("\n") for i in range(1, len(ll)): try: toml.loads("".join(ll[:i])) except toml.TomlDecodeError: ...
23,318
def test_getSBMLFromBiomodelsURN2(): """ Check that model can be loaded in roadrunner. :return: """ urn = 'urn:miriam:biomodels.db:BIOMD0000000139' sbml = temiriam.getSBMLFromBiomodelsURN(urn) print("*" * 80) print(type(sbml)) print("*" * 80) print(sbml) print("*" * 80) r ...
23,319
def node_label(label, number_of_ports, debug=None): """ generate the HTML-like label <TABLE ALIGN="CENTER"><TR><TD COLSPAN="2">name</TD></TR> <TR> <TD PORT="odd">odd</TD> <TD PORT="even">even</TD> </TR> singleport: <TR> <TD PORT="port">port</TD> </TR> return a s...
23,320
def grouperElements(liste, function=len): """ fonctions qui groupe selon la fonction qu'on lui donne. Ainsi pour le kalaba comme pour les graphèmes, nous aurons besoin de la longueur, """ lexique=[] data=sorted(liste, key=function) for k,g in groupby(data, function): lexique.append(list(g)) return lexique
23,321
def test_eofs_matches_sklearn(): """Test result from eofs routine matches reference implementation.""" x = np.random.uniform(size=(100, 20)) k = 10 eofs_result = rdu.eofs(x, n_modes=k) model = sd.PCA(n_components=k) pcs = model.fit_transform(x) assert np.allclose(model.components_, eofs_...
23,322
def SensorLocation_Cast(*args): """ Cast(BaseObject o) -> SensorLocation SensorLocation_Cast(Seiscomp::Core::BaseObjectPtr o) -> SensorLocation """ return _DataModel.SensorLocation_Cast(*args)
23,323
def fatorial(num=1, show=False): """ -> Calcula o fatorial de um número. :param num: Fatorial a ser calculado :param show: (opicional) Mostra a conta :return: Fatorial de num. """ print('-=' * 20) fat = 1 for i in range(num, 0, -1): fat *= i if show: resp = f'{str...
23,324
def test_plotting_with_each_graph_data_property(my_outdir): # Note: All outputs were inspected manually, all bugs were resolved and all shortcomings # documented in the docstrings and below here. This becomes necessary again in case of # major code changes and can hardly be automated (with reasonable effort...
23,325
def read_rudder_config(path=None): """Reads the servo configuration from config.yml and returns a matching servo.""" if path is None: path = os.path.dirname(os.path.abspath(__file__)) with open(path + "/config.yml", "r") as yml: conf = yaml.full_load(yml) rudder_config = conf["rudder...
23,326
def test_simple_line_parse(): """Simple line parse""" print(test_simple_line_parse.__doc__) line = " int i = 0;" parsed_line = Sea5kgCppLintLineParser(line, 'file', 0) assert parsed_line.get_line() == line assert parsed_line.get_filename() == 'file' assert parsed_line.get_number_of_line()...
23,327
def linear_trend(series=None, coeffs=None, index=None, x=None, median=False): """Get a series of points representing a linear trend through `series` First computes the lienar regression, the evaluates at each dates of `series.index` Args: series (pandas.Series): data with DatetimeIndex as the ...
23,328
def cli(ctx: callable) -> None: """DIRBS script to output reports (operator and country) for a given MONTH and YEAR. Arguments: ctx: click context (required) Returns: None """ pass
23,329
def test_hook_initialization(base_app): """Test hook initialization.""" app = base_app magic_hook = MagicMock() app.config['INDEXER_BEFORE_INDEX_HOOKS'] = [ magic_hook, 'test_invenio_bulkindexer:_global_magic_hook' ] ext = InvenioIndexer(app) with app.app_context(): recid = ...
23,330
def snapshot_metadata_get(context, snapshot_id): """Get all metadata for a snapshot.""" return IMPL.snapshot_metadata_get(context, snapshot_id)
23,331
def graph_from_tensors(g, is_real=True): """ """ loop_edges = list(nx.selfloop_edges(g)) if len(loop_edges) > 0: g.remove_edges_from(loop_edges) if is_real: subgraph = (g.subgraph(c) for c in nx.connected_components(g)) g = max(subgraph, key=len) g = nx.convert_node_...
23,332
def hook(t): """Calculate the progress from download callbacks (For progress bar)""" def inner(bytes_amount): t.update(bytes_amount) # Update progress bar return inner
23,333
def delete(event, context): """ Delete a cfn stack using an assumed role """ stack_id = event["PhysicalResourceId"] if '[$LATEST]' in stack_id: # No stack was created, so exiting return stack_id, {} cfn_client = get_client("cloudformation", event, context) cfn_client.delete_s...
23,334
def _rec_compare(lhs, rhs, ignore, only, key, report_mode, value_cmp_func, _regex_adapter=RegexAdapter): """ Recursive deep comparison implementation """ # pylint: disable=unidiomatic-t...
23,335
def exists_job_onqueue(queuename, when, hour): """ Check if a job is present on queue """ scheduler = Scheduler(connection=Redis()) jobs = scheduler.get_jobs() for job in jobs: if 'reset_stats_queue' in job.func_name: args = job.args if queuename == args[0] an...
23,336
def q_inv_batch_of_sequences(seq): """ :param seq: (n_batch x n_frames x 32 x 4) :return: """ n_batch = seq.size(0) n_frames = seq.size(1) n_joints = seq.size(2) seq = seq.reshape((n_batch * n_frames * n_joints, 4)) seq = qinv(seq) seq = seq.reshape((n_batch, n_frames, n_joints, ...
23,337
def dealer_wins(chips): """Player loses chips""" print("The dealer won.") chips.lose_bet()
23,338
def check_policy_enforce(logical_line, filename): """Look for uses of nova.policy._ENFORCER.enforce() Now that policy defaults are registered in code the _ENFORCER.authorize method should be used. That ensures that only registered policies are used. Uses of _ENFORCER.enforce could allow unregistered po...
23,339
def msa_job_space_demand(job_space_demand): """ Job space demand aggregated to the MSA. """ df = job_space_demand.local return df.fillna(0).sum(axis=1).to_frame('msa')
23,340
def get_pdf_cdf_3(corr, bins_pdf, bins_cdf, add_point=True, cdf_bool=True, checknan=False): """ corr is a 3d array, the first dimension are the iterations, the second dimension is usually the cells the function gives back the pdf and the cdf add_point option duplicated the last po...
23,341
def unconfigure_route_map(device, route_map_name, permit): """ unconfigure route map Args: device (`obj`): device to execute on route_map_name (`int`): route map name permit (`int`): Sequence to insert to existing route-map entry Return: None ...
23,342
def test_wrong_params(param, match): """Test Exceptions at check_params function.""" rng = np.random.RandomState(0) X = rng.rand(5, 2) with pytest.raises(ValueError, match=match): bisect_means = BisectingKMeans(n_clusters=3, **param) bisect_means.fit(X)
23,343
def create_app(): """ Application factory to create the app and be passed to workers """ app = Flask(__name__) import logging logging.basicConfig( filename='./logs/flask.log', level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:...
23,344
def build_vocab(args, dataset, schema_graphs): """ Construct vocabularies. This function saves to disk: - text vocab: consists of tokens appeared in the natural language query and schema - program vocab: consists of tokens appeared in the program - schema vocab: consists of table and field name...
23,345
def create_win_jupyter_console(folders): """ create a batch file to start jupyter @param folders see @see fn create_win_batches @return operations (list of what was done) """ text = ['@echo off', 'set CURRENT2=%~dp0', 'call "%CURRENT2%env.bat"', ...
23,346
def incidence_matrix( H, order=None, sparse=True, index=False, weight=lambda node, edge, H: 1 ): """ A function to generate a weighted incidence matrix from a Hypergraph object, where the rows correspond to nodes and the columns correspond to edges. Parameters ---------- H: Hypergraph objec...
23,347
def write_linkdirs_geotiff(links, gd_obj, writepath): """ Creates a geotiff where links are colored according to their directionality. Pixels in each link are interpolated between 0 and 1 such that the upstream pixel is 0 and the downstream-most pixel is 1. In a GIS, color can then be set to se...
23,348
def test_encode_decode_get_profile(): """Test encode decode get profile.""" msg = YotiMessage( performative=YotiMessage.Performative.GET_PROFILE, token=str(uuid4()), dotted_path="a", args=tuple(), ) assert YotiMessage.decode(msg.encode()) == msg
23,349
def compare_models(model1, model2, tmpdir): """Checks if weights between two models can be shared.""" clf = model1() pipe = make_pipeline( make_union( HashingVectorizer(), HashingVectorizer(ngram_range=(2, 3), analyzer="char") ), clf, ) X = [ "i really li...
23,350
def _add_parents_and_tree(commit, git_objects, git_root): """Add parent reference (i.e. to the parent commit) and tree reference (to the top-level tree) to a commit object. """ content = cat_file(commit.sha, git_root, CatFileOption.PRETTY) ptr_str = content.split("\n")[0].strip() ptr_obj = git_o...
23,351
def check_for_cd_frame(fem1): """ A cylindrical/spherical CD frame will cause problems with the grid point force transformation """ if any([card_name in fem1.card_count for card_name in ['GRID', 'SPOINT', 'EPOINT', 'RINGAX']]): icd_transform, icp_transform, xyz_cp, nid_cp_cd = fem1.get_displ...
23,352
def initial_landing_distance(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the initial landing distance on that interest area. The initial landing distance is the pixel distance between the first fixation to land in an interest area and the left edge of ...
23,353
def load_object(filename): """ Load saved object from file :param filename: The file to load :return: the loaded object """ with gzip.GzipFile(filename, 'rb') as f: return pickle.load(f)
23,354
def runAsStandalone(): """Contains script execution flow when run as standalone application. """ #### Pre-execution internal configuation check. #initLogger = logging.Logger(name=_toolName) #initLogger.addHandler(logging.StreamHandler(sys.stderr)) #### Configuration fine, execute as pl...
23,355
def list_events_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """Lists all events and return outputs in Demisto's format Args: client: Client object with request args: Usually demisto.args() Returns: Outputs """ max_results = args.get('max_results') eve...
23,356
def update_weights(weights, expectation_g_squared, g_dict, decay_rate, learning_rate): """ Refer: http://sebastianruder.com/optimizing-gradient-descent/index.html#rmsprop""" epsilon = 1e-5 for layer_name in weights.keys(): g = g_dict[layer_name] expectation_g_squared[layer_name] = decay_rate...
23,357
def get_or_generate_vocab_inner(data_dir, vocab_filename, vocab_size, generator, max_subtoken_length=None, reserved_tokens=None): """Inner implementation for vocab generators. Args: data_dir: The base directory where data and vocab files are store...
23,358
def response_map(fetch_map): """Create an expected FETCH response map from the given request map. Most of the keys returned in a FETCH response are unmodified from the request. The exceptions are BODY.PEEK and BODY partial range. A BODY.PEEK request is answered without the .PEEK suffix. A partial range (e.g. BODY...
23,359
def test_attr(pymel, node): """Validate the `attr` method behavior""" port = node.attr("foo") assert isinstance(port, pymel.Attribute)
23,360
def make_cat_wfpc2(fitsfile, outcat='default', regfile='default', configfile='sext_astfile.config', whtfile=None, weight_type='MAP_WEIGHT', gain=2.5, texp='header', ncoadd=1, satur=65535., catformat='ldac', det_area=30, det_thresh=2.5, ...
23,361
def RigidTendonMuscle_getClassName(): """RigidTendonMuscle_getClassName() -> std::string const &""" return _actuators.RigidTendonMuscle_getClassName()
23,362
def mp_solve_choices(p, q, n, delta_x, delta_y, delta, psi): # <<< """Implements mp_solve_choices form metapost (mp.c)""" uu = [None]*(len(delta)+1) # relations between adjacent angles ("matrix" entries) ww = [None]*len(uu) # additional matrix entries for the cyclic case vv = [None]*len(uu) # angles ("r...
23,363
def Generate3DBlueNoiseTexture(Width,Height,Depth,nChannel,StandardDeviation=1.5): """This function generates a single 3D blue noise texture with the specified dimensions and number of channels. It then outputs it to a sequence of Depth output files in LDR and HDR in a well-organized tree of directori...
23,364
def submit(): """Receives the new paste and stores it in the database.""" if request.method == 'POST': form = request.get_json(force=True) pasteText = json.dumps(form['pasteText']) nonce = json.dumps(form['nonce']) burnAfterRead = json.dumps(form['burnAfterRead']) pasteK...
23,365
def select_from_dictset( dictset: Iterator[dict], columns: List[str] = ['*'], condition: Callable = select_all) -> Iterator[dict]: """ Scan a dictset, filtering rows and selecting columns. Basic implementation of SQL SELECT statement for a single table Approximate SQL: SEL...
23,366
def money_recall_at_k(recommended_list, bought_list, prices_recommended, prices_bought, k=5): """ Доля дохода по релевантным рекомендованным объектам :param recommended_list - список id рекомендаций :param bought_list - список id покупок :param prices_recommended - список цен для рекомендаций :param...
23,367
def get_clustering_fips( collection_of_fips, adj = None ): """ Finds the *separate* clusters of counties or territorial units that are clustered together. This is used to identify possibly *different* clusters of counties that may be separate from each other. If one does not supply an adjacency :py:class:`dict`...
23,368
def stop_after(space_number): """ Decorator that determines when to stop tab-completion Decorator that tells command specific complete function (ex. "complete_use") when to stop tab-completion. Decorator counts number of spaces (' ') in line in order to determine when to stop. ex. "use explo...
23,369
def find_cut_line(img_closed_original): # 对于正反面粘连情况的处理,求取最小点作为中线 """ 根据规则,强行将粘连的区域切分 :param img_closed_original: 二值化图片 :return: 处理后的二值化图片 """ img_closed = img_closed_original.copy() img_closed = img_closed // 250 #print(img_closed.shape) width_sum = img_closed.sum(axis=1) ...
23,370
def _search(progtext, qs=None): """ Perform memoized url fetch, display progtext. """ loadmsg = "Searching for '%s'" % (progtext) wdata = pafy.call_gdata('search', qs) def iter_songs(): wdata2 = wdata while True: for song in get_tracks_from_json(wdata2): yiel...
23,371
def img_to_vector(img_fn, label=0): """Read the first 32 characters of the first 32 rows of an image file. @return <ndarray>: a 1x(1024+1) numpy array with data and label, while the label is defaults to 0. """ img = "" for line in open(img_fn).readlines()[:32]: ...
23,372
def get_config(): """Return a user configuration object.""" config_filename = appdirs.user_config_dir(_SCRIPT_NAME, _COMPANY) + ".ini" config = _MyConfigParser() config.optionxform = str config.read(config_filename) config.set_filename(config_filename) return config
23,373
def launch_matchcomms_server() -> MatchcommsServerThread: """ Launches a background process that handles match communications. """ host = 'localhost' port = find_free_port() # deliberately not using a fixed port to prevent hardcoding fragility. event_loop = asyncio.new_event_loop() matchco...
23,374
def acq_randmaxvar(): """Initialise a RandMaxVar fixture. Returns ------- RandMaxVar Acquisition method. """ gp, prior = _get_dependencies_acq_fn() # Initialising the acquisition method. method_acq = RandMaxVar(model=gp, prior=prior) return method_acq
23,375
def test_imdb_shard_id(): """ Feature: Test IMDB Dataset. Description: read data from all file with num_shards=4 and shard_id=1. Expectation: the data is processed successfully. """ logger.info("Test Case withShardID") # define parameters repeat_count = 1 # apply dataset operations ...
23,376
def enable_logging(logging_lvl=logging.DEBUG, save_log=False, logfile_prefix=""): """ Enables Color logging on multi-platforms as well as in environments like jupyter notebooks :param logging_lvl: Given debug level for setting what messages to show. (logging.DEBUG is lowest) :param save_log: If true a ...
23,377
def from_config(func): """Run a function from a JSON configuration file.""" def decorator(filename): with open(filename, 'r') as file_in: config = json.load(file_in) return func(**config) return decorator
23,378
def update_user(user, domain, password=None): """ create/update user record. if password is None, the user is removed. Password should already be SHA512-CRYPT'd """ passwdf = PASSWDFILE % {"domain": domain} passwdb = KeyValueFile.open_file(passwdf, separator=":", lineformat=USERLINE+"\n") passw...
23,379
def puzzle_pieces(n): """Return a dictionary holding all 1, 3, and 7 k primes.""" kprimes = defaultdict(list) kprimes = {key : [] for key in [7, 3, 1]} upper = 0 for k in sorted(kprimes.keys(), reverse=True): if k == 7: kprimes[k].extend(count_Kprimes(k, 2, n)) if not...
23,380
def periodogram_snr(periodogram,periods,index_to_evaluate,duration,per_type, freq_window_epsilon=3.,rms_window_bin_size=100): """ Calculate the periodogram SNR of the best period Assumes fixed frequency spacing for periods periodogram - the periodogram values periods - pe...
23,381
def derivative_overview(storage_service_id, storage_location_id=None): """Return a summary of derivatives across AIPs with a mapping created between the original format and the preservation copy. """ report = {} aips = AIP.query.filter_by(storage_service_id=storage_service_id) if storage_locatio...
23,382
def fetch_packages(vendor_dir, packages): """ Fetches all packages from github. """ for package in packages: tar_filename = format_tar_path(vendor_dir, package) vendor_owner_dir = ensure_vendor_owner_dir(vendor_dir, package['owner']) url = format_tarball_url(package) pri...
23,383
def execute_search(search_term, sort_by, **kwargs): """ Simple search API to query Elasticsearch """ # Get the Elasticsearch client client = get_client() # Perform the search ons_index = get_index() # Init SearchEngine s = SearchEngine(using=client, index=ons_index) # Define t...
23,384
def cli(dbname, direct_store, hashdb_path, logfile, sleeptime): """ Trivial wrapper about main to create a command line interface entry-point. (This preserves main for use as a regular function for use elsewhere e.g. testing, and also provide a sensible location to initialise logging.) """ d...
23,385
def last_char_to_aou(word): """Intended for abbreviations, returns "a" or "ä" based on vowel harmony for the last char.""" assert isinstance(word, str) ch = last_char_to_vowel(word) if ch in "aou": return "a" return "ä"
23,386
def times_vector(mat, vec): """Returns the symmetric block-concatenated matrix multiplied by a vector. Specifically, each value in the vector is multiplied by a row of the full matrix. That is, the vector is broadcast and multiplied element-wise. Note this would be the transpose of full_mat * vec if full_mat r...
23,387
def ensure_path(path:[str, pathlib.Path]): """ Check if the input path is a string or Path object, and return a path object. :param path: String or Path object with a path to a resource. :return: Path object instance """ return path if isinstance(path, pathlib.Path) else pathlib.Path(path)
23,388
def create_arguments(parser): """Sets up the CLI and config-file options""" client_args = parser.add_argument_group('client test arguments') client_args.add_argument('-t', '--tenantname', default='admin', help='Tenant Name') client_args.add_argu...
23,389
def examine_mode(mode): """ Returns a numerical index corresponding to a mode :param str mode: the subset user wishes to examine :return: the numerical index """ if mode == 'test': idx_set = 2 elif mode == 'valid': idx_set = 1 elif mode == 'train': idx_set = 0 ...
23,390
def main(): """Validates individual trigger files within the raidboss Cactbot module. Current validation only checks that the trigger file successfully compiles. Returns: An exit status code of 0 or 1 if the tests passed successfully or failed, respectively. """ exit_status = 0 ...
23,391
def create_pinata(profile_name: str) -> Pinata: """ Get or create a Pinata SDK instance with the given profile name. If the profile does not exist, you will be prompted to create one, which means you will be prompted for your API key and secret. After that, they will be stored securely using ``keyri...
23,392
def create_tfid_weighted_vec(tokens, w2v, n_dim, tfidf): """ Create train, test vecs using the tf-idf weighting method Parameters ---------- tokens : np.array data (tokenized) where each line corresponds to a document w2v : gensim.Word2Vec word2vec model n_dim : in...
23,393
def miniimagenet(folder, shots, ways, shuffle=True, test_shots=None, seed=None, **kwargs): """Helper function to create a meta-dataset for the Mini-Imagenet dataset. Parameters ---------- folder : string Root directory where the dataset folder `miniimagenet` exists. shots ...
23,394
def process_account_request(request, order_id, receipt_code): """ Process payment via online account like PayPal, Amazon ...etc """ order = get_object_or_404(Order, id=order_id, receipt_code=receipt_code) if request.method == "POST": gateway_name = request.POST["gateway_name"] gatewa...
23,395
def add_classification_categories(json_object, classes_file): """ Reads the name of classes from the file *classes_file* and adds them to the JSON object *json_object*. The function assumes that the first line corresponds to output no. 0, i.e. we use 0-based indexing. Modifies json_object in-place....
23,396
def create_compound_states(reference_thermodynamic_state, top, protocol, region=None, restraint=False): """ Return alchemically modified thermodynamic states. Parameters ---------- reference_...
23,397
def initialize_binary_MERA_random(phys_dim, chi, dtype=tf.float64): """ initialize a binary MERA network of bond dimension `chi` isometries and disentanglers are initialized with random unitaries (not haar random) Args: phys_dim (int): Hilbert space dimension of the bottom layer c...
23,398
def tts_init(): """ Initialize choosen TTS. Returns: tts (TextToSpeech) """ if (TTS_NAME == "IBM"): return IBM_initialization() elif (TTS_NAME == "pytts"): return pytts_initialization() else: print("ERROR - WRONG TTS")
23,399