content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import six def xor(key, data): """ Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``da...
248bc694f014031a1a9a40c5598e96f381a13ada
619,708
def unscale_input(img): """Reverses scaling of image values from [-1,1] to [0,255]. Args: img (numpy.ndarray[float]): image to scale Returns: numpy.ndarray[float]: unscaled image """ return ((img + 1) * 127.5)
3578cc542100723b0a348df2c8a9914af35efd7d
619,710
def get_info_str(*key): """ Returns a continuous string of a list of objects. Each object is transferred to a string and strings are separated by '_' to form the final string. If a string of an object is too long or the object is a class, it will be replaced by the class name of the object. All the stri...
07ca01d60f0402a6e4d894da2823172929e66dd3
619,713
def get_object_from_action_name(action): """Return the object from the name of the action""" if action.startswith('pick_'): object_name = action[len('pick_'):] else: object_name = None return object_name
2054103146a553c222c5ec4926eb55c8e9ac539b
619,714
def get_hash_id(param): """Return the hash ID of a parameter.""" return param['_']['hash_id']
000df3dda41f32e6f368b4d415ffdd6ae168e058
619,716
def parse_locust_stats(env): """ Turn the locust stats into more print-friendly data. """ stats = env.runner.stats statistics = { "requests": {}, "failures": {}, "num_requests": stats.num_requests, "num_requests_fail": stats.num_failures, } for name, value in...
8d9288259ae175a8029e4f31f9aa78321eaab23e
619,717
import textwrap def _wrap_word(text: str, w: int) -> str: """ Wrap word :param text: text :param w: max line length :return: Wrapped word """ return "\n".join(textwrap.wrap(text, w, replace_whitespace=False, break_long_words=False))
9587c193625527713f34d471146415693b75585c
619,718
def action_key(action): """Returns string representation of action. This is also what is returned by argmax_Q. Needs a dictionary for that if the string representation is not enough.""" return action
2ad939de47d915e5533f3d0dab933da215aebec9
619,723
def bytes_list2bin(bl): """Convert list of bytes to binary string""" return b''.join(chr(i).encode('latin-1') for i in bl)
3e755fc30498da79c688938ccc44a0be3fcc1ff7
619,725
def get_answer_using_qa(nlp, question, context): """Get answer using a classifier trained with the QA technique Parameters ---------- nlp: Pipeline Trained QA Pipeline question: String Question that the model will answer context: String The Context of the question R...
d0fa0e942600dc7176f8f7a858fe3ff0f9ffe838
619,727
def check_legendary(item): """ Check if item is a Legendary """ if item.name == 'Sulfuras, Hand of Ragnaros': return True return False
03f6aa2efb70662142a6abac1d255affa3ae926e
619,728
import requests def submit_request(url: str, token: str, query: str) -> requests.Response: """Post a query to an API access point, along with an authentication token. Retry with a progressive timeout window. """ MAX_REQUESTS = 3 TIMEOUT_INCREMENT = 5 response = None req_count = 1 whi...
9ccc1ef966b15ece39c3d2260adb06f4d327c9de
619,729
def check_col(x, y, digits_grid): """ Checks if a digit in a box with coordinates y, x fits to its column. Useful for checking if sudoku is solvable at all. :param x: a coordinate counted from 0 :param y: a coordinate counted from 0 :param digits_grid: 2D numpy array that contains digits. 0 <==> there is n...
df825122d9cb1dc4fe4956948a7922b84fd637fa
619,735
def _inject_args(sig, types): """A function to inject arguments manually into a method signature before it's been parsed. If using keyword arguments use 'kw=type' instead in the types array. sig the string signature types a list of types to be inserted Returns the altered...
4a8485403dbd7fbd35af5436e20154e3a9e26180
619,737
def _dirac(a, b): """Calculate the dirac function for labels.""" return int(a == b)
76b2e793e3aa76545225024700eb4eb123970ced
619,738
def _format_gaussian_report(result): """Formats a `_GaussianResult` as a complete report str. The information presented includes: - The parameters of the Gaussian fit - The extrapolated probability of the `assertAllMeansClose` failing, assuming the distribution of means is Gaussian - Suggested changes to...
1cef9cab811a798b17f30207bdf67cd2cd6d11c3
619,741
import torch def is_active(coords, active_voxels, volume_resolution): """ compute whether coordinates belong to active voxels by two criterias: 1) a coordinate should be within the volume bound 2) it belongs to the input active voxels Args: coords: [b, n_pts, n_steps, 3] active_vo...
b077aaaac585c23a1c6a07f26dea69a834c3ea03
619,744
def quadrilaterals_mesh_to_centroids(x_vertices, y_vertices): """Find the centroids of a mesh from its vertices. Parameters ---------- x_vertices - 2d numpy array (NxM) y_vertices - 2d numpy array (NxM) Returns ------- x,y - 2d numpy array (N-1xM-1) """ x = (x_vertices[0:-1,0...
fce6c190944d963810cab3bd35ec174cea3ec277
619,746
def format_address(parts): """ Format a parsed email address for sending :param parts: a tuple of the name and email :return: a properly formatted email """ if parts[0] == "": return parts[1] return f"{parts[0]} <{parts[1]}>"
7e74843dbd1c236c03c597268c48e72c9ce99545
619,749
def set_rpn_weights(training_model, inference_model, verbose=False): """ Set region proposal network (RPN) weights from training to inference graph Args: training_model: MaskRCNN training graph, tf.keras.Model inference_model: MaskRCNN inference graph, tf.keras.Model verbose: ...
462586984fe736fe38ac13fe10f5d41d5343c4ac
619,751
def bflag2str(bflag): """ Args: bflag (dict): binary flag Returns: flag as binary string, keys """ l = [] #print("flag keys ", bflag.keys()) #['plankton', 'small_Z_diff', 'melting_layer', 'too_many_peaks'] keys = ['mod_calibration', 'unsecure_calibration', 'particle_influ...
57e5c3d5c431a478176ce96a42de4b085ea0549d
619,752
import re def is_relative_path(src: str): """Returns true if src is a relative path. """ assert isinstance(src, str), ValueError("relative_path must be a string") return not (src.startswith("/") or re.match(r"[a-zA-Z]:\\", src) is not None)
bc0b8fc19d47467ad5f9388811651a392402d5b8
619,754
import re def keep_only_letters(text, keep_cash=True): """ Remove from string `text` all characters that are not letters (letters include those with portuguese accents). If `keep_cash` is true, do not remove the dollar sign '$'. """ if keep_cash == True: extra_chars = '$' else: ...
8228c61abda354473131f0688cf4a77a6beeb148
619,755
def mean(data): """Compute the mean of the provided data.""" n = len(data) try: return [float(sum(l))/len(l) for l in zip(*data)] except TypeError: return sum(data)/n
d1cbe552d6176750486df832c8f5b0a74e6fca8c
619,756
def rounder(x, ndigits): """Round a number, or sequence of numbers, to a specified number of decimal digits Args: x (None, float, complex, list): The number or sequence of numbers to be rounded. If the argument is None, then None will be returned. ndigits (int): The number of decima...
17d02f934e0ac62070010a3524885b5cb25afb36
619,758
def str2bool(value): """ Type to convert strings to Boolean (returns input if not boolean) """ if not isinstance(value, str): return value if value.lower() in ('yes', 'true', 'y', '1'): return True elif value.lower() in ('no', 'false', 'n', '0'): return False else: re...
9c14671dafed09d1c027a34f2380c0ff33bac7bb
619,759
def prlimit_command(command_list, virtual_memory_limit): """ Prepend memory limiting arguments to a command list to be run with subprocess. This method uses the `prlimit` program to set the memory limit. The `virtual_memory_limit` size is in bytes. prlimit arguments: -v, --as[=limits] ...
685876c6902ba804eedfa061155608e350671fee
619,761
from pathlib import Path def parse_lovpy_ignore(path: Path): """Returns all patters contained in given .lovpyignore file.""" if not path.name == ".lovpyignore": raise RuntimeError(f"Invalid .lovpyignore file: {str(path)}") ignore_paths = [] with path.open("r") as f: for line in f: ...
9682b308fde4bc46ed34ac29e840085024328238
619,765
def is_number(string): """Function to test whether a string is a float number""" try: float(string) return True except ValueError: return False
46e03d14021ea0cfca08d5a5701f5a820d84984f
619,767
def partition_coefficients(IDs, top, bottom): """ Return partition coefficients given streams in equilibrium. Parameters ---------- top : Stream Vapor fluid. bottom : Stream Liquid fluid. IDs : tuple[str] IDs of chemicals in equilibrium. Returns ----...
3c4022aa4638ea7ff46360f17a9f730b2dcce03d
619,768
def get_vos(da): """ Takes an xarray DataArray containing veg_index values and calculates the vegetation value and time (day of year) at valley of season (vos) for each timeseries per-pixel. The valley of season is the minimum value in the timeseries, per-pixel. Parameters ---------- ...
fa0f2f2ac46445d91d5276e6c65b9572c320f94b
619,771
def needs_ascii(fh): """ Answer whether to encode as ascii for the given file handle, which is based on whether the handle has an encoding (None under py2 and UTF-8 under py3) and whether the handle is associated with a tty. """ if fh.encoding and fh.encoding != "UTF-8": return True ...
4a6065ebfd0c14467e2d7bb2ebc801a9bce47913
619,775
import torch def preprocess(im, pro): """ This function converts the numpy arrays or lists to tensors and returns it. Can be augmented with different operations in the future if needed (like augmentation). im: BxCxHxW images pro: list of list of integers [delta_elev, delta_azim, e...
6005c2679fcc4561cdc240622557e936f137cf70
619,778
def _get_used_ports(vms): """ Return a set of ports in use by the ``vms``. :param vms: list of virtual machines :type vms: list(:class:`~.vm.VM`) :return: set of ports :rtype: set(int) """ used_ports = set() for vm in vms: ip, port = vm.get_ssh_info() ...
aaa3e141fb060a78ba86d71d59ed59fb59fd4132
619,779
def dict_to_associative_list(dict_value): """Serializes a dict to an associative list.""" return ",".join(["%s=%s" % (k, dict_value[k]) for k in dict_value])
6918014d62fe6f5f1eb05e2aa4d453dc117d9850
619,783
import torch def is_on_gpu(model): """ Returns True if all parameters of a model live on the GPU. """ assert isinstance(model, torch.nn.Module) on_gpu = True has_params = False for param in model.parameters(): has_params = True if not param.data.is_cuda: on_gpu ...
fd624e4e656ffe39e1c98fd0ab690e6444da3058
619,784
from datetime import datetime def add_metadata_values_to_record(record_message): """Populate metadata _sdc columns from incoming record message The location of the required attributes are fixed in the stream """ extended_record = record_message['record'] extended_record['_sdc_extracted_at'] = reco...
7553b0771104aab110825c15e21c5d81e37b051b
619,785
def optimize_list_worker(x, n0, profiler, **kwargs): """Worker function needed for parallel execution of the likelihood optimization (see the `_optimize_list` method of `Profiler`).""" return profiler._optimize_list(x, n0, **kwargs)
3f92d0c65ad8a9f3a6227a7adaf961bf70e7180e
619,786
def body(prg): """ Code body """ return prg[2:]
cc2126849dba05e81954289f5bfe24ec676806ab
619,796
import requests def web_gbif_validate(tax, rnk, gbif_id=None, gbif_ignore=None): """ Validates a taxon name and rank against the GBIF web API. It uses the API endpoint species/match?name=XXX&rank=YYY&strict=true endpoint to # safe to assume that the next least nested taxonomic level is the pare...
a758c6da277043993f7d5f70dd01ffe43b98c54b
619,797
from pathlib import Path def find_free_filename(file_path: str) -> Path: """Given a file path, check if that file exists, and if so, repeatedly add a numeric infix to that file path until the file does not exist. For example, if output/counts.csv, exists check if counts_1.csv, counts_2.csv, and s...
cc46b56a28c395cc7da2d59550f5fc2a809a678e
619,798
def _read_fname(fname): """ Open fname, read the contents, return them. """ with open(fname, 'rb') as fil: return str(fil.read())
a5a7646c5fed379793ef0dd56b4d49e50096efc3
619,800
from typing import Union def _get_item(ptr, itempath: str) -> Union[str, dict, list, None]: """Utility function. The ptr param should point at .services then follow the itempath (separated via '.') to the expected object. Returns None if invalid (tries to avoid Error).""" root = ptr for element in ite...
98a8945d7ab5804f27f6d93995c428c072c1743b
619,801
def get_value_at_index(my_list, index_list): """This method will take a base list and traverse the contained multi-dimensional array. Parameters: my_list -- This is the base list object index_list -- This is a list of nested indexes in a multi-dimensional array for example: [2][...
82b9421cb0716df21489dff6e9c6f95ca25d785e
619,802
def get_lin_func_param(point_1, point_2): """ given two pairs of (X,Y) extracts parameters of a linear function. m: slope b: constant :param point_2: :param point_1: :return: slope, constant """ precision = 5 slope = round((point_1.predicted_profit - point_2.predicted_profit) / ...
c0d432c07bc32a317a1bc29957a84896596e8094
619,803
def trading_pair_to_symbol(trading_pair: str) -> str: """ Converts Hummingbot trading pair format to Beaxy exchange API format example: BTC-USDC -> BTCUSDC """ return trading_pair.replace('-', '')
6ce7485f3bbd08eeb66604eb3014a9b09cb8926c
619,804
import ipaddress def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = ipaddress.ip_address(address) return True except (ValueError): return False
230938f2f7a70df919930f919f04baa3c4ba1377
619,805
import re def prep_file_name(path, file): """ append the original path and file name * strips special chars * remove spaces (replace with underscore) * convert to lowercase :param path: the path part of the new file name :param file: the original file name :return: sanitized name ...
f90e1e315d7fef51b66152ec14627716f72c5808
619,810
from bs4 import BeautifulSoup def get_job_title_indeed(card: BeautifulSoup) -> str: """ Extracts the jobs title from the portion of HTML containing an individual job card. Args: card (BeautifulSoup object): The individual job posting card being processed. Returns: str: The job title...
882f91df7bb193823ca6c12a76f65eff91d865e9
619,812
def strip_quotes(S): """ String leading and trailing quotation marks """ if '"' in S[0] or "'" in S[0]: S = S[1:] if '"' in S[-1] or "'" in S[-1]: S = S[:-1] return S
a9c09e8381af1122707b55e412cc3bc40652cf04
619,814
def tsplit(string, delimiters): """Behaves str.split but supports multiple delimiters.""" delimiters = tuple(delimiters) stack = [string,] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) ...
23e131c6d9fc8b7058da210b360f559a6fc37db4
619,816
from typing import Union def increment_by_n(n: Union[int, float]): """Generates a function that will increment by n. Args: n (int): integer to increment by. >>> increment_by_n(2)(2) 4 """ def incrementor(base: Union[int, float]): return base + n return incrementor
413634bbc9f3a6ba7550ee5989e8d3452ec6dea0
619,817
def fmt_xpath_spec(tag: str, attributes: dict): """Format a xpath_spec string using the given tag and attributes The xpath_spec returned is 'absolute', and thus can't be used. Prepend "./" to the xpath spec if using it to actually look up an element. :param tag: The tag to format into the xpath spec ...
ad13f111fee09b2ead4a8ed9967564c3ffc3ee5f
619,819
def _flatten_array_to_str(array): """ Helper function to reduce an array to a string to make it immutable. Args: array (array): Array to make to string Returns: string: String where each value from the array is appended to each other """ s = "" for i in array: s...
229bb0f3908717d87964c24cb2e13f357727c837
619,820
def checkIfX(coordinate, x): """ This function is a filter which return true if the first value of tuple is equal to x In : tuple : tuple to be tested In : x : float, The test value Out : Bool : Result of test """ if(coordinate[0][0] == x): return True else: return False
6bc7d5d9459a159857e169914f6820cbcad9b9fc
619,823
from typing import List def f_range(start: float, end: float, step: float=1.) -> List[float]: """Make list of floats like `numpy.arange`.""" out = [] while start < end: out.append(start) start += step return out
e101e9f97625f0c13498ad09c565382c2aae5782
619,829
from typing import List def string_wrap(text: str, wrap_length: int) -> List[str]: """ Split a string into groups of wrap length. :param text: Original text :param wrap_length: Length at which the string has to be wrapped :return: List of wrapped strings """ string_list = [] while tex...
92e5dc0be6be621e3ce3ee121fc72de9b1670a60
619,831
def calc_confidence(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False): """Evaluates the generated rules. One measurement for quantifying the goodness of association rules is confidence. The confidence for a rule 'P implies H' (P -> H) is defined as the support for P and H divided by ...
c6550ada50b75ec3c03953cc67c4342e09722515
619,833
def calc_sales_price(price): """ 计算9折后的价格 :param price: 折前价格 :return: 折后价格 """ if price < 0: raise ValueError("price should not < 0!") sales = 0.9 * price return sales
4b3b7244115e22ba4d02914167db565db1b3b71a
619,834
import re def remove_html(entry): """ Remove html tags from tweet (use in pd.df.apply) Args: entry (entry of pandas df): an entry of the tweet column of the tweet dataframe Returns: output: tweet with html tags remove """ pattern = r'<.+?>' output = re.sub(pat...
29955237df95d7afadc33e62016ae97c20309b24
619,837
import yaml def get_model_tracer_lists(spec): """Return the `model_tracer_list` specified in the emergent constraint input file: EC-input.yaml. Parameters ---------- spec : string Specification of the constraint option in EC-input.yaml. Options include: 'ocean_constraint', ...
e5ad7bb707fac0522070db079e6bcb3357011d87
619,838
def get_number(file): """Returns the number part of the file name """ parts = file.split(sep="_") return parts[1]
ab169b67ef9f721f34e4974c08ca30b9fa622394
619,839
def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg
33898b4dc5b14d8cc7142f6942eee8df1cac732c
619,852
from typing import Dict import json def load_dict(filepath: str) -> Dict: """Load a dictionary from a JSON's filepath. Args: filepath (str): JSON's filepath. Returns: A dictionary with the data loaded. """ with open(filepath) as fp: d = json.load(fp) return d
04578489b278087799f36f2e7a2100b827dcec20
619,853
def max_or_zero(*args, **kwargs): """returns max(*args) or zero if given an empty sequence (in which case max() would throw an error)""" if not args: return 0 if not args[0]: return 0 else: return max(*args, **kwargs)
7d921acb3c5397418ee9171c798570b5017f24f1
619,855
def get_all_participants_in_dw_study(dw, study_id): """ return all local participant ids for a study :param dw: data warehouse end point :param study_id: study id in dw :return: list of local participant ids """ participants = dw.get_participants(study_id) local_participant_ids = [] ...
2842bedcbfb26a0ee7bbe228daed0514bc543ae8
619,857
def task_divide(idx, n): """ Split array into specified number of sub-arrays. Used in context of tasks. Parameters ---------- idx List of tasks. n Number of sub-arrays to split. """ total = len(idx) if n <= 0 or 0 == total: return [idx] if n > total:...
d44236f11e4448b64f646e949de3a886071bf5e1
619,858
def simpson(x, f): """ Compute a 1D definite integral using Simpson's rule. Parameters ---------- f : function User defined function. x : numpy array Integration domain. Returns ------- I : float Integration result. """ a = x[0] b = x[1] ya...
b36cf065de90c99580e67152db0290ff42c17df9
619,860
def broadcast_shapes(*shapes): """ Broadcast any number of shapes against each other. Parameters ---------- *shapes : tuples The shapes to broadcast Example ------- >>> broadcast_shapes((1,5), (3, 2, 1)) (3, 2, 5) """ if any(not isinstance(s, tuple) for s in shapes...
06a2cebee284836b28654a21ad70b59842366032
619,861
def sort_by_index_with_for_loop(index, array): """ Sort the array with the given index and return a list of (<element>, <original index>, <new index>) tuples. Parameters: index: List of length n that contains interger 0 to n-1. array: List of length n. Returns: A list of len...
a436e5a4ffa1647c83a3e9996a78a5aeefe92fc7
619,862
def read_txt(file_list): """Read .txt file list Arg: file_list (str): txt file filename Return: (list): list of read lines """ with open(file_list, "r") as f: filenames = f.readlines() return [filename.replace("\n", "") for filename in filenames]
8ae653b75e9bee6efabd2109a5ca905a2bc13fa7
619,866
import re def sentences(text: str) -> list[str]: """ Splits text into an array of its sentences. Finds two spaces, or newline, or tab, and splits there. Parameters ------------ text: str The text to be split up. Returns ------------ str[] An array of strings (sentenc...
e71fbf9f896b547f7152cd82d9d64d7fa7ff52b8
619,867
def division(a, b): """ Divides one operator from another one Parameters: a (int): First value b (int): Second value Returns: int: division result """ if b == 0: raise ValueError('Can not divide by zero') return a / b
8633fb59a3e8a3a6c4e812724ddd9570d88deba2
619,869
import json def policy_from_file(file_path): """Return dictionary from policy file.""" with open(file_path) as pol_file: policy = pol_file.read() return json.loads(policy)
6a6f272ab363c4b4af73b5da36eb7306b21b9cd1
619,870
import functools import warnings def deprecated(f): """Decorator to mark functions or methods as deprecated.""" @functools.wraps(f) def wrapped(*args, **kwds): message = "Calling deprecated function {}".format(f.__name__) warnings.warn(message, DeprecationWarning, stacklevel=2) re...
3d8ed63a7348821908010a3dc7b76bcb344f6eea
619,874
def getlastmatched(strike_to_match, strikes, endix, epsilon=.01): """ Return the index of the last item in a sorted list of strikes that matches strike_to_match. Search descending from endix in the list of strikes. A match is defined as a strike differing from strike_to_match by less than epsilo...
6773fc5ea4f182d327b43c000421d3fa5ac8d749
619,877
def extract_unmasked_data(radar, field, bad=-32768): """Simplify getting unmasked radar fields from Py-ART""" return radar.fields[field]['data'].filled(fill_value=bad)
1f2de462b80b216d306ffb132aea09ef8d8f4e67
619,880
from typing import Iterable def mult_elwise(items: Iterable, value: float): """Multiply all values in an iterable by a constant.""" result = [] for i in items: result.append(i * value) return result
694aabedee8f0c7bff85c1ee5eca7e56bfa570b5
619,882
def rescale_to_max_value(max_value, input_list): """ Rescale each value inside input_list into a target range of 0 to max_value """ scale_factor = max_value / float(max(input_list)) # Multiply each item by the scale_factor input_list_rescaled = [int(x * scale_factor) for x in input_list] return inpu...
448b35fdd79761ad93bbec1c56fd9f1db65d4914
619,883
def get_requirements(filename: str): """Build the requirements list from the filename""" requirements_list = [] with open(filename, "r") as reqs: for install in reqs: requirements_list.append(install.strip()) return requirements_list
dace4f4351269a4900dffe60caf4fcbb5a314b08
619,888
def matcher(source): """ Matches user input with datasets, the lists can be extended """ matcher_map = {"power_plant": ["coal", "coals", "natural gas", "gas", "bioenergy", "biomass", "hard coal", "lignite", "Fossil fuels", "fossil", "...
93e3290fd21b98e5fcb36040ade2453ea8dafa11
619,891
def __process_line(line, strip_eol, strip): """ process a single line value. """ if strip: line = line.strip() elif strip_eol and line.endswith('\n'): line = line[:-1] return line
7facecfa0cfa7b15fc4ea06f941a5ba63d42159b
619,892
def event(base_url: str) -> str: """ Build the URL for an execution's event. """ return '/'.join([base_url, 'events'])
d9d9df03475808dd5077d673ce4ea77e7f281326
619,893
def json_int_clean(json_elmnt): """return integer if json element is not none, otherwise return -1""" if json_elmnt: ret = int(json_elmnt) else: ret = -1 return ret
aff4d920b1d8f8046b2cd4f6083c348cc4a18a0a
619,895
def get_root(database): """Load root folder from database.""" return list(database.keys())[0]
2be983b48bc3d67f003d103dc623a54311dfcaf6
619,896
def get_movies_by_keyword(hs_movie, enter_val): """ Showing the movies that consists of entered word Parameters: hs_movie (dic): information about movies enter_val (str): Entered keyword returns: list: return list_tuple """ list_tuple = [] for year in hs_movie: for mo...
710e7478e58dd5a88c65efad1a9843505e6c9369
619,898
def split_sequences(sequences): """The output of the sequencer can be split into four different types of sequences for ease of checking: Sequences of words, sequences of lemmas, sequences of words without stops, and sequences of lemmas without stops. This method performs that split. :param list seq...
2b4d75f424318d9b0abe7704c69faeb8c24a0d0c
619,901
import six def convert_to_text(value): """ Make sure a value is a text type in a Python version generic manner. :param value: a value that is either a text or binary string. :returns value: a text value. """ if isinstance(value, six.binary_type): value = value.decode('utf8') if no...
88176cabb6cf0d9fa66ec7645e90a9f941b163a8
619,902
import torch def nm_suppression(boxes, scores, overlap=0.45, top_k=200): """ Non-Maximum Suppressionを行う関数。 boxesのうち被り過ぎ(overlap以上)のBBoxを削除する。 Parameters ---------- boxes : [確信度閾値(0.01)を超えたBBox数,4] BBox情報。 scores :[確信度閾値(0.01)を超えたBBox数] confの情報 Returns ------- ...
7e8cfb5ce8c589408b004bd42475468e4d0ad959
619,903
def find_occurrence(string, substring, occurrence): """Find position of n'th occurrence of substring in string, else -1.""" # string - a string to be searched # substring - a substring to search for # occurrence - the occurrence to search for, starting from 0 # if not present, return -1 found ...
6048db3d96394192c3692fe5b958d9e402d0fd66
619,905
def prep_early_warning(hours, minutes, assignment_name): """ Create a early warning message. :param hours: Hours until the deadline. :type hours: int :param minutes: Minutes until the deadline. :type minutes: int :param assignment_name: Name of the assignment that approaches its deadline. ...
6ee485e007190c87db92affcf4c9be4dcb586d47
619,906
def _agent_is_gene(agent, specific_only): """Returns whether an agent is for a gene. Parameters ---------- agent: Agent The agent to evaluate specific_only : Optional[bool] If True, only elementary genes/proteins evaluate as genes and families will be filtered out. If False,...
1c6eb9d3343eb00f3aea2827784db45f0eb2dfea
619,907
def _MergeSpacedArgs(command_line, argname): """Combine all arguments |argname| with their values, separated by a space.""" i = 0 result = [] while i < len(command_line): arg = command_line[i] if arg == argname: result.append(arg + ' ' + command_line[i + 1]) i += 1 else: result.app...
bf94c5100cf3b665488d2a558df6bfe04954e8ea
619,908
import math def nice_num(rge, rnd): """ Get a nice number (1, 2, 5, 10, ...) :param rge: range :param rnd: round or not :return: a nice number """ exponent = math.floor(math.log10(rge)) fraction = rge / math.pow(10, exponent) if rnd: if fraction < 1.5: nice_fra...
e51140311f9d3704e9644b2395299bff13bcd198
619,910
def toDD(n): """Takes an integer and returns a string of length 2 corresponding to it""" if n // 10 > 0: return str(n) else: return "0" + str(n)
31d92ccb13e9927a737c58c65459e28e74026c69
619,913
def get_flooded_second_token_from_msg(msg): """Get the first token image from message when flooded Arguments: msg (PIL.Image.Image): Image object Return: token (PIL.Image.Image): Image object """ return msg.crop((202, 0, 229, msg.height))
6014748be2f915849b9cf0178576ae73fe369956
619,915
def A_pixel(info_dict): """ Compute the projected area of one pixel on the sky Parameter --------- info_dict: dictionnary Returns -------- A_pixel: float projected area of one pixel on the sky (arcsec2/px) """ pix_sky_area = info_dict['pixelScale_X']*info_dict['pi...
ecaf62aa3bc20fe3a5cb88ccff1beee7679e64dc
619,919
def build_test_info(framework='tensorflow', framework_version=None, framework_describe=None, channel=None, build_type=None, batch_size=None, model=None, accel_cnt=None, ...
ac9fba3944b696d7826dd7ab80cacc05a54e8c72
619,920
def b36decode(number: str) -> int: """Convert the base36 number to an integer.""" return int(number, 36)
6caf4df523f467775c847c492137b03ffbf6d67c
619,924
def get_clim_model_filenames(config, variable): """Extract model filenames from the configuration.""" model_filenames = {} for key, value in config['input_data'].items(): if value['short_name'] == variable: model_filenames[value['dataset']] = key return model_filenames
78c8be83e01485952c8d48acee3ff857fbc6f80f
619,925