content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def profile_edit(request, username, edit_profile_form=EditProfileForm, template_name='userena/profile_form.html', success_url=None, extra_context=None, **kwargs): """ Edit profile. Edits a profile selected by the supplied username. First checks permissions if the user ...
8b318b9e4fc170e1622cc3a0ea37fd0e62c1a356
45,500
def minimal_medium( models: CommunityModelDirectory, min_growth: float = 0.1, threads: int = 1 ) -> pd.DataFrame: """Calculate the minimal medium for a set of community models.""" manifest = models.manifest.view(pd.DataFrame) model_folder = str(models.model_files.path_maker(model_id="blub")).replace( ...
2e23579b05d1102a18dddc30ba1aa088c91d07c5
45,501
def ais_singleiter( y_pred, y_test, prob_pos, sample_budget, g, alpha, known_rows, filter_rows ): """Perform a single AIS iteration of calibration + sampling. Args: y_pred: model predictions (k,) y_test: ground-truth labels for sampled rows (samples,) prob_pos: model scores (k,) ...
c56acbd47c0b04dfc45ce25be97231a80ebbbab2
45,502
def request_user_has_rule_trigger_permission(request, trigger): """ Check that the currently logged-in has necessary permissions on the trigger used / referenced inside the rule. """ if not cfg.CONF.rbac.enable: return True user_db = get_user_db_from_request(request=request) rules_r...
b72be83203f3ae49fb99b939c03b604985401f27
45,503
import collections def dict_update(d, u): """Update dict d based on u recursively.""" for k, v in u.items(): if isinstance(v, collections.Mapping): d[k] = dict_update(d.get(k, {}), v) else: d[k] = v return d
c1228442e280bf14424a9c7abb9dae82d0ee46f0
45,504
import re def soft_break(value, length, process=lambda chunk: chunk): """ Encourages soft breaking of text values above a maximum length by adding zero-width spaces after common delimeters, as well as soft-hyphenating long identifiers. """ delimiters = re.compile(r'([{}]+)'.format(''.join(map(...
66e43db80582ee2fcceb72303adf939dd5ada8f1
45,505
def flip(function): """ Returns a function which behaves like `function` but gets the given positional arguments reversed; keyword arguments are passed through. >>> from brownie.functional import flip >>> def f(a, b): return a >>> f(1, 2) 1 >>> flip(f)(1, 2) 2 """ @wraps(fun...
86fb3cb5a5f60a195a6b71fb77eaefb1aa24706d
45,506
def org_has_prescribing(org_type, org_id): """ Return whether this org has any prescribing data associated with it """ row_grouper = get_row_grouper(org_type) return org_id in row_grouper.offsets
e1f393f3251743d7cc62818831f6a6d7597d4f46
45,507
def get_or_create_experiment(experiment_name: str) -> mlflow.entities.Experiment: """ Returns an existing MLflow experiment if it exists, otherwise it creates a new one. Args: experiment_name (str): The name or ID of the experiment. Returns: mlflow.experiment: The found or created expe...
7bb587119bba792b66945e8a2988893198c08b06
45,508
def data_generator(metric): """ finding gamma for NNC and generating files to train and test data sets :param metric: string of metric name :return: X_train: vector with size of n_train of binary vectors with size of example_size X_test: vector with size of n_test of binary vectors with siz...
a5dc0ccf3c2f0c9db0935dc785705f16516c6569
45,509
def cal_total_variation_loss_v1(logits, gts=None, reduction="mean"): """ :param preds: (N,C,H,W) logits predicted by the model. :param gts: useless arg. :param reduction: specifies how all element-level loss is handled. :return: total_variation_loss """ probs = logits.simgoid() h, w = pr...
e76aec4a908374c61444051346e0d53b9ae2b5b1
45,510
def encode_boolean(value): """ Returns 1 or 0 if the value is True or False. None gets interpreted as False. Otherwise, the original value is returned. """ if value is True: return 1 if value is False or value is None: return 0 return value
4a6442438d3a7e85597ac76d2f48ce44ba505be2
45,511
def is_gauss_sum_separable(n,k): """ Returns true if gauss sum is separble for dirichlet characters mod k calculated for positive integer n Parameters ---------- n : int denotes positive integer for which dirichlet characters are calculated k : int denotes positive intger mod ...
459ca26a8052c57093e94b12ee833febec5b9001
45,512
def get_session(): """ Returns: the trident _SESSION """ return _SESSION
c4f05c57343779baee6f3aaa2c5a7834ea2ada8e
45,513
def clip_by_global_norm(max_norm) -> GradientTransformation: """Clip updates using their global norm. References: [Pascanu et al, 2012](https://arxiv.org/abs/1211.5063) Args: max_norm: the maximum global norm for an update. Returns: An (init_fn, update_fn) tuple. """ def init_fn(_): retu...
084f57223f13314a778ddd4627323a2529fe5e3d
45,514
def random_file_url(company): """ Generate a random image url string. Parameters: company: str The company name for the hostname. Return: str A generated url for an image on the company's host. """ url = "-".join(company.split()) return f"https://{ur...
80989c1a1cc860a66c101196a021adb093382e00
45,515
def validate_sami_id(candidate_sami_id): """Dummy validation function for SAMI IDs, always returns true.""" return True
302df887aeafb7e93437e5103a8e0b77fea72b6e
45,516
def get_binary_column_prob(dataset): """Returns a probability tuples for binary class = True and binary class = False for the binary column in the dataset""" binary_column = dataset.columns_that_are('binary')[0] a_count = 0 not_a_count = 0 for attr_value, class_value in zip(binary_column, da...
8d1c00eb0f930757719505ed032e1513650acd78
45,517
import sys def nearing_recursion_limit(): """Return true if current stack depth is within 100 of maximum limit.""" return sys.getrecursionlimit() - _get_stack_depth() < 100
bd05fd8a8feca351d4045f1c73412b8d4bd5867b
45,518
def get_workloads(month): """Calls the same method on the Month model.""" return month.get_workloads()
0b71297c0e244c07e8c832c69037f6b428b60316
45,519
def GetCrypter(secret): """Returns the Keyczar Crypter object returned by the secrets manager instance GetCrypter method.""" return GetSecretsManagerForSecret(secret).GetCrypter(secret)
6806063331a12f85bcaf4f7d57a2bd18fbb25b61
45,520
import copy def resample(image, target, mapping, shape, order=3): """ Resample an image to a target CoordinateMap with a "world-to-world" mapping and spline interpolation of a given order. Here, "world-to-world" refers to the fact that mapping should be a callable that takes a physical coordinate...
b96935c0007fcb818128499861e534216a759dbd
45,521
def roster_details(member_id): """Get the roster details for a particular member Decorators: ROSTER Arguments: member_id {[number]} -- [Id that uniquely identies this member] """ _db = DB() start_time = request.args.get("start_time") end_time = request.args.get("end_time") ...
e1382aeb877c94acc5f70bd84083ca97ec033dd5
45,522
def interpft(x, N): """Interpolates x to n points in Fourier Transform domain """ n = len(x) assert n < N a = jfft.fft(x) nyqst = (n + 1) // 2 z = jnp.zeros(N -n) a1 = a[:nyqst+1] a2 = a[nyqst+1:] b = jnp.concatenate((a1, z, a2)) if n % 2 == 0: b = b.at[nyqst].set(b[n...
572465a3abfaedf27eb765c0654ef956dc1f0e1f
45,523
def price_router(token_in, token_out=usdc, router=None): """ Calculate a price based on Uniswap Router quote for selling one `token_in`. Always uses intermediate WETH pair. """ tokens = [interface.ERC20(token) for token in [token_in, token_out]] router = interface.UniswapRouter(router or ROUTERS...
7c481dfe146432327917123555bcaadffed95400
45,524
def create_esax_time_series(ts_subs, w, per): """ This method creates the eSAX representation for each subsequence and puts them row wise into a dataframe. :param ts_subs: a list of np arrays with the subsequences of the time series :type ts_subs: list of np arrays :param w: word size used for the ...
f271e65bde3b5418f3defd19210d508ce3152a03
45,525
def regex_for_progress(): """ T0:210 /210 B:0 /0 """ return '([0-9].*)\/([0-9].*?)\\r'
2f5230b73ab90ca77e1f1550e141f25265aea844
45,526
def check_penn_treebank_dataset(method): """A wrapper that wraps a parameter checker around the original Dataset(PennTreebankDataset).""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_par...
443f08874f3efc821b1a5a376f0ad2ceb7b5c831
45,527
def _get_all_topic_subscription(topicid): """Gets all of the users subscribed to the topic subscription if you are an admin.""" current_user = get_jwt_identity() if current_user: user = User.query.filter_by(username=current_user).first() if user.is_staff: topic_sub = Topic_Subscr...
22e87a69d34c18bf133bd6da0a91becff008841f
45,528
import os import json import random def shuffle_files_in_list_from_categories(paths_list, categories, metadata_path, type='youtube8m', seed=5): """ generates a list of randomly shuffled paths of the files contained in the provided directories which match at least one of the given categories from the 'categories...
9bcd636083b4fe66f1b71a3afe0a8631e132371e
45,529
import os import time def lambda_handler(event, context): """ Route the incoming request based on intent. The JSON body of the request is provided in the event slot. """ # By default, treat the user request as coming from the America/New_York time zone. os.environ['TZ'] = 'America/New...
e55debca1ab81f832fbdd2c9545c4030ec23cc53
45,530
def get_phase(signal, sample_rate, frame_length=32, frame_shift=8, window_type="hanning", preemphasis=0.0, square_root_window=True): """Compute phase imformation. Args: signal: input speech signal sample_rate: w...
13e7c07370b9c05686f1766ef8a8add8e21bb5e9
45,531
def crossGeneRandom(genea, geneb): """ A crossover startegy where parts of two genes are randomly swapped. 12347 => 14341 54321 52327 Parameters ---------- genea : 1D numpy array An 1D numpy array/list of genes. geneb : 1D numpy array An 1D nu...
60e5bcd72b18e0e723f5ae2054f4b980ea56def4
45,532
def predict(summaries, row) -> tuple: """ Predict the most likely class from inputs: summaries: prepared summaries of dataset row: a row in the dataset for predicting its label (a row of X_test) This function uses the probabilities calculated from each class via the function 'calculate_class_proba...
6e07240fefcb80e4e54a279b11434eb3fb29863a
45,533
import math import bisect import pdb import copy def find_antenna_overlay_for_sector(points_to_cover, center, radius, detection_coverage): """ Find the overlay pattern for antennas so they cover a sector. """ def find_cover(rotated_antenna_pattern,points_to_cover): """ Find the subset of point...
5e6d859cbbef4423f64599adb20545c6fa941db9
45,534
def disable_tls_for(template, port): """ Change a deployment template to disable TLS communications. @param template: deployment template @param port: listening port for Cloudera Manager with TLS disabled @rtype: DeploymentTemplate @return: updated deployment template """ if not templat...
496369113f6ee4ab6df8a43e2ee15a2d0518ac55
45,535
def get_staffline(y_position, extracted_staff_arr): """Gets the staffline of the extracted staff. Args: y_position: The staffline position--the relative number of notes from the 3rd line on the staff. extracted_staff_arr: An extracted staff NumPy array, e.g. `StafflineExtractor.extract_stav...
d4167918907ee93c400e1104ea157fea8d591c96
45,536
def _get_task_info(): """Get task info from Rosetta Code Returns: List of Tuple(task name, task url) """ url = "http://www.rosettacode.org/wiki/Category:Programming_Tasks" soup = get_soup(url) task_tags = soup.find("div", class_="mw-category").find_all("a") task_urls = [] # list of task ...
cc186dfaaf9b40d85421c8ea1e9e59a8b5ab4fa2
45,537
def sample_action(policy, state): """ Samples a policy for an action given the current state. """ choices = np.arange(0, policy.shape[1]) probabilities = policy[state] return np.random.choice(choices, p=probabilities)
afd38b37a4d754acb26cdd0ca5e18a5c596219f0
45,538
def _plot_clusters(estimator, fdata, *, chart=None, fig=None, axes=None, n_rows=None, n_cols=None, labels, sample_labels, cluster_colors, cluster_labels, center_colors, center_labels, center_width, colormap): """Implementation of the plot of the FDataGrid sam...
73de9e0a47f6009addbf84a9fbc43aa7735421c8
45,539
import time def plot(canvas, word, grid, answers): """ called by handle_plot() function draws a box around the word if it is a correct solution """ # pulls data from answers dictionary (iscol, isrev, word_len, x_start, y_start) = answers[word] (x1, y1, square_dim) = find_coord(x_start, y_...
67c504a88d6299d3a7bfe1fa6d529d5652b04957
45,540
def split_flow_into_segments(flow): """Splits the flow into multiple segments where a segment is defined by: data only from endpoint A (request) followed by data only from endpoint B (response). New data from endpoint A initiates a new segment. Returns: list of TcpFlow instances with each instance repre...
a84d4fd5e2a4125e07714f62d422edc147b7f302
45,541
def sigD(jax=True, dtype=np.float32): """ Pauli 'down' matrix. PARAMETERS ---------- jax (bool, default True): Toggles whether a Jax or np array is returned. dtype: the data type of the return value. """ vals = [[0, 0], [1, 0]] D = np.array(vals, dtype=dtype) if jax:...
baca10cdb28de8baade2b8be064f5093d09ed00f
45,542
from re import X def is_clockwise(points): """ Check if the points given forms a clockwise polygon :return: True if the points forms a clockwise polygon """ a = 0 i, j = 0, 0 for i in range(len(points)): j = i + 1 if j == len(points): j = 0 a += points[i][X]*points...
230f9566d45a5abdd5442a2b7f2d7882a1894c9e
45,543
def kl_divergence(p, q): """Standard KL divergence.""" return stats.entropy(p, q)
b0060b117d9c594d761d2d0c3f123b161fdd6090
45,544
import os def calculate_unaberrated_contrast_and_normalization(instrument, design=None, return_coro_simulator=True, save_coro_floor=False, save_psfs=False, outpath=''): """ Calculate the direct PSF peak and unaberrated coronagraph floor of an instrument. :param instrument: string, 'LUVOIR', 'HiCAT', 'RST'...
36436c0f211e9a5ff303f6073e5bb397a0520f76
45,545
def validate_category(value): """Validator for Node#category. Makes sure that the value is one of the categories defined in CATEGORY_MAP. """ if value not in Node.CATEGORY_MAP.keys(): raise ValidationValueError('Invalid value for category.') return True
98ea86f6ca3ba9893efabd3a1a0344c018cd3f75
45,546
def drop_unevaluated_comp(df): """Drop unevaluated compounds from a dataframe.""" df = df[df.index.get_level_values( level=metadata.TREATMENT_GROUP) != metadata.NEGATIVE_CONTROL] df = df[df.index.get_level_values(level=metadata.MOA) != metadata.UNKNOWN] return df
246df0cb2956e5568f1e71c297afc79fe33ac125
45,547
def target_frame(): """Input target frame.""" return 'IAU_ENCELADUS'
34e4fdf51544f8a3d4e9bb43737b717e6d89c417
45,548
def associate_node_id(tr, node=""): """ Returns a dictionary with key 'id' and value as the ID associated with the node string. """ return {"id": tr.get_uml_id(name=node)}
5e6eb1076cdeed9abc8b00d1de60a255f6292dd3
45,549
def record(app, db, s3_location): """Create a record.""" record = { 'title': 'fuu' } record = Record.create(record) record.commit() db.session.commit() return record
dbad6748eedb3930ac25982d3b7905564204eca1
45,550
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Flipr from a config entry.""" hass.data.setdefault(DOMAIN, {}) coordinator = FliprDataUpdateCoordinator(hass, entry) await coordinator.async_config_entry_first_refresh() hass.data[DOMAIN][entry.entry_id] = coord...
af17c6701258239ac40a086dc83da04efc592285
45,551
def build_api_query(req: ExternalAPIRequest) -> str: """ build_api_query takes a ExternalAPIRequest object and returns a URL with query params """ # if the query options weren't specified, return the url without # adding to it. if not req.q: return req.url base_url = req.url if not ba...
444f4dca6ddf3f68fe23ef00e0d5e5a8aff108cf
45,552
def SET(query): """ Decorator that marks a method as a SET query handler for some variable in the genotype-phenotype interface. The decorator receives as argument the name of the query. For instace, this decorator is applied to the Synapses.set_weights method as @SET("synapses:weights"). """...
fb055d59626988201cdb3686d2ff98c8d9f0a21f
45,553
import argparse def parse_arguments(args): """ Parse the arguments from the user """ parser = argparse.ArgumentParser( description= "Filter UniRef EC list\n", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument( "-i","--input", help="the UniRef ...
b1803e6d8d0c1101831838a69711770f9f27c131
45,554
import os def pax(src, pkgdir, verbose=0, dry_run=0, TOOL='/bin/pax'): """ Create a pax gzipped cpio archive of the given src directory and store it to the given pkg directory returns size of archive """ dest = os.path.realpath(os.path.join(pkgdir, 'Contents', 'Archive.pax.gz')) mkpath(os...
65d3ea27ccac548b6d20e905d2beb6d792865a2d
45,555
def get_last_close_str( fmt=ae_consts.COMMON_DATE_FORMAT): """get_last_close_str Get the Last Trading Close Date as a string with default formatting ae_consts.COMMON_DATE_FORMAT (YYYY-MM-DD) :param fmt: optional output format (default ae_consts.COMMON_DATE_FORMAT) """ retur...
03acaebfa8676c88ceffa2f8a0d5f9b9bb2e8f47
45,556
from pathlib import Path import logging import torch def load_grad_z(grad_z_dir=Path("./grad_z/"), train_dataset_size=-1): """Loads all grad_z data required to calculate the influence function and returns it. Arguments: grad_z_dir: Path, folder containing files storing the grad_z values t...
9649b20fc613f3789b32e8cc629b51dbe16c0d3a
45,557
import os def extract_games(world_folder): """ Locate the games in a world folder. """ envs = [] for filename in os.listdir(world_folder): if filename.endswith(".ulx"): envs.append(world_folder + "/" + filename) return envs
a0f60fadf0662dc4d420edb213fd42bca654c800
45,558
def clause_words(clause_tree): """ Returns the constants in a clause. These will be everything that is not a keyword. """ if clause_tree == []: return [] elif clause_tree[0] == 'func': assert(len(clause_tree) == 3) if clause_tree[2] == []: return [clause_tree[1]] else: return [clause_...
5f72cb17397acb9313db5625afd6b4b073f4172f
45,559
def _reusables(): """Return the reusables object. We use this wrapper because so that functions which use the reusables variable can be pickled. """ return reusables
d2db430b4393761eb5f618dff1c44cc29185a225
45,560
def algo_ration(balls: Balls) -> int: """ Algorithmus: Binäre-Suche mit optimiertem Teilverhältnis mit der ersten Kugel, dann mit Einzelschritten suchen. Teilverhältnis -> Mittlere Anzahl: 0.10 -> 13.43 ; 0.19 -> 10.94 ; 0.20 -> 10.94 ; 0.21 -> 10.96 ; 0.30 -> 12.30 :param balls: Die Kugeln für ...
cae301a84488a23c78ad164f61a7e96393d3201e
45,561
def D50(Stk50, RhoP, Q, C, Eta, W): """ Returns the cut point diameter D50 Parameters ---------- Stk50 : float Stokes number for 50% collection efficiency = 0.23 RhoP : float particle density (g/cm3) Q : float volumetric flow rate (cm3/s) ...
b5b4905ef438862af0355eabd932f453a166a5f7
45,562
def rank_transform(arr: np.ndarray, centered=True) -> np.ndarray: """ Transform a 1-dim ndarray with arbitrary scalar values to an array with equally spaced rank values. This is a nonlinear transform. :param arr: input array :param centered: if the transform should by centered around zero :retu...
40a32abebb0c0bc834726046fe04ab81876cca98
45,563
def getMagic(fileName): """Get file magic.""" mime = magic.Magic(mime=True) mimeType = mime.from_file(fileName) return mimeType
3e39f6d80d494644eb4b1cbd956a2f37ec192083
45,564
import warnings def inspect_out(*args, **kwargs): """Deprecated: Please use inspect_hex()""" warnings.warn("inspect_out() is deprecated; use inspect_hex().", DeprecationWarning) return inspect_hex(*args, **kwargs)
2ef1d5077c62cd815f7ee1b707b461aed7f12129
45,565
import re def get_slurm_queue(): """Get a list of jobs currently in the Slurm queue. """ pattern = ('(?P<job_id>\d+)+\s+(?P<name>[-\w\d_\.]+)\s+(?P<user>[\w\d]+)\s+(?P<group>\w+)' '\s+(?P<account>[-\w]+)\s+(?P<partition>[-\w]+)\s+(?P<time_limit>[-\d\:]+)\s+' '(?P<time_left>[-\d\...
263ab66e0af15653b739bb08d419c58dc896618f
45,566
import importlib def DirDocNode(arg_dir, the_dir): """ This creates a non-clickable node. The text is taken from __doc__ if it exists, otherwise the file name is 'beautifuled'. """ full_module = arg_dir + "." + the_dir try: imported_mod = importlib.import_module(full_module) exce...
478fab481c4fe7c6243127c03d3e39dbec1d03ae
45,567
def is_move_slide_locked(start_hex: tuple, ending_hex: tuple, board_piece_locations: set[tuple]) -> bool: """ A move is 'slide locked' if a piece on a physical board cannot be slid from its current hex to an adjacent, empty hex without having to pick up the moving piece. This function expects start_hex and ...
46479e92d1ad5abe9e9309a4d01c74b236fc9287
45,568
import logging def face_detect(): """ { "faceimage":"img(base64 or url)" } :return: { "similar":1.0, "code":"00000", "errorinfo":"message", "result":true } """ try: face_base64 = request.json face_detect_result = FaceUtils.detect_face(face_ba...
ff9b5d3a4babeb863254e4596cec7567acb189b1
45,569
import traceback def uninstall(): """ Uninstall the Azure Monitor Linux Agent. This is a somewhat soft uninstall. It is not a purge. Note: uninstall operation times out from WAAgent at 5 minutes """ find_package_manager("Uninstall") if PackageManager == "dpkg": OneAgentUninstallCom...
e3db155f4ab4494d792ddc6af733b52573f26e76
45,570
def match_riccati(eq, f, x): """ A function that matches and returns the coefficients if an equation is a Riccati ODE Parameters ========== eq: Equation to be matched f: Dependent variable x: Independent variable Returns ======= match: True if equation is a Riccati ODE, F...
8f3228ad1af3f6777557bb12587d91706db5ce77
45,571
import re def find_nonAscii(text): """ Return the first appearance of a non-ASCII character (in a `Match` object), or `None`. """ regex = re.compile(r'([^\x00-\x7F])+') return re.search(regex, text)
bc299752eab5088214f9e1f62add388bf0721153
45,572
def linear_search(arr, x): """ Performs a linear search :param arr: Iterable of elements :param x: Element to search for :return: Index if element found else None """ l = len(arr) for i in range(l): if arr[i] == x: return i return None
2cb03eef6c9bb1d63df97c1e387e9cbfe703769a
45,573
def _filter(data, scopedData, scopedLogic): """ Filter 'scopedData' using the specified 'scopedLogic' argument. 'scopedData' argument can be: - a manually specified data array; - a JsonLogic rule returning a data array; - a JsonLogic 'var' operation returning part of the data object ...
2cef191bcd39bcf61f6a5d4dadb06c8861dec6ca
45,574
def _parse_age_specific_distribution(df, parameter, parameter_function, age_bins, full_factorial): """Age-specific parameter sampling from a numpy distribution Create a column in the DataFrame for each age bin, and sample from the specified distribution. Modifies the input DataFrame in place. """ ...
b5cb833b0adfcdf288bf616d24e32b5693fbb88e
45,575
import tarfile def generic_tarfile_verify(filepath, method): """ Verify that a tar/tgz/tbz/txz file is valid and working. :param filepath: Filename. :type filepath: str :param method: Tarfile read method. :type method: str """ if smart_is_tarfile(filepath): with tarfile.open(...
a7436d9a21b8fedb97c157aa00bc5154a016cf4c
45,576
def helicsFederateInfoSetCoreType(fi: 'helics_federate_info', coretype: 'int') -> "void": """ """ return _helics.helicsFederateInfoSetCoreType(fi, coretype)
562111a7f0968b7d1da298e5d3914340572b57e4
45,577
def score_hmm_unit_id_shuffle(bst, hmm, n_shuffles=250, normalize=False): """Docstring goes here. Returns ------- scores : array of size (n_events,) shuffled : array of size (n_shuffles, n_events) """ scores = score_hmm_logprob(bst=bst, hmm=hmm, ...
fb4d1cf399b2d9ba4a64ff29bd46d1042c637f50
45,578
def get_service_rel_tech_decr_by(tech_decreased_share, service_tech_by_p): """Iterate technologies with future less service demand (replaced tech) and get relative share of service in base year Parameters ---------- tech_decreased_share : dict Technologies with decreased service service...
83ed7d94f27c60d36e0da8f65d0d75c21135e949
45,579
import os def cmd_run(client, args): """Runs the application container. Parameters ---------- client : docker.client.DockerClient The Docker API client. args : argparse.Namespace A Namespace object populated with the values of the command line arguments. Returns ------- ...
def477a29e37227803b5e093a9b7ecedce851fe7
45,580
def step(grouped_seqs, stop_short=False): """ Generates tuples of lists of rows for every matching keys """ Empty = object() NoMore = object() EmptyVal = [] keys = [Empty] * len(grouped_seqs) vals = [EmptyVal] * len(grouped_seqs) def update(i, gs): try: k, rs = next...
9832db0cde8f1a40869b359ff8f37dc84cf43899
45,581
import copy def get_opencor_algorithm(requested_alg, config=None): """ Get a possibly alternative algorithm that OpenCOR should execute Args: requested_alg (:obj:`Algorithm`): requested algorithm config (:obj:`Config`, optional): configuration Returns: :obj:`Algorithm`: possibly ...
eb827f25b4e4255272d45a0b66c6e21d88aec4ca
45,582
import torch def wassertein_distance(u_x: Tensor, s_x: Tensor, u_y: Tensor, s_y: Tensor, is_target: bool = True, num_iter: int = 10): """ Computer Wassertein distance between two multivariate normal distribution X Y the covariance matrix of Y is assumed to be unit matrix if is_targ...
f96a934b3462f2fc4b7a60402b47bfc1b434e3df
45,583
import torch from typing import Tuple def mask_tokens(inputs: torch.Tensor, tokenizer: PreTrainedTokenizer, args) -> Tuple[torch.Tensor, torch.Tensor]: """Prepares masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.""" if tokenizer.mask_token is None: rai...
51d89a0f1fd5bad33c2cc39722cb1889439ca617
45,584
def to_json(p): """Returns a JSON-compatible dict of a plugin that can be serialized and sent to clients. """ name = (p['vimorg_name'] or p['github_repo_name'] or p['github_vim_scripts_repo_name']) author = (p['vimorg_author'].strip() or p['github_author'].strip()) plugin_manager_us...
8dfd7db473138859c880461090a436cf73a46948
45,585
def sms_in(request): """ sender - the number of the person sending the sms receiver - the number the sms was sent to msgdata - the message """ sender = request.GET.get("sender", None) receiver = request.GET.get("receiver", None) msgdata = request.GET.get("msgdata", None) if sender is...
14156fcbca2d68605187eaa271b42ca6e418438a
45,586
import sys def bytes_to_str(data): """bytes to string, used after data transform by internet.""" if isinstance(data, bytes): return data if sys.version_info.major == 2 else data.decode("ascii") if isinstance(data, dict): return dict(map(bytes_to_str, data.items())) if isinstance(data...
c61964a9955f2e1de5be5ec7398f0ce7e247c6a2
45,587
def best_model_based_selector(train_features, test_features, train_similarity_target, test_similarity_target, regressor): """ Function used to select the best model based selector """ model_based_score = 0 scaling_factors = ["0.25*mean", "0.5*mean", "median", "1.25*mean", "1.5*mean"] # scaling_factors = ["0.5*mean"...
98e608fa8ef913306fbf50bb5fe4aaf6f5c28bfd
45,588
def ex12(): """ Example 12 Example with state file name: Example12.py Copyright Log Opt Co., Ltd. """ m1 = Model() n = 9 #number of activities state = m1.addState("state") state.addValue( time=0, value=0 ) state.addValue( time=7, value=0 ) state.addValue( time=14, valu...
3d497273cc7bab96e33fc881ea53c08ae20f4342
45,589
import logging import os import subprocess def GetAllCmdOutput(args, cwd=None, quiet=False): """Open a subprocess to execute a program and returns its output. Args: args: A string or a sequence of program arguments. The program to execute is the string or the first item in the args sequence. cwd: I...
38a3908686c8020ffdbaac8c483c5faa08aaac51
45,590
def resultados_portafolio(p,w,C): """ Dados unos pesos de colocacion para un portafolio y teniendose los rendimientos y covarianzas historicas, se obtiene el rendimiento y volatilidad del portafolio `p`: matriz con rendimientos historicos del portafolio `w`:...
d1577b0be03f31e75cb253205a8f1b8b320bfc77
45,591
import argparse def arg_parser() -> dict: """Parse CLI arguments. Returns: dict: parsed arguments in dictionary """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("words", nargs="+", type=str, help="Sentence that will be translated") return parser.parse_args...
8962a16da185f145f8b5db335a65a2fd5d247f3c
45,592
def pml_prompt(): """ Reads user input given the PML prompt. """ return raw_input("pml:> ")
898dbc1ddb84a93b5c348eb3b28bcf089081a35b
45,593
def out_labels(G, q): """Returns a list of each of the labels appearing on the edges starting at `q` in `G`. Parameters ---------- G : labeled graph q : vertex in `G` Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(1, 2, label="a") >>> G.add_edge(1, 3, label="a")...
9849b96b562c74259b631907335a40f807e11709
45,594
import pathlib def get_project_root(name, context='local'): """find out where a repository lives context can be 'local' or 'remote' or a repo type ('sf', 'bb', 'git') """ is_private = name in private_repos is_private_value = name in private_repos.values() if is_private_value: value = ...
de93fde0eaa0536b77219489a101fadad2f16f3f
45,595
import os def relpath(path, start=os.curdir): """Return a relative version of a path flaming - copied from the python 2.7 source for os.path.relpath() because python 2.5 doesn't have this by default""" if not path: raise ValueError("no path specified") start_list = [x for x in os.path...
2bcdac47f9aef6e8247e29455b372f56f74d0209
45,596
def IKinBody(Blist, M, T, thetalist0, eomg, ev): """Computes inverse kinematics in the body frame for an open chain robot :param Blist: The joint screw axes in the end-effector frame when the manipulator is at the home position, in the format of a matrix with axes as the colu...
18b3f411c34e897e89df5488eced6cdfedd1d80e
45,597
from typing import BinaryIO def _read_uint8(stream: BinaryIO) -> int: """Read an unsigned 8-bit integer from the given byte stream.""" return helpers.read_int(stream, 1, signed=False)
504c22e69a157127585972634205816114fd3435
45,598
def config_homepath(homepath, logpath=False, cachepath=False): """ Fix path for ini file. :param homepath: Path to ini file. :type homepath: str :param logpath: True if processing log folder, False if not. Default is False. :type logpath: bool :param cachepath: True if processing cache fo...
249e2d2bbd4a9112f6b9a5c0c307acc7a7f9da7a
45,599