content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def dec2hp(dec): """ Converts Decimal Degrees to HP Notation (float) :param dec: Decimal Degrees :type dec: float :return: HP Notation (DDD.MMSSSS) :rtype: float """ minute, second = divmod(abs(dec) * 3600, 60) degree, minute = divmod(minute, 60) hp = degree + (minute / 100) + (s...
f081e69c2bede5143a769729f1eb8df9aa3bf8c7
626,937
def mean_normalization(x): """ This script is to do mean normalization for DataFrame Parameter: x: format: DataFrame rows:feature columns:samples Returns: output:DataFrame; after mean normalization. rows:feature columns:samples """ for ...
15905088d458c7a9b0e19b1f1d558fb2541b18dc
626,939
import re def camel_to_underscore(camelcase): """ Convert a camelcased string to underscore_delimited (tweaked from this StackOverflow answer) http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case """ s1 = re.sub('(^/_)([A-Z][a-z]+)', r'\1_\2', camel...
d4a11003232f52c5e412cdebb759be63be402f2f
626,944
import torch def prepare_device(numberOfGpusToBeUsed): """ Function to setup GPU device if available. The function gets the indices of the GPU devices that are used for DataParallel. Parameters ---------- numberOfGpusToBeUsed : int Number of GPUs to be used ...
1ff00c41937421c6894dde80cb1145e443906156
626,945
def handles_url( url ): """ Does this storage driver handle this kind of URL? """ return ".s3.amazonaws.com" in url
e74d7365ffd07da6ba9c9988ea00432d28b99c1a
626,946
def after(node, values, positions, places=False): """ Returns the set of all nodes that are after the given node. """ n = node[positions["_n"]] if places is not False: try: return [values[n + places]] except IndexError: return list() sent_len = node[posit...
45a5bfcac0d9d41902dd9c8231f976f1164cb03e
626,949
def remove_empty(dictionary): """Removes empty entries from a dictionary.""" for key in list(dictionary.keys()): if dictionary.get(key) is None: del dictionary[key] return dictionary
3b54f3fd97560ebead9ba32f44ea301e066a1440
626,954
import torch def div_func(inputs: torch.Tensor, other: float, unsqueeze_dim: int = 1): """ Overview: Divide ``inputs`` by ``other`` and unsqueeze if needed. Arguments: - inputs (:obj:`torch.Tensor`): the value to be unsqueezed and divided - other (:obj:`float`): input would be divi...
76fcea6458b713d164e1bc0ab9551b59bad3a2c0
626,957
def parse_namefile_ini(line): """ Parse a line from a .ini file to get the described file location Parameters ---------- line : str Line from the .ini file, containing the location of a file of interest. Returns ------- processed_line : str ...
800f3551f37e40a2e9a9ca1d11695be4d1adfe77
626,963
def normalize(vals): """normalize a series of values using min/max normalization""" return (vals-vals.min())/(vals.max()-vals.min())
95288d79b4100a031c60dbd2eb03e20b9aff6490
626,968
def prepare_args(args): """ Prepare arguments to be used as the API expects it :param args: demisto args :return: transformed args """ args = dict((k.replace("-", "_"), v) for k, v in list(args.items())) if "is_public" in args: args["is_public"] = args["is_public"] == "True" retu...
eaf0d7f7f30390d02481ff01e9eea4a7b3262ef2
626,969
def centre(images): """Mapping from {0, 1, ..., 255} to {-1, -1 + 1/127.5, ..., 1}.""" return images / 127.5 - 1
73ea422309ffc4c3b90d2f1798ce45e34cc035d1
626,971
def bounce_easeout(pos): """ Easing function for animations: Bounce Ease Out """ if pos < 4 / 11.0: return (121 * pos * pos) / 16.0 if pos < 8 / 11.0: return (363 / 40.0 * pos * pos) - (99 / 10.0 * pos) + (17 / 5.0) if pos < 9 / 10.0: return (4356 / 361.0 * pos * pos) - (...
9974d6e57291350378bb10757397504755a2e17d
626,972
def filter_traceback_list(tl): """ Returns the subset of `tl` that originates in creator-written files, as opposed to those portions that come from Ren'Py itself. """ rv = [ ] for t in tl: filename = t[0] if filename.endswith(".rpy") and not filename.replace("\\", "/").startswi...
0fa40c64f8c423c5acebf34d0609f32338620808
626,973
def poly_eval_horner(coefs, x): """ Evaluates the polynomial whose coefficients are given in coefs on the value x using the Horner's method. This function is much faster than regular polynomial evaluation. Polynomial coefficient are stored in coefs from the lowest power to the highest. x is required...
4dd16ba8e73510b74a1d18e8a38dbe0ae0ac70d8
626,975
def serialize_results(results : dict) -> str: """Serialize a results dict into something usable in markdown.""" n_first_col = 20 ans = [] for k, v in results.items(): s = k + " "*(n_first_col-len(k)) s = s + f"| {v[0]*100:.1f} | {v[1]*100:.1f} |" ans.append(s) return "\n".j...
c64ba7bbf898e3085290615d163401b7c2382ca6
626,979
import pickle import base64 def decode(something): """ Decodes from base-64 pickled object. """ return pickle.loads(base64.b64decode(something))
dfaffa998e30d395afe3b7ae6a620b656ead585a
626,984
def retreive_filename(path): """ Truncates absolute file directory and returns file name. Parameters ---------- path : 1-dimensional string containing absolute directory of a file, in /<dir>/<filename>.<foramt> format. Returns ------- filename : <filename> portion of the given file...
0841fada4380280c6ac85fe617bca0d1b47a702c
626,985
def is_density_matrix(input): """Determine if the input array can be a density matrix. Args: input (array): input array. Returns: bool: whether input can be a density matrix. """ return input.shape[-1] == 2 and input.shape[-2] == 2
42608dc18a075279c66fae801fced6b118dfea14
626,987
import bz2 import pickle def read_pickle(filepath, compressed=False): """ Reads the summarized background from a compressed binary file Parameters ---------- filepath: Filepath to compressed file compressed: Whether to use bz2 compression. Defaults to False """ if compress...
b2fd35ed131f4dbedaaf9b8d3904291012b54b6f
626,988
def test_step(x, model, estimator, **config): """Test the `model` given the mini-batch of observations `x` and the gradient estimator/evaluator `estimator`""" loss, diagnostics, output = estimator(model, x, backward=False, **config) return diagnostics
f1af20d3ecdcf9f9b7a2c4213fc51aa2b6660b0b
626,992
def get_task_version(taskf): """return a version for a taskf. This is wrapper around taskf.get_version() that will not raise an exception if a tool is not installed but will return None instead. """ try: version = taskf().get_version() except Exception as ex: msg = str(ex) ...
cfafc774fa969a0eb3acad13f3acdf47b8de722e
626,993
def as_bool(x): """ Returns True if the given string in lowercase equals "true", False otherwise. """ return True if x.lower() == "true" else False
abb90349a44c8e8c433d7a360809624b47b1f66b
626,994
from typing import Union import re import operator def condition_matches(value: Union[int, float], format_: str) -> bool: """ Return true if the value matches the condition in the pattern. """ match = re.search(r"\[(>|>=|<|<=|=)(\d*(?:\.\d*)?)\]", format_) if not match: return True op...
bd12e5ded2d01c9e6b99e89e7747d59dea1d9ac4
626,997
def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. Preserve all white space except added line breaks consume the space on which they break the line. Don't wrap long words, thus the output text may have line...
4790fe4e837305a9ab49bc211b6cf4e9be3b5af9
627,003
def task2(a): """ Function that calculates square value of argument Input: one integer Output: one integer """ return a**2 #return iloczyn
19afd47664de55e3bb23ed405e26fcfcbbab0fa3
627,004
def bucopt(self, method="", nmode="", shift="", ldmulte="", rangekey="", **kwargs): """Specifies buckling analysis options. APDL Command: BUCOPT Parameters ---------- method Mode extraction method to be used for the buckling analysis: LANB - Block Lanczos SUBSP...
0c1256711940b6511ff6a7e6a5aa9ab0b0d2d625
627,008
def getNthFromLast(head, n): """ Take two pointers one starting from head the other starting from the nth node, so when the latter node reaches the end the former would have reached the Lenth-n nodes """ ptr = head c = 0 while ptr and c < n: # We want the nptr to reach the l...
e80afde6f7e5ca9ec5011ac4a3a3bc3ff684ebca
627,010
def compareNodes(node_1, node_2): """ Compares two nodes to check if they are equal :param node_1: The first node to check :type node_1: Node type :param node_2: The second node to check :type node_2: Node type :returns: True or False :rtype: Boo...
2b7c1d2d748cd4732eff1fd7677c10fc1fff2bd4
627,011
from datetime import datetime def now() -> datetime: """Return the datetime object of the current time. :return: datetime object represeting current time """ return datetime.now().astimezone()
e1ca72a8cf22b1614a406a3d44148fb509d262a8
627,014
def jarManifest(target, source, env, for_signature): """Look in sources for a manifest file, if any.""" for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": return src return ''
83bdb3cd01e83f3ba949e2a9faa11f8c98d1589a
627,015
def correct_time_dilation(df): """Short summary. Parameters ---------- df : Pandas DataFrame The dataframe containing the photometry of all events. Returns ------- Pandas DataFrame The same dataframe with undilated times. """ for idx, row in df.iterrows(): ...
b7aae7a26279d5629a367cf49e898a5543981dd9
627,016
def _GetLowerBoundBuildNumber( lower_bound_build_number, upper_bound_build_number, # The default window is the number of builds # Findit will look back for an analysis. default_build_number_window_size=500): """Determines the lowest bound build number relative to an upper bound. Args: lower...
4d148de8dcae8123feb8095871f6a1f622694d25
627,019
def get_related_fields(model): """ Returns all the fields of `model` that hold the link between referencing objects and the referenced object (`model`). :param model: orphaned model class :returns: list of fields of `model` that hold references via dependent objects """ return [ f f...
b5abe1e4bf4e0ada8cf60d113fb472d59f67b98b
627,021
def weekend_integration_1_SS_idx_rule(M): """ The index for type 1 weekend-tour type integration constraints is (day, week, window, tour type). :param M: Model :return: Constraint index rule """ return [(j, w, i, t) for j in M.DAYS for w in M.WEEKS for i in M.WINDOW...
4b0e1e8c64097592fdf43ae9bc43ac547c0eebde
627,022
import yaml def load_config(filename: str) -> dict: """ Load a configuration file as YAML """ with open(filename) as fh: config = yaml.safe_load(fh) return config
da7f02c638f1ccb684b39d3b2b24d7e4e8587f08
627,025
import torch from typing import Tuple def normalize_sizes(y_pred: torch.Tensor, y_true: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """Normalize tensor sizes Args: y_pred (torch.Tensor): the output of the model If a 3-dimensional tensor, reshapes to a matrix y_true (torch....
13d551034f96a84f2215a92f60f2a7649c906bee
627,026
import math def cos_anneal(e0, e1, t0, t1, e): """ ramp from (e0, t0) -> (e1, t1) through a cosine schedule based on e \in [e0, e1] """ alpha = max(0, min(1, (e - e0) / (e1 - e0))) # what fraction of the way through are we alpha = 1.0 - math.cos(alpha * math.pi/2) # warp through cosine t = alpha * t1 ...
e6f1eee3b35e6b85d4dc301e6aa8b63b180c407e
627,028
def aggregate_actions_and_lengths(actions_per_frame): """Identify the actions in a video and count how many frames they last for. Given a list of actions (e.g. ['a', 'a', 'a', 'b', 'b']) summarise the actions and count their lifespan. For the example input just given, the function returns (['a', 'b'], [3, ...
d0c433957e30cbafc5b24c38ce6b5df7696378e8
627,029
def get_name_from_attributes(variant): """Generates ProductVariant's name based on its attributes.""" values = [ attributechoice_value.title for attributechoice_value in variant.attribute_map.values() ] return " / ".join(values)
f6bf117fb38b05d2a08eae4ce178e19381ebcdeb
627,036
import operator import pkgutil def _get_modules_names(package): """Get names of modules in package""" return sorted( map(operator.itemgetter(1), pkgutil.walk_packages(package.__path__, '{0}.'.format(package.__name__))))
c81066f5d35da3474a4e1790db3ba64ada9f688f
627,037
def insert_sort(input_list): """Insert sort function.""" if isinstance(input_list, list): for i in range(len(input_list) - 1): for j in range(i + 1, 0, -1): if input_list[j] < input_list[j - 1]: temp = input_list[j] input_list[j] = inpu...
7f8d2ec558cda16de3043d4d42144abed6305a01
627,038
from functools import reduce from operator import add def fitness(individual, target): """ Calculutes the fitness of an individual, lower is better :param individual: individual to calculate fitness :param target: the target value to achieve """ result = reduce(add, individual, 0) return a...
4bb7e0bbefad871879cb2d5109f675b437d99f9c
627,039
def transform_to_bool(value): """ Transforms a certain set of values to True or False. True can be represented by '1', 'True' and 'true.' False can be represented by '1', 'False' and 'false.' Any other representation will be rejected. """ if value in ['1', 'true', 'True']: return Tr...
dd648d94be143ee9e896097851ce35bb3bfd0c3b
627,045
import json def _get_options(options_file=None): """ Read in options_file as JSON. :param options_file: filename to return :type options_file: str :return: options as dictionary :rtype: dict """ if options_file is not None: with open(options_file, 'r') as opt_fil...
9011175e8583541982f761a9f60375a0bdca88c1
627,046
import re def clean_jsonp_callback(callback): """ Returns JSONP callback function name or None. Callback function names can contain alphanumeric characters as well as periods (.) and brackets ([ and ]), allowing names like "one.two[3]". """ callback = re.sub('[^a-zA-Z0-9\._\[\]]', '', callback) ...
361603e3eb8a29f285d8ce97ec4a1c1a030d6c56
627,047
def get_bowtie2_index_files(base_index_name): """ This function returns a list of all of the files necessary for a Bowtie2 index that was created with the given base_index_name. Args: base_index_name (string): the path and base name used to create the bowtie2 index Returns: ...
534d8c1a442571a441f37fb943898b53a4fce706
627,049
def order_heuristic(mgr, var_priority = None): """ Most signifiant bits are ordered first in BDD. var_priority is a list of variable names. Resolves ties if two bits, are of the same priority, it resolves based. e.g. var_priority = ['x','y','z'] would impose an order ['x_0', 'y_0', 'z_0'] """ ...
55c8beebddf49dde574f65530b88453dfa2fb60a
627,050
def scale(n, float_round=None): """ High-order function to scale result to arbitrary value. f = scale(10) f(5) -> 50 if float_round f = scale(0.1, 2) f(10) -> 10.2 :param n: Scaling factor :param float_round: Number of decimal places :return: Callable, performing scaling :r...
9c2cefd79d81476fba07bc3e8057fe5b4f2cce82
627,051
from typing import List def create_readable_data(data: List[int]) -> List[list]: """Create a program readable sudoku puzzle given a list of numbers === Attributes === data: a list of numbers containing sudoku puzzle === Returns === a readable sudoku puzzle """ result = [[data[col + 9 * r...
152fe696ac81f5822ed4d2a76862a623959bb8a2
627,052
from typing import List from typing import Any from typing import Callable from typing import Set def dagroots(sorted_nodes:List[Any], inbounds:Callable[[Any],Set[Any]])->Set[Any]: """ Return a set of root nodes of a DAG. DAG should be topologically sorted. """ nonroots=set() acc=set() for node...
b1c618824cea5c1b438b9d70f5e1c971efebb8ed
627,053
def convert_numeric_list(str_list): """ try to convert list of string to list of integer(preferred) or float :param str_list: list of string :return: list of integer or float or string """ assert isinstance(str_list, list) if not str_list: return str_list try: return l...
3eefde31b1e9ac2758efa3f4111d2c1b70df50eb
627,063
def hashstring(s): """Compute a string hash based on the function "djb2". Use at most 64 characters. """ h = 5381 s = s[0:64] for c in s: h = ((h << 5) + h + ord(c)) & 0xffffffff return h
a0803a38c52c12346c5b362e1db9be9d6ddc8fcf
627,066
def get_programming_language(repo_info): """Return programming language used for repository""" try: return repo_info.find('span', {'itemprop': 'programmingLanguage'}).text.strip() except AttributeError: return
5e0b76599ed023088de62ac4625b60fe3339d981
627,069
def find_python_in_context(context): """Find Python executable within the given context. Args: context (ResolvedContext): Resolved context with Python and pip. name (str): Name of the package for Python instead of "python". default (str): Force a particular fallback path for Python exec...
92f88310f3eb134b4ba7caa4c1044b1397c4cf91
627,071
import click def email_option(help_message, long="--email", short="-e", name="email", required=True): """ Email option standard definition. Use as decorator for commands. """ return click.option( long, short, name, required=required, type=str, help=...
7fecba302ebf1a81cba08a54cb52774348152427
627,072
def shellescapespace(s): """Escape spaces for shell.""" return s.replace(" ", "\\ ")
4f3d9a1c43c1894759216662d8ee1ba37ff26438
627,073
def find_level_sections(alts): """ Find pairs of start/finish indicies of consecutive altitudes with the same value. I.e. where an aircraft was in level flight. Parameters ---------- alts: float array An array of altitudes[feet] Returns ------- level_indicies: a list of ind...
ed80b0fe8c9e9debaf3959a19a49a7d14d6ddf52
627,074
def clean_text(text): """ Remove most punctuation from string and make it lowercase :param text: String :return: String with cleaned up text """ text = text.lower() text = text.replace("!", " ") text = text.replace("?", " ") text = text.replace(";", " ") text = text.replace('"', ...
bb08ce63485bc77ef7f082f9f916c543e12301fd
627,081
def read_hex(field: str) -> int: """Read a hexadecimal integer.""" return int(field, 16) if field != "" else 0
59c3f1c39647b3186f4f4efa1bded53f0a6ed788
627,086
def bwtc_scaling_factor(order): """Return the appropriate scaling factor for bandwidth to timeconstant converstion for the provided demodulator order. """ scale = 0.0 if order == 1: scale = 1.0 elif order == 2: scale = 0.643594 elif order == 3: scale = 0.509825 e...
8b88eccfa37df1c8e49fe82c0f1a87b0e26ef101
627,088
from typing import Any def get_category(parameter_meta: Any, input_name: str, category_key: str = "category", fallback_category: str = "other") -> str: """ :param parameter_meta: A dictionary containing the parameter_meta information. :param input_name: The name of th...
6eba16b078f0bf5ae5fabf0e46621d2fe3aadc9b
627,095
def remove_start(s: str, start: str): """ Helper function to remove the beginning of a string. :param s: the string to remove the prefix from. :param start: the prefix of the string to remove. :return: s with the start of the string removed. """ assert s.startswith(start) return s[len(st...
ab831976fa0e56ae91544f1a635805eb1d928970
627,096
def projects_q(project): """Return the gerrit query selecting all the project in the given list :param project: List of gerrit project name. :type project: list of str :return: gerrit query according to `Searching Changes`_ section of gerrit documentation. :rtype: str .. _Searc...
98c93c289c6e084d29c50690ddfdd85ad0650a07
627,098
def square_to_condensed(i: int, j: int, n: int): """Convert a square matrix position (i, j) to a condensed distance matrix index. Args: i: Index i. j: Index j. n: The dimension of the matrix. See Also: https://stackoverflow.com/questions/13079563/how-does-condensed-distance...
d940df40d91c2ba943c3131a53acb00b1bd50f9f
627,103
import textwrap def sample_project_path(tmp_path): """Create a sample project to be cleaned.""" source = """ import pytask @pytask.mark.depends_on("in.txt") @pytask.mark.produces("out.txt") def task_dummy(produces): produces.write_text("a") """ tmp_path.joinpath("task_dummy.py...
3c77d277114810a0f5ca8dc6ce6ec09f9ce57f11
627,104
def str_to_bool(val): """ Convert a string representation of truth to True or False True values are 'y', 'yes', or ''; case-insensitive False values are 'n', or 'no'; case-insensitive Raises ValueError if 'val' is anything else. """ true_vals = ['yes', 'y', ''] false_vals = ['no', 'n'] ...
9764fed734a48e6ec7c434d827feebccd5f0c137
627,107
def transform(subject: int, loop_size: int) -> int: """Transform the ``subject`` in ``loop_size`` steps of a hard-coded algorithm.""" value = 1 for _ in range(loop_size): value *= subject value %= 20201227 return value
a5bf5a85eccc26d0dde4afea36a4e0db7153dda3
627,109
def solidsFluxPembWake(rhop, emf, umf, us): """ Calculates the solids entrainment flux for the surface of a bubbling bed with the bubble wake ejection model of Pemberton and Davidsion (Chem. Eng. Sci., 1986, 41, pp. 243-251). This model is suitable if multiple bubbles coalesce at the surface before ...
75f37822587b788234dd39ea546482f4ce6b509c
627,111
from pathlib import Path def get_test_script() -> Path: """ Returns the full path to a testing script that lives inside of the test suite. :return: """ current = Path(__file__).parent script = current / "script_for_tests.py" assert script.is_file(), f"File {script} not found" return sc...
ea0fb2a7c60fe8089090b48cf90f47a7c457c78b
627,113
import torch def axis_angle_into_quaternion(normalized_axis, angle, device=torch.device("cpu"), dtype=torch.float32): """ Takes an axis-angle rotation and converts into quaternion rotation. https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles :param normalized_axis: Axis of rotation ...
1defb1f5410cb97ffe29b4e6a94e334088f94d18
627,121
def for_entities_in(container): """ Receives messages sent to a target inside the specified container. :param container: A container whose entities' messages will be received. """ def filter(target): if target.container == container: return True if target == container: re...
9d9538a6b1cc15b71ba4a287189e485c6efbbd45
627,125
def execution_time(result): """Return the execution time of a query.""" avail = result.summary().result_available_after cons = result.summary().result_consumed_after return avail + cons
d91a237962a45c1d2a128dddd07d7770a3c4b736
627,127
def determinant(matrix): """ Calculates the determinant of a matrix. matrix is a list of lists whose determinant should be calculated If matrix is not a list of lists, raise a TypeError with the message matrix must be a list of lists If matrix is not square, raise a ValueError with the message ...
c02378da8f9cf8ae00cea4ee8c58ee7dad87ecde
627,130
def do_files_to_copy_contain_entry_with_src(files_to_copy, src): """Searches the files to be copied for an entry with src field that matches the given src.""" is_present = False for file_to_copy in files_to_copy: if file_to_copy.src == src: is_present = True break return ...
a46ab3e264ddd6d3014faaf730ec393117c989cf
627,138
from typing import Dict from typing import Tuple def parse_header_and_separator( header: str, separator: str ) -> Dict[str, Tuple[int, int]]: """Parse header and separator and return {field: (start, end)}""" headers = header.split() separators = separator.split() field_to_start_end = {} # type: D...
22f8da1cda2210a4e1f22f3b1a3722278449c9f4
627,139
import hashlib def get_hash(string, length=8): """ Shortcut for generating short hash strings """ return hashlib.sha1(string.encode("utf-8")).hexdigest()[:length]
869b699b39cea700adebc9e233f6b0bf8fd59f95
627,145
def get_filenames_in_release(manifestdict): """ <Purpose> Get the list of files in a manifest <Arguments> manifestdict: the manifest for the release <Exceptions> TypeError, IndexError, or KeyError if the manifestdict is corrupt <Side Effects> None <Returns> A list of file names """ filenamelist =...
5c1fea416f8e08cd9ec735036e69cee8845de497
627,146
import re def parse_function_definition(deftxt: str) -> tuple[str, str]: """Parse a function definition""" # Connect multiple lines if so deftxt = re.sub(r'\n\s*', ' ', deftxt, flags=re.M) # Split the definition line to the function name and the variables definition function_name, variables, _ ...
317a17692fadfc2c54e92b0fd6f2f26da632906e
627,149
def _mirrorpod_filter(pod): """Check if a pod contains the mirror K8s annotation. Args: - pod: kubernetes pod object Returns: (False, "") if the pod has the mirror annotation, (True, "") if not """ mirror_annotation = "kubernetes.io/config.mirror" annotations = pod["metadata...
a07a6ff924a44e57d1ffc8af1e40b0b80d1307e8
627,153
def _find_clusters(mst_graph, vertices): """Find the cluster class for each vertex of the MST graph. It uses the DFS-like algorithm to find clusters. Args: mst_graph (dict): A non-empty graph representing the MST. vertices (list): A list of unique vertices. Returns: A l...
9ff6e4f3a15bf3c855622e5d80731d9c578d55e9
627,154
def atoi(v): """Convert v to an integer, or return 0 on error, like C's atoi().""" try: return int(v or 0) except ValueError: return 0
bea39b0b9a41c9f48e653cc835aad05e0378f3bf
627,157
def get_control_latex(model): """ Get the labels for each Hamiltonian. It is used in the method method :meth:`.Processor.plot_pulses`. It is a 2-d nested list, in the plot, a different color will be used for each sublist. """ num_qubits = model.num_qubits num_coupling = model._get_num_co...
2e2c003c0ee3d1b0424d092ed9c1a48280b46ccf
627,160
def lr_poly(base_lr, curr_iter, max_iter, warmup_iter=0, power=0.9): """Polynomial-decay learning rate policy. Args: base_lr: A scalar indicates initial learning rate. curr_iter: A scalar indicates current iteration. max_iter: A scalar indicates maximum iteration. warmup_iter: A scalar indicates th...
47cea1789b6cc7c32c8e99fb9b5eb0f8c1083791
627,162
def periodic(t, T): """ Returns equivalent time of the first period if more than one period is simulated. :param t: Time. :param T: Period length. """ while t/T > 1.0: t = t - T return t
0e3a5788ae795e00cb9962181774829947142a1b
627,163
from typing import Mapping def has_node(g: Mapping, node, check_adjacencies=True): """Returns True if the graph has given node >>> g = { ... 0: [1, 2], ... 1: [2] ... } >>> has_node(g, 0) True >>> has_node(g, 2) True Note that 2 was found, though it's not a key of ``g...
f8dcb4ea41904f5e836fb44df83b2acf88f12de2
627,165
from typing import Optional def next_batch(limit: int, offset: int, total: Optional[int]) -> bool: """Is there a next batch of resources?""" if total is None: return True return (total - offset) > 0
51febba2c3732bf9c1896b3fd31d4b9d5503c8e2
627,166
def score(word_list, lm): """ Use LM to calculate a log10-based probability for a given sentence (as a list of words) :param word_list: :return: """ return lm.score(' '.join(word_list), bos=False, eos=False)
1b9430077460279cad4a429b723c9e7b8d2fd555
627,169
def same_type_and_id(first, second): """Same type and ID""" return type(first) is type(second) and first.id == second.id
32f92bc28b7bdef8a5c48a4250fda032742c4bde
627,171
def process_datasets(datasets): """Return a list of datasets provided as a string in GUI input or None if default 'All' is provided. Args: datasets (str): a string with coma-separated datasets names Example: >>> process_datasets("Data1,Data2") ['Data1', 'Data2'] """ ...
2ddd14a4b05e22861849ff3fc0d519802d315d2b
627,172
import math def solar_declination(doy): """ Calculate the solar declination for a given day of the year (Allen et al. 1998). Parameters ---------- doy : int Julian day of the year (-). Returns ------- float Solar declination (rad). """ return 0.409 * math...
db1b6bbf38c69ffbb0b5f5ba47283cdf2cd7a4dd
627,173
def degTohms(ideg): """ Converts degrees to hours:minutes:seconds :param ideg: objects coordinates in degrees :type ideg: float :return: hours:minutes:seconds :rtype: string """ ihours = ideg / 15. hours = int(ihours) + 0. m = 60. * (ihours - hours) minutes = int(m) + 0. ...
70f349311519bf4bc9f5cdb6e93d4fd57f192c61
627,180
def is_english_word_alpha(word: str) -> bool: """Returns True when `word` is an English word. False otherwise. Args: word: Any given word Examples: >>> is_english_word_alpha("English") True >>> is_english_word_alpha("영원한") False >>> is_english_word_alpha("do...
d6c4a3322e828ebbc6a30b6585ff6913616ec2ba
627,181
from typing import Optional from typing import Sequence import torch def uniform_superposition( num_qubits: int, batch_dims: Optional[Sequence] = None, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.complex64, requires_grad: bool = False ): """Create...
154a88234aedcd6985bc2a22c710d064ae6c213d
627,182
def anyInArray(array, elements): """ 要尋找的任一元素,存在於 array 當中即返回 True,否則返回 False :param array: 被搜尋的陣列 :param elements: 要尋找的元素們 :return: """ for element in elements: if element in array: return True return False
d1de5fbe945c71572fc62250b042c556417df940
627,187
from pathlib import Path import mimetypes def content_type(path: Path) -> str: """ Guess the content type of *path* from its name. If the type is not guessable, returns the generic type ``application/octet-stream``. """ type, encoding = mimetypes.guess_type(path.name) return type or "appl...
9c105431814f7fd5272043e2d5b8ddf56a6a0e1c
627,188
def sum_digits(n : int) -> int: """ Given a non-negative integer n, return the sum of its digits. Parameters ---------- n : int number to return the sum of Returns ------- int sum of numbers digits """ if n == 0: return 0 x = sum_digits(n // 10) + (...
ae8cd8b64d15548b2e5ede1feb40e564d01a1239
627,191
from pathlib import Path import shutil def images_path(tmp_path_factory, some_image, n_images: int = 3) -> Path: """ Return a temporary directory that has been prepared with some image files: - img_0.jpg - img_1.jpg - img_2.jpg - ... """ tmp_img_path = tmp_path_factory.mktemp('imgs_dir...
ab3825acb132892f0b65d37e943003cb61055089
627,192
def from_pcl(infile, outfile): """Convert a pcl file to biom format using the biom package :param infile: String; name of the input tsv or pcl file :param outfile: String; name of the resulting converted biom file External dependencies - biom-format: http://biom-format.org/ """ cmd="bi...
0977481ed78929a37178532eb957d95c68e10076
627,193
def parse_vespa_json(data): """ Parse Vespa results to get necessary information. :param data: Vespa results in JSON format. :return: List with retrieved documents """ ranking = [] if "children" in data["root"]: ranking = [hit["fields"]["id"] for hit in data["root"]["children"] if "...
ac3675518a553927095ba0068d47b59153f2d0ac
627,194