content
stringlengths
22
815k
id
int64
0
4.91M
def get_available_tf_versions(include_prerelease: bool = False) -> List[str]: """Return available Terraform versions.""" tf_releases = json.loads( requests.get("https://releases.hashicorp.com/index.json").text )["terraform"] tf_versions = sorted( [k for k, _v in tf_releases["versions"].i...
29,600
def relay_tagged(c, x, tag): """Implementation of tagged for Relay.""" assert tag.is_constant(int) rtag = get_union_ctr(tag.value, None) return rtag(c.ref(x))
29,601
def get_vf(Xf, Nf): """ compute the 1-spectrogram of the projection of a frequency band of the mix at 1 frequency on some directions :param Xf: T x I complex STFT of mix at a given f :param Nf: Mp x Md x I projection matrix :return: Vf: Mp x Ml x Nt magnitude spectrogram of projection...
29,602
def gen_data_code(stream, bits=ic.core_opts.data_bits): # type: (ic.Stream, int) -> dict """ Create a similarity preserving ISCC Data-Code with the latest standard algorithm. :param Stream stream: Input data stream. :param int bits: Bit-length of ISCC Data-Code (default 64). :return: ISCC Data-...
29,603
def file_get_size_in_bytes(path: str) -> int: """Return the size of the file in bytes.""" return int(os.stat(path).st_size)
29,604
def model_fn_builder( bert_config, init_checkpoint, layer_indexes, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstim...
29,605
def save_labeled_tree(args): """ A tree is stored as (sent: str, spans: list, labels, list, tags: list). """ with open(args.ifile, "r") as fr, \ open(args.ofile, "w") as fw: for tree in fr: tree = tree.strip() action = get_actions(tree) tags, sent,...
29,606
def git2pep440(ver_str): """ Converts a git description to a PEP440 conforming string :param ver_str: git version description :return: PEP440 version description """ dash_count = ver_str.count('-') if dash_count == 0: return ver_str elif dash_count == 1: return ver_str.s...
29,607
def rejoin(hyphenated, line): """Add hyphenated word part to line start, dehyphenating when required.""" first_part, hyphen = split_hyphen(hyphenated) second_part, rest = split_first_token(line) if is_same_vowel(first_part[-1], second_part[0]): # same vowel before and after hyphen keep_...
29,608
def msg_bytes(msg: Union[bytes, bytearray, zmq.Frame]) -> Union[bytes, bytearray]: """Return message frame as bytes. """ return msg.bytes if isinstance(msg, zmq.Frame) else msg
29,609
def test_build_symmetry_operations(): """Check that all the symmetry operations are built correctly.""" one = np.identity(4) two = np.zeros((4, 4)) two[1, 0] = 1.0 two[0, 1] = 1.0 two[2, 2] = 1.0 two[3, 3] = 1.0 three = np.zeros((4, 4)) three[0, 0] = 1.0 three[1, 1] = 1.0 t...
29,610
def abort(msg): """ Prints the given error message and aborts the program with a return code of 1. """ click.secho(msg, fg='red') sys.exit(1)
29,611
def iucr_string(values): """Convert a central value (average) and its s.u. into an IUCr compliant number representation. :param values: pair of central value (average) and s.u. :type values: tuple((float, float)) :return: IUCr compliant representation :rtype: str """ if values[1] == 0 or va...
29,612
def augment_signals(ds, augment_configs): """ Apply all augmentation methods specified in 'augment_config' and return a dataset where all elements are drawn randomly from the augmented and unaugmented datasets. """ augmented_datasets = [] for conf in augment_configs: aug_kwargs = {k: v for k...
29,613
def sse_pack(d): """For sending sse to client. Formats a dictionary into correct form for SSE""" buf = '' for k in ['retry','id','event','data']: if k in d.keys(): buf += '{}: {}\n'.format(k, d[k]) return buf + '\n'
29,614
def proj_beta_model(r2d_kpc, n0, r_c, beta): """ Compute a projected beta model: P(R) = \int n_e dl at given R Parameters ---------- - r2d_kpc: array of projected radius at which to compute integration - n0 : normalization - r_c : core radius parameter - beta : slope of the profile...
29,615
def read_raw_datafile(filename): """ Read and format the weather data from one csv file downloaded from the climate.weather.gc.ca website. """ dataset = pd.read_csv(filename, dtype='str') valid_columns = [ 'Date/Time', 'Year', 'Month', 'Day', 'Max Temp (°C)', 'Min Temp (°C)', 'Me...
29,616
def zeros(shape, backend=TensorFunctions): """ Produce a zero tensor of size `shape`. Args: shape (tuple): shape of tensor backend (:class:`Backend`): tensor backend Returns: :class:`Tensor` : new tensor """ return Tensor.make([0] * int(operators.prod(shape)), shape, back...
29,617
def delete(name: str): """Remove a Maestral configuration.""" if name not in list_configs(): click.echo("Configuration '{}' could not be found.".format(name)) else: from maestral.config.base import get_conf_path for file in os.listdir(get_conf_path("maestral")): if file.s...
29,618
def formatLabels(labels, total_time, time): """Format labels into vector where each value represents a window of time seconds""" time_threshold = 1 num_windows = total_time // time Y = np.zeros(num_windows) for label in labels: start = label['start'] duration = label['duration'] ...
29,619
def line(line_def, **kwargs): """Highlights a character in the line""" def replace(s): return "(%s)" % ansi.aformat(s.group()[1:], attrs=["bold", ]) return ansi.aformat( re.sub('@.?', replace, line_def), **kwargs)
29,620
def ceil_datetime_at_minute_interval(timestamp, minute): """ From http://stackoverflow.com/questions/13071384/python-ceil-a-datetime-to-next-quarter-of-an-hour :param timestamp: :type timestamp: datetime.datetime :param minute: :type minute: int :return: :rtype: datetime.datetime ""...
29,621
def iterate_fasta(fasta, database = 'data/gsaid.db'): """ Function to iterate through aligned fasta file *non threaded* :param cursor: sqlite database handler :param fasta: file containing sequences :param ref: file containing reference sequence, default-> NC_04552.fa """ handle = convert_fa...
29,622
def make_response( activated=True, expires_in=0, auto_activation_supported=True, oauth_server=None, DATA=None, ): """ Helper for making ActivationRequirementsResponses with known fields """ DATA = DATA or [] data = { "activated": activated, "expires_in": expires_i...
29,623
def post_create_manager_config( api_client, id, log_files=None, configuration_files=None, ports=None, process_manager=None, executables=None, **kwargs ): # noqa: E501 """post_create_manager_config # noqa: E501 Create a new plugin manager configuration. If no params are provide...
29,624
def get_long_desc() -> str: """ read long description and adjust master with version for badges or links only for release versions (x.y.z) """ get_version() release = re.compile(r'(\d+\.){0,2}\d+$') with open(os.path.join(wd, 'README.md')) as fd: if _version == '0.0.0' or not release.mat...
29,625
def get_current_user(): """Load current user or use anon user.""" return auth.User( uuid=None, login='anon', password='', name='anon', visiblity=None, language=None, last_seen=None, )
29,626
def validate(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*'): """Check whether the check digit is valid.""" try: valid = checksum(number, alphabet) == 1 except Exception: # noqa: B902 raise InvalidFormat() if not valid: raise InvalidChecksum() return number
29,627
def pct_chg(x: Union[np.ndarray, pd.Series]) -> np.ndarray: """Percentage change between the current and a prior element. Args: x: A numpy.ndarray or pandas.Series object Returns: A numpy.ndarray with the results """ x = x.astype("float64") if isinstance(x, pd.DataFrame): ...
29,628
def calc_gram_matrix(input_mat): """ Paper directly mentions about calculating Gram matrix: G_{ij}^l = \sum_k F_{ij}^l F_{jk}^l i and j stand for filter position and k stands for position in each filters. If matrix A is composed of vectors, a1, a2, a3, etc, e.g. A = [a1, a2, a3, ...] note...
29,629
def parse_annotations_with_food_part_template(annotations, premise): """ """ annotations_aggregated = [] annotations_reported = [] rows_grouped_by_premises = annotations[annotations["premise"] == premise] for hypothesis in rows_grouped_by_premises["hypothesis"].unique(): rows_grouped_by_hy...
29,630
def filter_dictionary(dictionary, filter_func): """ returns the first element of `dictionary` where the element's key pass the filter_func. filter_func can be either a callable or a value. - if callable filtering is checked with `test(element_value)` - if value filtering is checked ...
29,631
def restart_workflow(workflow_id, clear_data=False, delete_files=False): """Restart a workflow with the latest spec. Clear data allows user to restart the workflow without previous data.""" workflow_model: WorkflowModel = session.query(WorkflowModel).filter_by(id=workflow_id).first() WorkflowProcesso...
29,632
def create_template_alias(AwsAccountId=None, TemplateId=None, AliasName=None, TemplateVersionNumber=None): """ Creates a template alias for a template. See also: AWS API Documentation Exceptions :example: response = client.create_template_alias( AwsAccountId='string', Templ...
29,633
def spike_lmax(S, Q): """Maximum spike given a perturbation""" S2 = S * S return ((1.0 / Q) + S2) * (1 + (1.0 / S2))
29,634
def get_engine(): """Returns the db engine.""" if not hasattr(g, 'sqlite_engine'): g.sqlite_engine = create_engine('sqlite:///' + app.config['DATABASE'], echo=True) return g.sqlite_engine
29,635
def is_on_curve(point): """Returns True if the given point lies on the elliptic curve.""" if point is None: # None represents the point at infinity. return True x, y = point return (y * y - x * x * x - curve.a * x - curve.b) % curve.p == 0
29,636
def find_closest_point( odlc: Dict[str, float], boundary_points: List[Dict[str, float]], obstacles: List[Dict[str, float]], ) -> Tuple[Dict[str, float], List[float]]: """Finds the closest safe point to the ODLC while staying within the flight boundary Parameters ---------- odlc : Dict[str, ...
29,637
def test_T1(): """ >>> as_input(T1) >>> main() 5.5 """
29,638
def _get_band_edge_indices( band_structure: BandStructure, tol: float = 0.005, ) -> Tuple[Dict[Spin, List[int]], Dict[Spin, List[int]]]: """ Get indices of degenerate band edge states, within a tolerance. Parameters ---------- band_structure : BandStructure A band structure. tol...
29,639
def spectra(args): """subroutine for spectra subcommand """ vcf = cyvcf2.VCF(args.vcf, gts012=True) if args.population: spectra_data = Counter() for variant in vcf: spectra_data[variant.INFO['mutation_type']] += 1 spectra = pd.DataFrame(spectra_data, ...
29,640
def make_val_dataloader(data_config, data_path, task=None, data_strct=None): """ Return a data loader for a validation set """ if not "val_data" in data_config or data_config["val_data"] is None: print_rank("Validation data list is not set", loglevel=logging.DEBUG) return None loader_type ...
29,641
def _get_urls(): """Stores the URLs for histology file downloads. Returns ------- dict Dictionary with template names as keys and urls to the files as values. """ return { "fsaverage": "https://box.bic.mni.mcgill.ca/s/znBp7Emls0mMW1a/download", "fsaverage5": "https://box...
29,642
def guid_bytes_to_string(stream): """ Read a byte stream to parse as GUID :ivar bytes stream: GUID in raw mode :returns: GUID as a string :rtype: str """ Data1 = struct.unpack("<I", stream[0:4])[0] Data2 = struct.unpack("<H", stream[4:6])[0] Data3 = struct.unpack("<H", stream[6:8])[0...
29,643
def test_explained_inertia_decreases(mca): """Check the explained inertia decreases.""" assert test_util.is_sorted(mca.explained_inertia)
29,644
def thaiword_to_time(text: str, padding: bool = True) -> str: """ Convert Thai time in words into time (H:M). :param str text: Thai time in words :param bool padding: Zero padding the hour if True :return: time string :rtype: str :Example: thaiword_to_time"บ่ายโมงครึ่ง") ...
29,645
def _build_index_mappings(name, data_prefix, documents, sizes, num_samples, seq_length, seed): """Build doc-idx, sample-idx, and shuffle-idx. doc-idx: is an array (ordered) of documents to be used in training. sample-idx: is the start document index and document offset for each ...
29,646
def get_grains(ng,gdmin,angrange0,angrange1,two_dim): """ Get specified number of grains with conditions of minimum distance and angle range. """ dang = (angrange1-angrange0) /180.0 *np.pi /ng grains= [] ig = 0 dmin = 1e+30 while True: if ig >= ng: break pi= np.zeros((3,)...
29,647
def two_loops(N: List[int]) -> List[int]: """Semi-dynamic programming approach using O(2n): - Calculate the product of all items before item i - Calculate the product of all items after item i - For each item i, multiply the products for before and after i L[i] = N[i-1] * L[i-1] if i != 0 else 1 ...
29,648
def make_slurm_queue(dirmain, print_level=0): """get queue list from slurm """ # Check slurm list_ids = [] list_scripts = [] usr = os.environ.get('USER') proc = subprocess.run(['squeue', "-u", usr, "-O", "jobid:.50,name:.150,stdout:.200"], capture_output=True) all_info_user = proc.std...
29,649
def test_undeclared_always_write(): """Test error raised if always write specified that isn't in PROP_TYPES.""" with pytest.raises(XDLUndeclaredAlwaysWriteError): TestUndeclaredAlwaysWrite()
29,650
def in_test_directory(): """ Change to a temporary empty directory for testing purposes. """ old_cwd = os.getcwd() tempdir = tempfile.mkdtemp() os.chdir(tempdir) try: yield finally: os.chdir(old_cwd) shutil.rmtree(tempdir, onerror=_remove_readonly)
29,651
def read_renku_version_from_dockerfile(path: Union[Path, str]) -> Optional[str]: """Read RENKU_VERSION from the content of path if a valid version is available.""" path = Path(path) if not path.exists(): return docker_content = path.read_text() m = re.search(r"^\s*ARG RENKU_VERSION=(.+)$", ...
29,652
def run_package(): """ Entry point for running a Kedro project packaged with `kedro package` using `python -m <project_package>.run` command """ project_context = load_package_context(project_path=Path.cwd(), package_name=Path(__file__).resolve().parent.name) project_context.run()
29,653
def zero_mean(framed): """Calculate zero-mean of frames""" mean = np.mean(framed, axis=1) framed = framed - mean[np.newaxis, :].T return framed
29,654
def now(): """ 返回当前时间 """ return timezone.now()
29,655
def calc_thickness_of_wing(XFOILdirectory, chordArray2): """ calculation wing thickness list """ # open airfoil data data = io_fpa.open2read(os.path.join("data", XFOILdirectory, "foil.dat")) # make airfoil list xlist = [float(i.split()[0]) for i in data[1:]] ylist = [float(i.split()[1])...
29,656
def scholarly_init_connection(): """ Bind TorRequest to Scholarly service Parameters ---------- No arguments Returns ------- Nothing """ while True: # assign new tor identity ips = assign_new_ip(text=True) # use the tor request for scholarly tor_...
29,657
def rgb_to_hex(r, g, b): """Turn an RGB float tuple into a hex code. Args: r (float): R value g (float): G value b (float): B value Returns: str: A hex code (no #) """ r_int = round((r + 1.0) / 2 * 255) g_int = round((g + 1.0) / 2 * 255) b_int = round((b + 1...
29,658
def test_run_string() -> None: """Valida run() called with a single string command.""" cmd = "echo 111 && >&2 echo 222" old_result = subprocess.run( cmd, shell=True, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) ...
29,659
def calc_R(x,y, xc, yc): """ calculate the distance of each 2D points from the center (xc, yc) """ return np.sqrt((x-xc)**2 + (y-yc)**2)
29,660
def get_followers_list(user_url, driver, followers=True): """ Returns a list of users who follow or are followed by a user. Parameters ---------- user_url: string driver: selenium.webdriver followers: bool If True, gets users who are followers of this user. If False, gets us...
29,661
def main(): """Run preprocessing process.""" parser = argparse.ArgumentParser( description="Normalize dumped raw features (See detail in parallel_wavegan/bin/normalize.py)." ) parser.add_argument( "--metadata", type=str, required=True, help="directory including fe...
29,662
def test_tag(): """Test that the tag attribute works correctly.""" class DummyModel(Model): """The simplest instance of Model possible.""" x = DummyModel() x.tag['foo']['bar'] = 5 assert len(x.tag.keys()) == 1 assert len(x.tag['foo'].keys()) == 1 assert x.tag['foo']['bar'] == 5 ...
29,663
def test(): """ The empty string becomes a2582a3a0e66e6e86e3812dcb672a272. AoC 2017 becomes 33efeb34ea91902bb2f59c9920caa6cd. 1,2,3 becomes 3efbe78a8d82f29979031a4aa0b16a9d. 1,2,4 becomes 63960835bcdc130f0b66d7ff4f6a5a8e. """ tests = { '': 'a2582a3a0e66e6e86e3812dcb672a272', 'AoC 2017': '3...
29,664
def policy_to_dict(player_policy, game, all_states=None, state_to_information_state=None, player_id: Optional = None): """Converts a Policy instance into a tabular policy represented as a dict. This is compatible with the C++ TabularEx...
29,665
def compressed_gw(Dist1,Dist2,p1,p2,node_subset1,node_subset2, verbose = False, return_dense = True): """ In: Dist1, Dist2 --- distance matrices of size nxn and mxm p1,p2 --- probability vectors of length n and m node_subset1, node_subset2 --- subsets of point indices. This version of the qGW code...
29,666
def force_gather(*pargs): """Like force_ask(), except more insistent. In addition to making a single attempt to ask a question that offers to define the variable, it enlists the process_action() function to seek the definition of the variable. The process_action() function will keep trying to define ...
29,667
def get_stats(service: googleapiclient.discovery, videos_list: list): """Get duration, views and live status of YouTube video with their ID :param service: a YouTube service build with 'googleapiclient.discovery' :param videos_list: list of YouTube video IDs :return items: playlist items (videos) as a l...
29,668
def FactoredIntegers(): """ Generate pairs n,F where F is the prime factorization of n. F is represented as a dictionary in which each prime factor of n is a key and the exponent of that prime is the corresponding value. """ yield 1,{} i = 2 factorization = {} while True: if ...
29,669
def NotecardExceptionInfo(exception): """Construct a formatted Exception string. Args: exception (Exception): An exception object. Returns: string: a summary of the exception with line number and details. """ name = exception.__class__.__name__ return sys.platform + ": " + name...
29,670
def load_test_dataset(cfg: Dict) -> Tuple[Tuple[List]]: """Read config and load test dataset Args: cfg (Dict): config from config.json Returns: Tuple[Tuple[List]]: Test dataset """ X_test, y_test, test_prompt_ids = read_dataset( cfg.preprocess_data_args["test_path"], ...
29,671
def create_client_dir(client_dir=None): """Create client directories""" if not os.path.exists(client_dir): os.makedirs(client_dir)
29,672
def clear_caches() -> None: """ Clear all Caches created by instagramy in current dir """ return shutil.rmtree(cache_dir, ignore_errors=True)
29,673
def linha(tam=20): """ -> Cria uma linha :param tam: (opcional) Determina o tamanho da linha :return: Sem retorno """ print('-'*tam)
29,674
def SingleCameraCalibration_from_xml(elem, helper=None): """ loads a camera calibration from an Elementree XML node """ assert ET.iselement(elem) assert elem.tag == "single_camera_calibration" cam_id = elem.find("cam_id").text pmat = numpy.array(numpy.mat(elem.find("calibration_matrix").text)) r...
29,675
def contrast_augm_cv2(images,fmin,fmax): """ this function is equivalent to the numpy version, but 2.8x faster """ images = np.copy(images) contr_rnd = rand_state.uniform(low=fmin,high=fmax,size=images.shape[0]) for i in range(images.shape[0]): fac = contr_rnd[i] images[i...
29,676
def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle_load('preprocess.p')
29,677
def detection_layer(config, rois, mrcnn_class, mrcnn_bbox, image_meta): """Takes classified proposal boxes and their bounding box deltas and returns the final detection boxes. Returns: [batch, num_detections, (y1, x1, y2, x2, class_score)] in pixels """ # Currently only supports batchsize 1 ...
29,678
def connectedSocketDiscover(): """ Try to discover the internal address by using a connected UDP socket. @return: a L{Deferred} called with the internal address. """ def cb(address): protocol = DatagramProtocol() listeningPort = reactor.listenUDP(0, protocol) protocol.tr...
29,679
def construct_source_plate_not_recognised_message( params: Dict[str, str] ) -> Tuple[List[str], Optional[Message]]: """Constructs a message representing a source plate not recognised event; otherwise returns appropriate errors. Arguments: params {Dict[str, str]} -- All parameters of the plate e...
29,680
def grab_kaeri_nuclide(nuc, build_dir="", n=None): """Grabs a nuclide file from KAERI from the web and places it a {nuc}.html file in the build directory. Parameters ---------- nuc : str, int nuclide, preferably in name form. build_dir : str, optional Directory to place html fi...
29,681
def odd(x): """True if x is odd.""" return (x & 1)
29,682
def sparse_transformer_local(): """Set of hyperparameters for a sparse model using only local.""" hparams = common_hparams.basic_params1() hparams.max_length = 4096 hparams.batch_size = 4096 hparams.add_hparam("max_target_length", 4096) hparams.add_hparam("add_timing_signal", False) hparams.add_hparam("lo...
29,683
def make_aperture_mask(self, snr_threshold=5, margin=4): """Returns an aperture photometry mask. Parameters ---------- snr_threshold : float Background detection threshold. """ # Find the pixels that are above the threshold in the median flux image median = np.nanmedian(self.flux, ...
29,684
def test_relative_content_url_with_object(): """This function tests creating a content mention with a relative content URL but with a Khoros object. .. versionadded:: 2.4.0 :returns: None """ title, url, content_id = get_content_test_data(relative_url=True) khoros = Khoros() print() #...
29,685
def verify_json_message(json_message, expected_message): """ Verify JSON message value. """ LOGGER.debug(json_message) LOGGER.debug(expected_message) try: message = json.loads(json_message) except TypeError: message = json_message validation = [KEY_SITE_ID, KEY_VARIAB...
29,686
def verify_password(username, password): """Verify the password.""" if username in users: return check_password_hash(users.get(username), password) return False
29,687
def data_mnist(one_hot=True): """ Preprocess MNIST dataset """ # the data, shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(X_train.shape[0], FLAGS.IMAGE_ROWS, ...
29,688
def get_file_paths_by_pattern(pattern='*', folder=None): """Get a file path list matched given pattern. Args: pattern(str): a pattern to match files. folder(str): searching folder. Returns (list of str): a list of matching paths. Examples >>> get_file_paths_by_pattern(...
29,689
def pval_two(n, m, N, Z_all, tau_obs): """ Calculate the p-value of a two sided test. Given a tau_obs value use absolute value to find values more extreme than the observed tau. Parameters ---------- n : int the sum of all subjects in the sample group m : int number of ...
29,690
def make_where_tests(options): """Make a set of tests to do where.""" test_parameters = [ { "input_dtype": [tf.float32, tf.int32], "input_shape_set": [([1, 2, 3, 4], [1, 2, 3, 4]),], "use_where_v2": [False, True], }, { "input_dtype": [tf.float32, tf.int32],...
29,691
def test_then_1() -> None: """test_then_1.""" f: Parser = token("foo") def f_then(result: ParseResult) -> None: assert result.tokens == ["foo"] def f_catch(result: ParseResult) -> None: assert False, "成功した場合は空振りする必要がある。" assert f.exec("foobar").then(f_then).catch(f_catch)
29,692
def install(lib_name): """ Installes a library from a local file in ./libs Parameters ---------- lib_name: str the name of the library that will be installed Returns ------- nothing Exception --------- Raises an Exception if the library can't be installed from ...
29,693
def test_plot_state(sampler, tmpdir, filename, track_gradients): """Test making the state plot""" x = np.arange(10) sampler.min_likelihood = x sampler.max_likelihood = x sampler.iteration = 1003 sampler.training_iterations = [256, 711] sampler.train_on_empty = False sampler.population_it...
29,694
def classify_pixel(input_data, classifier, threads=8, ram=4000): """ Runs a pre-trained ilastik classifier on a volume of data Adapted from Stuart Berg's example here: https://github.com/ilastik/ilastik/blob/master/examples/example_python_client.py Arguments: input_data: data to be classifi...
29,695
def invite_accepted_candidates(): """Invites accepted candidates to create an account and set their own password.""" form = InviteAcceptedCandidatesForm() if form.validate_on_submit(): selected = [ Candidate.query.filter_by(id=c).first() for c in form.selected_candidates.data.split(',') ] us...
29,696
def plot_perc_miscoordination(joint_actions, state, iter_avg, n_runs, num_episodes, run=None): """Plot percentage of miscoordination per agent""" perc_joint_actions = shape_dim_for_plot(iter_avg, n_runs, joint_actions, run) means = perc_joint_actions.mean(axis=2) x_axis = np.arange(0, num_episodes/iter_...
29,697
def ramp_overlap(x0, y0, w0, h0, angle0, x1, y1, w1, h1, angle1): """Calculates the overlap area between two ramps.""" # Check if bounding spheres do not intersect. dw0 = _rect_diagonal(w0, h0) dw1 = _rect_diagonal(w1, h1) if not bounding_circles_overlap(x0, y0, dw0, x1, y1, dw1): return 0. # Check if...
29,698
def url_external(path, query): """Generate external URLs with HTTPS (if configured).""" try: api_url = request.url_root if settings.URL_SCHEME is not None: parsed = urlparse(api_url) parsed = parsed._replace(scheme=settings.URL_SCHEME) api_url = parsed.geturl(...
29,699