content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_backend(group): """Return the backend of given process group. Parameters ---------- group : ProcessGroup The process group to query backend. Returns ------- str The backend spec. """ return group.backend
1609ad1239d5a1d4dde07a8678c4a955fa303941
618,431
from typing import Dict from typing import Any def create_mesa_dir_name(comb: Dict[str, Any]) -> str: """ Creates a MESA run dir name to use for the given combination of MESA parameter values. These prefixes should be unique for each MESA run. This also needs to be deterministic, reguardless of the f...
e57e0793dd249aa4f73f7ab99e310e2a3ef00907
618,432
def json_as_python_set(dct): """Decode json {'_set_object': [1,2,3]} to set([1,2,3]) Example ------- decoded = json.loads(encoded, object_hook=json_as_python_set) Also see :class:`JSONSetEncoder` """ if '_set_object' in dct: return set(dct['_set_object']) return dct
94482090661363ece83ede7960e9d775c0a55d66
618,434
def reverse_list_strings(lines): """ Reverse a list of strings: - First, reverse entries of the list. - Second, reverse each entry of the reversed list. """ return [line[::-1] for line in lines[::-1]]
60434b7cd485ce16b76e312ce6caa6cf84252a3b
618,435
import zipfile def _format_toc(filename): """Return a table of contents for the zip file as a string. Args: filename (str): Path to zip file Returns: directory listed in format matching zipfile.printdir() """ zf = zipfile.ZipFile(filename) lines = [] lines.append("%-46s %19s %12s...
c6113eb87ed5b7bbd37accc250a782f1b42d0e33
618,438
import requests def validate_api(api): """ Validates the API key by sending a single request to Climacell API :param api: 32-char API ket :return: True if api is valid """ endpoint = "https://api.climacell.co/v3/weather/realtime" # Build sample params params = {'lat': '0', 'lon': '...
c5845ad9c9576bc2d09b492d5fba97caaf562cd0
618,443
def prplus(number): """Prefix with "+" for positive values""" return '+' if number >= 0 else ''
0ae50e92f1b8e1d321229ed784493671f050ab18
618,451
def format_percent(d, t): """ Format a value as a percent of a total. """ return '{:.1%}'.format(float(d) / t)
9c3e871191e2757436c466c2560810b80a7880dc
618,452
def smart_zip(keys, values): """For handling the case where keys and values may be scalars""" if isinstance(values, float): return zip(keys, [values]) else: return zip(keys, values)
b8617e83a5b9aa381cfbacb422e0a4f7c94ff3a4
618,453
def format_frame(frame): """ Return a nice representation of frame.f_locals :param frame: frame object :returns: string representation """ buf = "" for key, value in frame.f_locals.items(): buf += "\t%s -> %s\n" % (key, value) return buf
8f2ead03d449c6d97712d47c7b4905ea5a02ebc9
618,455
def tmp_file(tmpdir): """Provide a temporary file in pytest-defined tmp dir Returns: A path to the tmp file """ return tmpdir.join('tmp_data.json').strpath
38f40bec61e5aee4271cbc25032a1cb18003d010
618,457
import secrets def arbitrary_string() -> str: """ :return: an arbitrary, URL-safe string. """ return secrets.token_urlsafe()
088af8af9411241d89ba43cf80857ca31928f525
618,459
def simulate(dynamics,x0,ufunc,T=1,dt=1e-3): """Returns a simulation trace of dynamics using Euler integration over duration T and time step dt. Args: dynamics (Dynamics): the system. x0 (np.ndarray): the initial state. ufunc (callable): a policy u(t,x) returning a control vect...
89931fa50fcee831e90b71c601573bb4758e6cd3
618,460
def dup_scores(scores, num_winners): """Expand a list of scores by a factor of num_winners, yielding one per candidate >>> dup_scores([0, 5], 3) [0, 0, 0, 5, 5, 5] """ return [s for s in scores for n in range(num_winners)]
0b845b1849b3b1d6afa88e201d46f2978615076a
618,465
def dut_artifacts_dir(request): """Fixture for --dut-artifacts-dir.""" return request.config.getoption("--dut-artifacts-dir")
71d0771128763d6de49fab99d386e67e4004a48b
618,466
import base64 def generate_api_key(username, password): """ Generates a Base64-encoded api key, based on the WEkEO user credentials username:password. Parameters: username: WEkEO username password: WEkEO password Returns: Returns a string of the Base64-encoded a...
8fe964dd37e37b7144e3776b025f4b09e57fdee8
618,468
def lane_lines_directixes(lane_info): """ Computes the parabola directrix for both curves. """ def directrix(coefficients): a, b, c = coefficients return (b ** 2 - 4 * a * c + 1) / 4 * a return directrix(lane_info.left_fit), directrix(lane_info.right_fit)
2a7ad99d494719b9da51c0d4505c36ac54b32c57
618,471
def cross_list(sequences): """ Code taken from the Python cookbook v.2 (19.9 - Looping through the cross-product of multiple iterators) This is used to create all the variations associated with an product """ result =[[]] for seq in sequences: result = [sublist+[item] for sublist in resu...
0e530d52ec45b5bc8390a9c73be4ca71b308037a
618,473
def _l2_regularization(l2, model): """Computes the L2 regularization for the given model Args: l2 (float): L2 parameter model (:obj:`torch.nn.Module`): Model to use Returns: float: L2 loss (i.e. (l2 * l2_norm(params)) / 2) """ l2_loss = sum(param.norm(2) ** 2 for param in m...
250e7a13047cbd7f0fbeccd6f30fc13393b7c56c
618,475
from pathlib import Path def parse_path(input: str) -> Path: """Parse a string path from the config file. Args: input (str): Input list Returns: Path: Path """ return Path(input).expanduser()
197626dfc756d863a252b203419faf1926063e99
618,476
import functools def preduce(func): """shorthand for functools.partial(functools.reduce, func), for use with pipelines. """ return functools.partial(functools.reduce, func)
d0c86b3a4894aec1cf4760e9ace03adacc7fe923
618,483
import torch def alpha2rot_y(alpha, x, cx, fx): """ Get rotation_y by alpha + theta - 180 alpha : Observation angle of object, ranging [-pi..pi] x : Object center x to the camera center (x-W/2), in pixels rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi] """ rot_y = al...
620675b391770266dd3b9a185c24f63ee5d7ec80
618,484
import re def filter_results(results, args): """Filters results for any the user didn't want processed. Arguments: results: list of dicts, with each dict containing status for a service. args: argparse.ArgumentParser, options passed to script. Returns: list: with any matc...
21ab10680b6675670588f0a65a1b15fc9036db67
618,486
def preprocess(data): """ Function used to preprocess the input and output for the model. The input gets the special [SEP] token and the output gets a space added. """ return { "input": data['premise'] + '</s>' + data['hypothesis'], "output": str(data['label']) + ' ' + data['explanat...
ea96469640bd0ac52ee6e7b6690d7dd9a3b964fa
618,488
def basic_obj_get(obj): """Return the value of attribute "value" of "obj".""" return obj.value
81548364873fa2486b189dad714f6c8c87b43fa3
618,490
import string def is_in(s): """Return 1 if the string contains at least one punctuation symbol""" is_p = 0 for i in s: if i in string.punctuation: is_p = 1 break return is_p
167011563f2bdb7d2f1a37a9af3ca591dd40ebdb
618,492
def _is_cov_update_task(task_id, num_tasks): """Returns True if this task should update K-FAC's covariance matrices.""" if num_tasks < 3: return False return 0.6 * num_tasks <= task_id < num_tasks - 1
1a676e8a8e7a69d34b602d72094c45adbbd68eae
618,494
import math def normalize(vx, vy): """ Normalizes the input vector and returns its coordinates. """ norm = math.sqrt(vx * vx + vy * vy) if (norm > 1e-6): vx /= norm vy /= norm return (vx, vy)
097a44668c6dafb4ccb686e0cfe88b11ee449a13
618,495
def get_default_acquisition_for_domain(domain): """ Returns the default acquisition for the domain. """ if domain.get_type() == 'euclidean': return 'ei-ucb-ttei-add_ucb' else: return 'ei-ucb-ttei'
d0bda646e0787b8abe28e9da84403e29b14fbd83
618,499
def can_edit_user(logged_user, target_user): """ Is logged in user allowed to edit target user """ if logged_user == target_user: return True if logged_user.is_staff: return True return False
12b4a3c37d2ad86a1aff70f9f2be0e62e2ccaa66
618,500
from typing import Dict def merge_dict(dest: Dict, src: Dict, path=None, overwrite=True): """ Merges src dict into dest dict. Parameters ---------- dest: Dict dest dict src: Dict source dict path: List merge path overwrite: bool Whether overwrite dest d...
a9d25f2fff6755f0d947b319182e4d0dfbd22f81
618,501
def tokenised(text): """ Return a tokenised text list. :param text: text string to be tokenised. :return: list """ return [word for word in text.split()]
69eb762c822b5ed1c2f6dda9a2c0066a07cddddf
618,502
def subset_to_str_list(subset_sol): """From a subset solution (e.g.: [[0,1],[0,0]]) returns a list with the rows string and the columns string (e.g.: ['0 1', '0 0']) or NO_SOL""" return [' '.join([str(e) for e in subset_sol[0]]), \ ' '.join([str(e) for e in subset_sol[1]])]
ad152f18059fa5615320ed03b6c83ef176da6605
618,505
def _default_with_off_flag(current, default, off_flag): """Helper method for merging command line args and noxfile config. Returns False if off_flag is set, otherwise, returns the default value if set, otherwise, returns the current value. """ return (default or current) and not off_flag
880d826d1c487005102fbacb9d4dcc94fb14f4db
618,507
import math def add_smooth_sigma_round(cli_args, cur_smooth): """ Pull user-defined smoothing variables, calculate the sigma value for additional smoothing, and round the sigma value to 7 decimal places :param cli_args: Dictionary containing all command-line arguments from user :param cur_smooth: ...
56f2f2379738da8b3334f0367d93855c0c77eb8a
618,508
from typing import List def find_min_coins(coins: List[int], index: int, value: int): """ Find minimum number of coins that make a given value :param coins: List of coins. :param index: Length of the coins list minus one, for example: len(coins_list)-1. :param value: Amount required to be filled ...
7fe5782e6a452643ff730ded84d3545a0ff37eb2
618,510
def get_status(data_model, status) -> str: """Get the user friendly status name.""" statuses = data_model["sources"]["quality_time"]["parameters"]["status"]["api_values"] # The statuses have the human readable version of the status as key and the status itself as value so we need to # invert the diction...
cce3b85e8aac3999ead80efd6beae629e4ff8f90
618,511
def is_in_path(file_path, find_str): """ check if find_str is in filename given file path """ file_path = file_path.lower() find_str = find_str.lower() return file_path.split('/')[-1].find(find_str) >= 0
78f5c6a82b8662b9fe3a583fbb9afa828d71b19d
618,514
def partition_list(Z, L): """Returns a dictionary partitioning list L according to assignments in Z. Example: >>> Z = {0:0, 1:2, 2:7, 3: 7, 4:0} >>> L = [2, 1, 0, 4, 3] >>> partition_list(Z, L) {0:[0, 4], 2:[1], 7:[2, 3]} """ result = {} for l in L: k = Z[l] if k in ...
a1bc231aa4704465b21127f632aa6adc563fc0ce
618,519
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing categor...
6ed0b6c7d8b95b4edd19bd2a21f4e76047fa0d1f
618,522
def get_module_version(module): """ Retrieve __version__ variable from an imported module. @param module: The module instance. @type module: module @return: The version hash without the surrounding text. If not present return None. @rtype: str or None """ if hasattr(module, '__v...
380dd62e3120265eeeb884c87580fa27cd443f02
618,523
def dtanh(tanh_x): """ dTanH(x) = 1 - TanH(x)^2 """ return 1 - tanh_x**2
ffabc855b796e154d46769a6d261a57e687d2a2f
618,524
import json import requests def groupAdd(apikey,name): """ Creates a new Group with the chosen Name apikey: Your ApiKey from FileCrypt name: The name of your new group """ data={"api_key":apikey,"fn":"group","sub":"add","name":name,"parent":"0"} return json.loads(requests.post("https://filecrypt.cc/api.php",da...
1db9d922c4c655142a5598064c84644ccd8a8254
618,526
def _is_case_insensitive_substring(a, b): """return True if `a` is a case insensitive substring of `b`, else False""" return str(a).lower() in str(b).lower()
f47c5d15b7d9fd34f6a99465bd23a7c23a53c729
618,528
def update_probability(prior, prob_given_true, prob_given_false): """Update probability using Bayes' rule.""" numerator = prob_given_true * prior denominator = numerator + prob_given_false * (1 - prior) return numerator / denominator
ec6cd75ac0dd83388fc2ec0b5d99e661a6ad7c57
618,530
def h(p1, p2): """Manhattan distance""" (x1, y1), (x2, y2) = p1, p2 return abs(x1 - x2) + abs(y1 - y2)
a4581aa199b4a19c62878bb6e0bf8970a84f7152
618,534
def check_has_backup_this_month(year, month, existing_backups): """ Check if any backup in existing_backups matches year and month. """ for backup in existing_backups: if backup.createdYear == year and backup.createdMonth == month: return True return False
ade68262f374f2e56ba2f60c6e3689a50b87d7a0
618,536
def get_file_info(fname): """ Parse the asset file name e.g. inp: 20200714_103348_ssc6_u0001_analytic.tif out: analytic, 20200714_103348_ssc6_u0001 """ info = fname.split("_") asset_type, other_info = info[4:], info[:4] # for asset_type of 2 words if len(asset_type) == 2: ...
c06c95adab6ad7bcf983d1101dd61bf4163b1d6a
618,537
import unicodedata def normalize_text(text: str) -> str: """ Normalize text to NFC which represents chars as an unique code. Parameters ---------- text: str Input text string. Returns ------- str: Normalized text. """ return unicodedata.normalize("NFC", text)
5a36b2cbe1025300de9ccabcee9dc0ebe8b31dc7
618,541
def rdkit_atom_list(mol, key, method, args=None): """ Make a list of atoms with atomic information from rdkit.mol. Args: mol (rdkit.Chem.Mol): Mol object to get information from. key (str): Key of property to put in list. method (func): Class member method for rdkit.Chem.rdchem.Ato...
e1077f34da7b371abeef4461f09bfd6ba15a4602
618,542
def bounding_box(X): """ Calculates the boundaries of a given dataset on all sides Parameters: X - a data matrix where each row is a dimensional array of an item to be clustered Returns: Two tuples, where the first contains the minimum and maximum x values, and the second con...
98b3b9d1e5f31a2e6375a34e6ba24d4b985ff0ec
618,544
def _calcFlatSizes(canvasaxes, bounds, width, height, vert=True): """Used by :func:`calcVerticalSizes` and :func:`calcHorizontalSizes`. Calculates the width and height, in pixels, of each canvas. :arg vert: If ``True`` the sizes are calculated for a vertical layout; otherwise they are calcu...
1862c758352270dfb2bf0c9887e9803b73703226
618,545
import json def read_json(path): """Read data from JSON file.""" with open(path, 'r') as file: return json.load(file)
f4a991102e67c23b4d6811ebb12e77e461870dfd
618,546
from typing import Optional from typing import TextIO def _open_or_fallback( file_path : Optional[str], mode: str, fallback: Optional[TextIO] ): """ Arguments: file_path: a file path to open, or None to use the fallback. mode: mode to open with (e.g. "w" or "r") fallback: what to use when file_path is...
d82d5a5cd587462f3621580adece8cd08754bcd9
618,547
def Parent(tpe, criterion): """ A criterion used to search for records by filtering the parents using a criterion. For example * search for observables of TLP:RED cases * search for logs of tasks called 'Communication' Arguments: tpe (str): class name of the parent: `case`, `case_task`...
6d9d5dc2b7a7ab88524ac5b3d97184b4147bc25e
618,551
from typing import Iterable from typing import Mapping from typing import Any from typing import Dict def combine_api_output_dictionaries(input_dicts: Iterable[Mapping[str, Any]], require_uniqueness: bool = True ) -> Dict[str, Any]: """Merges...
9be4cea0574934b8552d716ff4048c8c8b827954
618,553
def CP(record): """ "Channel Process": a CP input link will cause the linking record to process any time the linked record is updated. Example (Python source) ----------------------- `my_record.INP = CP(other_record)` Example (Generated DB) ---------------------- `field(INP, "other CP"...
e285204a3518069c7bd948e8a6e98fdb9c76e766
618,556
def _make_dict(lang, my_tup): """Make tuple in a dictionary so can be jsonified into an object. """ labels = ['comment_text', 'offering_city', 'offering_fiscal_year', 'offering_quarter', 'stars', 'nanos'] results = {key: val for key, val in zip(labels, my_tup)} return results
c32e11970d68fcc7e1ae6086befc23b24aedf6ac
618,559
def decompose_mask_status( x ): """ Given a mask value, decompose what sub-status compose it Example: One pixel mask value is 928: 928 decompose into 32, 128, 256, 512 :Parameters: x: int Mask value :Returns: powers: list of int List of powers of 2 ma...
cda8b006174dd696f3fef2c96ae16791741d844d
618,565
def lower(text): """Returns text that has been lower. Args: text (str): input text to process. Output: result (str): corresponding text which has been lower. """ return text.lower()
f75f26b7096c0432fe56083483cda515e8949430
618,566
def segment_signal(signal, length=2, skip=0.5, sample_rate=257): """ Segments a signal into overlapping sections with defined length and skip size :param signal: the signal to segment :param length: the length of each segment (in seconds) :param skip: length of the space between the start of two co...
b19f4f2ee4a43115c04919d57bcf311861d8adfe
618,567
def build_portfolio(processed_market, portfolio): """Build a processed portfolio by reindex processed_market dataframe""" return processed_market.reindex(portfolio.index)
41ca06c200e0806dfe6248f8c0817df2ea1c8c06
618,570
import yaml def patterns(package_root): """Grab glob patterns from config file. """ conf_file = package_root.parent / "addheader.yml" if not conf_file.exists(): print(f"Cannot load configuration file from '{conf_file}'. Perhaps this is not development mode?") return None with open(...
9b93249f42830fdee250e07fd07e7d9c52eb2b12
618,571
import json def s3_create_anon_access_policy(bucket_name): """Create a bucket policy for anonymous read access and anonymous bucket listing. Returns ------- anon_access_policy: A json formatted s3 bucket policy """ anon_policy_dict = { "Version": "2012-10-17", "Statement": [ ...
46dec6e3990cb7bb05dbbbcb34fe49ce8ef26371
618,577
import math def compute_ratio(a_value,b_value): """ Computes the ratio between two values, handles divide by zero errors """ if b_value == 0: if a_value == 0: ratio= float('Nan') else: ratio= math.copysign(float('inf'),a_value) else: ratio= a_value/...
de51edff4dd0f37ccc7511619a06913776c1fb9a
618,578
from typing import Tuple def _in_0_region( interaction_coefficients: Tuple[float, float, float], weyl_tol: float = 1e-8, ) -> bool: """Tests if (x, y, z) ~= (0, 0, 0) assuming x, y, z are canonical.""" x, y, z = interaction_coefficients return abs(x) <= weyl_tol and abs(y) <= weyl_tol and abs(z) <...
97b7b9e296cfae904170e34e5dd4842d42bed9dc
618,580
def get_points(rays_o, rays_d, z_vals): """ Inputs: rays_o: (*Nrays, 3) rays_d: (*Nrays, 3) z_vals: (*Nrays, N) Output: points: (*Nrays, N, 3) """ points = rays_o[..., None, :] + \ rays_d[..., None, :] * z_vals[..., None] return points
fed637f10206ddce12f999bde518275c62132840
618,581
import uuid def get_uuid() -> str: """ Generate UUID. :return: generated UUID """ return str(uuid.uuid4())
5c12bcf1f15a94596ff700d46aa3d4fdfb3c1cad
618,582
def percent_profitable(winning_trades: int, total_trades: int) -> float: """ Percent profitable .. math:: Winning Trades / Total Trades = Percent Profitable :param winning_trades: int of the number of winning trades :param total_trades: int of the total number of trades executed :return: f...
92880718475a9a55536cea05316ce9aa6f5ac805
618,587
def modrange(x, low, high): """mod x such that it is between [low, high). >>> modrange(2.5, 1, 2) 1.5 >>> modrange(3., 1, 2) 1.0 """ spread = high - low diff = x - low mod = diff % spread return low + mod
a5d5fa2e48c8fa7ad9142edca6738d5cb951fbeb
618,592
def plus_two(x): """Add two to the argument.""" return x + 2
7e0e3b72e2091af6ea3e208762cb7946591cfdd8
618,596
import json def get_robot_constraints_json() -> str: """Return a test robot_constraints.json.""" robot_constraints = { "devices": [{ "deviceType": "robot", "parameters": { "jointLimits": [[-363.0000016970871, 363.00000013981145], [-363.00000169...
2804a2d6f3019436858166ced53fe3a24b92ecd0
618,599
def update_routing_segmentation_maps_from_source_segment( self, segment_id: int, segment_map: dict, ) -> bool: """Update D-NAT policies for specific source segment .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - vrf ...
d6360c83bb6ee44804703dac5315ba5f575d3cfa
618,600
import calendar def datetime2epoch(dt): """Convert a non-naive datetime object to a UNIX epoch timestamp""" return calendar.timegm(dt.utctimetuple())
d22e24688df9b79b5315d9045b45b70ebc9e0704
618,603
def biggest_differences_paragraphs(table): """ Finds the paragraphs with greatest average differences between words and their most frequent alternative across each semantic dimension Parameters ---------- table : a data frame The data frame representing average a paragraph's arousal, va...
ccae584f7672ee87fd348f246a2f4fbe06b106f9
618,604
def element(point, p, q, n): """Test, whether the given point is on the curve (p, q, n)""" if point: x, y = point return (x * x * x - p * x - q) % n == (y * y) % n else: return True
0433af33e5567597592d2b7fe07420317851b506
618,605
def parse_mtm(mtm_serial): """ Parses a mtm_serial string to a result of machine, model, serial """ mtm, serial = mtm_serial.split('_', 1) model = mtm[4:7] machine = mtm[0:4] return machine, model, serial
da0f8b35b88472ef0755f05d24a5623d34c9d924
618,607
def isdigit(char): """Return True iff char is a digit. """ return char.isdigit()
0d4cd1b041c50c5585abf3d685cc40719b54e192
618,608
def mod(a, b): """ Given two numbers, this function will return the first number modulo the second number """ return a % b
f527ef84d40d8f1c6aa0532fc93906b008bf6d83
618,609
def scriptClose(*args, **kwargs): """ Close the current script or group. Returns True if successful. """ return None
7df5b282258e557ae670b611d89276d25a292549
618,610
import json def load_config(config_file="config.json"): """ Read the given file to build configuration, the configuration needs to be json """ return json.load(open(config_file))
b15db951d467b5c5126e9348acf9c6d2769c7b4a
618,612
import hashlib import json def hash_dict(exp_dict): """Create a hash for an experiment""" return hashlib.md5(json.dumps(exp_dict, sort_keys=True).encode("utf-8")).hexdigest()
39ad50bba4c8a60d8eb3bdb48a1510f0fe94f2c6
618,615
def esc (s, is_attribute=False): """ escape XML special charcters Parameters: is_attribute if True, also escape " and ' for attribute values Returns: the escaped string """ s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") if is_attribute: return s.r...
17bf456740ef3e43b51f6fd45fc0df888e6d28f7
618,616
def is_admin(token): """Check if token has an admin role.""" roles = token.credentials.get("https://api.imjoy.io/roles", []) if "admin" not in roles: return False return True
ca720d697e57428c884fdb482f4565983fdaf354
618,619
def _center_strip_right(text: str, width: int) -> str: """Returns a string with sufficient leading whitespace such that `text` would be centered within the specified `width` plus a trailing newline.""" space = (width - len(text)) // 2 return space * " " + text + "\n"
ee858fc5fa1d9c37d263f6cc5ca6b5b2981164ea
618,622
def max_res_from_play_info( play_info: dict ) -> dict: """This is the parser for finding maximum resolution from play info (FVideo, VOD). Arguments: play_info (:class:`dict`) : Play info dict to find maximum resolution. Returns: :class:`dict`. Video data that has maximum resolution...
afd537e4cf10c26d9e04ed5a1af4f83ce358ee01
618,623
def to_visfmt(annot): """ Helper function that changes (tw,th,bw,bh) -> (tw,th,w,h). Used to convert annotations from ilsvr to visdrone's since most scripts are already written in visdrone's format. """ #Check if it's an empty bbox (neg scene) if len(annot) > 1: load = [annot[0]...
2982f0e97f316a237d742e98e397a7bdcbb1f3b8
618,624
def triangle_area(a, b, c): """ Return the area of the triangle defined by ``[a, b, c]``, where each vertex contains floats ``[x, y]`` """ return 0.5 * abs( a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]) )
5752abefc1e5dfedb46e9406aeec81b041270715
618,625
def owner_ids_to_string_array(owner_ids): """ Converts a snowflake owner id to an array of strings. Parameters ---------- owner_ids : `iterable` of `int` Snowflakes. Returns ------- owner_id_array : `list` of `str` """ return [str(owner_id) for owner_id in owner...
717fd5c7d1199979de93a986bc64747da0ed516f
618,628
def solution_linear(k: int, list_: list[int]) -> bool: """ O(n) Returns True if k can be found by addition of any 2 numbers in list """ potential = set() for a in list_: if a in potential: return True potential.add(k - a) return False
99dafc7b4e19e2c02890a2566f0d18f92c4867fa
618,631
import logging def clean_eventbrite_url (url): """ Remove unneeded query info from Eventbrite URL """ if url.find('?') >= 0: try: base, params = url.split("?", 1) except ValueError as e: logging.error( "Could not split." "Offending url is {}".f...
7acee737b8892d896be1e3b5a56a79e1f82f60ba
618,633
def get_need_size_for_each_dimension(used_coordinates: list, num_dimensions) -> list: """ Given a list of tuples, where each tuple is a 2N dimensional coordinate, get back a tuple of length 2N with the max value in each coordinate (plus 1 so the number is correct for sizing buffers) :param used_coordina...
9b9c25acaa26a207644c03496549929c52df5f4f
618,634
import pickle def unserialize_data(filename): """ Returns the stored dictionary of vocabulary given the filename in 'filename.pickle' format (filename must be a string). """ with open(f'pickles/{filename}', 'rb') as f: stored_vocab = pickle.load(f) return stored_vocab
780a0b72587ab852bfdcb9acb52235304ff6b244
618,637
import math def gsd(lat, zoom): """ Computes the Ground Sample Distance (GSD). More details can be found here: https://msdn.microsoft.com/en-us/library/bb259689.aspx Args: lat : float - latitude of the GSD of interest zoom : int - zoom level (WMTS) """ return (math.cos(lat * ...
fd7b2a44637e0b6de2dfddb14a0d48d70b06ec5d
618,647
import itertools def _get_available_name(original, cond): """ Iterate over possibles names for original string, adding a different number as suffix at each iteration. The new name is available by checking if it pass the condition. """ for c in itertools.chain([""], itertools.count()): suff...
5a4ddd4f3189ab1a34e0bc0a04a929395c20bdb4
618,651
def GetGaiaContext(tab): """Returns Gaia's login page context.""" for context in tab.GetWebviewContexts(): if context.GetUrl().startswith('https://accounts.google.com/'): return context return None
77ee25ac31ab963b9b9d6ac46928e9fea78d23d7
618,654
def get_unit(operation, num, primary=True): """Return the correct form of the unit tracked by the given operation.""" if not primary: return "ISK" types = { "killboard": "ship|ships", "collection": "item|items" } if "unit" in operation: unit = operation["unit"] e...
00df2f9a2b00c879299b2a3d5c50e14aa4bc3867
618,655
import math def BIC(loglik, k, n): """ Bayesian Information Criterion Parameters ---------- loglik : float Log likelihood k : int Parameters estimated n : int Number of observations Parameters ---------- float BIC, the smaller the better """ ...
dd2faa9fd4ac94eb4b2f6a00410ea428615691d2
618,657
def is_close(a0, a1, tol=1.0e-4): """ Check if two elements are almost equal with a tolerance. :param a0: number to compare :param a1: number to compare :param tol: The absolute tolerance :return: Returns boolean value if the values are almost equal """ return abs(a0 - a1) < tol
8c4eafb3640043168bc0571b262414c419d79a26
618,658
def _split_str(s, n): """ split string into list of strings by specified number. """ length = len(s) return [s[i:i + n] for i in range(0, length, n)]
c67417df306ea615c8f8fa6499294a537794816f
618,660