content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def group_repr(group_keys): """Get a string representation of a list of group keys""" if len(group_keys) == 0: return "{}" elif len(group_keys) == 1: return str(group_keys[0]) else: out = f"{group_keys[0]}" for key in group_keys[1:]: out += " x " o...
da8bb930ea09695334143d885dac34e18d8028d3
613,455
import re def determine_task_base_name(task_name: str, build_variant: str) -> str: """ Determine the base name of a task. For generated tasks the base name will have the build variant and sub-task index stripped off. For other tasks, it is the unmodified task_name. :param task_name: Name of task...
0b4f5f9ddd515b02b45706159da8399eaa791a1c
613,459
def _adjust_component(val: int) -> int: """ Written by Akshay Vashisht Returns the midpoint of the quadrant in which val is in. val must be between 0 and 255 inclusive. The 4 quadrants are 0 to 63, 64 to 127, 128 to 191, 192 to 255. The repespective midpoints of these quadrants are 31, 95, 159...
93c74171ebd96305c6e299e4ea4e7816b5523942
613,463
def get_full_action_name(service, action_name): """ Gets the proper formatting for an action - the service, plus colon, plus action name. :param service: service name, like s3 :param action_name: action name, like createbucket :return: the resulting string """ action = service + ':' + action...
f69eb13000fe92cd13783148c8ee340c45bd6591
613,464
def in_facebook_app(request): """ Determine if the given request points to a page within the Facebook app. """ return request.path.startswith('/fb')
d256953f78ef8dd02f3cf3c3e1f9c006dec94cdb
613,465
def get_word_with_letter_missing(word: str, position: int) -> str: """ >>> get_word_with_letter_missing('dog', 0) '?og' >>> get_word_with_letter_missing('dog', 1) 'd?g' >>> get_word_with_letter_missing('dog', 2) 'do?' """ if position == 0: return f'?{word[1:]}' if positio...
3383e8c739ea912d1270e6d8de71274891dba3c0
613,466
import math def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num...
20801f96a4795f7b0f56b5e366f53c797298fd23
613,468
from typing import List def card_average(hand: List[int]) -> float: """ :param hand: list - cards in hand. :return: float - average value of the cards in the hand. """ return sum(hand) / len(hand)
49aa3f8d4b82606250d491985c9aa9ff192703ef
613,471
def get_const_type(const_node): """Returns const's type. Args: const_node: const node Returns: str which is constant type. """ return const_node.GetChildren()[0].GetName()
61bc8fbe5203cd44bcd323a08bcec0a875256d84
613,479
def key_params(api): """Build a unique key from the builder name (as a list). E.g. arch x86 gpu GeForce320M mode MacMini4.1 os Mac10.6 """ # Don't bother to include role, which is always Test. blacklist = ['role', 'test_filter'] flat = [] for k in sorted(api.vars.builder_cfg.keys()): if k not in bl...
be16376bb9fc7b0c88716e86a819f72f0ad39c9e
613,480
import logging def get_spiro_vals(key: str, rec: dict) -> tuple: """ Takes a spirometry test (eg FEV1, FVC, etc) as key and returns an 8-tuple with pre then post measured, %predicted, SR as well as predicted and percent change Fills tuple position with None if value doesn't exist """ if not ke...
653ef2e12c1c8edbc01eae2221013f976b81adde
613,484
import platform import collections def get_local_rank_size(comm): """ Returns the rank of each process on its machine The processes on a given machine will be assigned ranks 0, 1, 2, ..., N-1, where N is the number of processes on this machine. Useful if you want to assign one gpu per mach...
3dd3d6da487c9e0fa0901b142a91998e2bf8cec5
613,485
import math def polar2cart(radius, xCoordinate, yCoordinate, polarAngle): """Changes polar coordinates to cartesian coordinate system. :param radius: Radius :param xCoordinate: x coordinate of the origin :param yCoordinate: y coordinate of the origin :param polarAngle: Angle :return: Cartesian...
ebcd22cd6ad9aa117dff3b017827869f7f0634df
613,488
import random def randomize_parameter(parameter_set, parameter_name, lower_bound, upper_bound): """ Change a parameter to a random value within the specified range. `parameter_name` in `parameter_set` will be changed in-place to the randomly selected value in `[lower_bound, upp...
1cc7921bc1af6602b990a082dee00cd58a968558
613,489
import torch from typing import Tuple def get_output_shape(network: torch.nn.Module, input_shape: Tuple[int, ...] ) -> Tuple[int, ...]: """ Run a dummy forward pass to get the output shape of the backbone. Can and should be overridden by subclasses that know the output shape witho...
467b6760ce46b9f7d865c430030ff22bf53a5923
613,497
import torch def sample_images_at_mc_locs(target_images, sampled_rays_xy): """ Given a set of Monte Carlo pixel locations `sampled_rays_xy`, this method samples the tensor `target_images` at the respective 2D locations. This function is used in order to extract the colors from ground truth im...
8905d7464f7a05ac643f35ca46c78bb678864111
613,499
def split_up_key_and_value(key_value_string): """Split up 'key=value' into 'key' and 'value'.""" parts = key_value_string.split('=') key = parts[0] if len(parts) > 0 else None value = parts[1] if len(parts) > 1 else None return (key, value)
4d5097a7394ddf5d415715db630172427f001b55
613,500
from typing import List def stringify(self: List[str]) -> str: """ Convert the list of strings to a string separated by / :param self: the list of strings :return: a string combined from the input list """ return '/'.join(self)
bfe830fc95ac9961c7f7df1f1bde051b7a3143e4
613,501
def _name_loggers(steps, loggers): """Names loggers in the format rubicon-ml expects them. Parameters ---------- steps: list of tuples of (str, sklearn.Estimator) The named estimator steps. loggers: list of rubicon_ml.sklearn.EstimatorLogger The rubicon-ml loggers. Returns ...
72be5e580d0290fb39dae1d644d27959da8ed0d1
613,503
from typing import Counter def consensus_maker(grouped_reads_list, cut_off): """ Create a consensus read using the most_common letter from each position """ num_reads = float(len(grouped_reads_list)) counters = [Counter(x) for x in zip(*grouped_reads_list)] consensus_read = ''.join( [c...
51d862257bdd4313cfe325d188cd8200b5c56bd3
613,508
def get_class_list(elt): """Return the list of CSS classes of an element.""" value = elt.get_attribute('class') return value.split() if value else []
96a236354c01dec7904db056b4f910653d542ddc
613,511
def get_dictionary_depth(d): """ Computes the depth of a nested dictionary recursively. Modified from https://www.geeksforgeeks.org/python-find-depth-of-a-dictionary/. Parameters ---------- d : dict The dictionary, the depth should be computed of. Returns ------- int ...
ae00423e152d00ea4892411343e401db1e1c1d0d
613,513
def recursive_len(item): """Calculate the number of elements in nested list Args: item (list): list of lists (i.e. nested list) Returns: Total number of elements in nested list """ if type(item) == list: return sum(recursive_len(subitem) for subitem in item) else: retu...
130d1706275c3f0eac4f4fe1f08d656d03f76ffc
613,515
def get_first_line_doc(any_type): """ Get the first line of the docstring of an object. Leading spaces are ignored and a trailing dot is being removed. :param any_type: the object :returns: the first line of the `__doc__` attribute of the object, otherwise an empty string :rtype: str ...
0f39cd744c56f8f49d860c4d838de67af43facab
613,516
def sentiments_to_list(doc_id, analyzed, single_document=False): """Converts sentiments response to flat lists with doc_id included :param doc_id: Will be inserted to each row as first element :param analyzed: Response json from anacode api for sentiment call :type analyzed: list :param single_docu...
4546aa8bc7a69a8245b97a4f43d06313154106df
613,520
def getdepth(tree): """ Returns the depth of the tree param tree -- the decision tree """ if tree.tb is None and tree.fb is None: return 0 return max(getdepth(tree.tb), getdepth(tree.fb)) + 1
0eaa619c20ac9743bd2663f7ed3a507a09ea7d45
613,523
import random def generate_cid() -> int: """Generate a valid CID""" # Exclude 0 and u32_max (0xffff_ffff) return random.randrange(1, 0xFFFFFFFF)
dbf0b6c938729bb3d61d1c4ba3f95302ea0eaaba
613,525
def fib(n): """Return Fibonacci sequence with length "n". Args: n: The length of the sequence to return. Returns: A list containing the Fibonacci sequence. """ result = [] a, b = 0, 1 for _ in range(n): result.append(b) a, b = b, a + b return result
8cc39b4e351f6530b306999c5ee5e1c4a07ec153
613,526
import gzip import pickle import difflib def get_model(model_id): """ Return sets of Inchikeys and names associated with the model id :param model_id: the name of the metabolic model :type model_id: str :return: :rtype: tuple(set, set) """ def get_set(file): with gzip.GzipFile(...
cd4f2b2e16a2d81a5c7fc12223f3f72cdc8377b7
613,529
def sizeof(args): """Return a string that describes the size of a list of arguments.""" return " + ".join(a["sizeof"] for a in args) if args != [] else "0"
a1afcf333678305e9e1c6e6dfda021d5b52f1dcb
613,530
def readVectorRaw(text): """Reads a vector from raw text 'v1 ... vn'""" items = text.split() return [float(v) for v in items]
10f0142227f36b8151da386fd5a72f6e54d4c022
613,531
def from_preorder(arr: list) -> dict: """ Convert a depth-first pre-order array to binary tree, returning the root node. """ node = {} size = len(arr) if size > 0 and arr[0] is not None: node['value'] = arr[0] half = (size // 2) + 1 if half > 1: half_1st = fro...
b6c15814568bbb22e9bfc184e431b33f79a55bd7
613,534
import inspect def _qualified_name(obj) -> str: """ Return the qualified name (e.g. package.module.Type) for the given object. Builtins and types from the :mod:`typing` package get special treatment by having the module name stripped from the generated name. """ type_ = obj if inspect.isclass...
e62af06946fd31f41b494f7c13c7d02990680035
613,540
def clean_opm_license_list(df): """This function takes the OPM Granted Licenses list (as a DataFrame) as input and cleans various aspects of it before returning it. Parameters ---------- df (DataFrame) : OPM Granted Licenses list Returns ------- df (DataFrame) : df after being cleaned. ...
1bcf84b52d9560c6a9d89c16168d66c7efc995af
613,541
import json def get_all_stations(stations_file: str) -> dict: """ Read stations map from a file :param stations_file: :return: """ with open(stations_file) as fptr: return json.load(fptr)
54384ec0af4525d4c6264be85969186ba786872f
613,543
def rrx(a, b, carry): """Rotate right with extend (Use carry as a 33rd bit) Returns (result, carry) """ b &= 31 a = (a & 0xffffffff) | ((carry & 1) << 32) a = (a >> b) | (a << (33 - b)) return (a & 0xffffffff, 1 & (a >> 32))
2782bfdd8d2df526b89dfa91d5c5f6905c8824b2
613,547
def clone_lc(client, lc, name, image_id): """ Create a new Launch Configuration identical to the one passed in, except for the new name and new image ID. """ PARAMS_TO_CLONE = [ 'KeyName', 'SecurityGroups', 'ClassicLinkVPCId', 'ClassicLinkVPCSecurityGroups', ...
7ae25b259a1af9f8bce6b66d0c979e95c121eed3
613,548
def assign_additional_hostname_choices(actions, objects): """ Generate choices with networks common for each object. Args: actions: Transition action list objects: Django models objects Returns: list of tuples with available network choices """ networks = [] for obj...
d5c652b38cf548b771e1240376db15ba57855544
613,549
def res_set_to_phenotype(res_set, full_list): """ Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which resources are present. Inputs: res_set - a set of strings indicating which resources are present full_list - a list of strings indicat...
e2bb9e00cf6e9e216009a68cb6a356465f4dbed1
613,552
def _get_owner(accounts, cloud_machine): """ For a given cloud machine, attempt to find the owners username Priority is given to 'owner' which will point to the projectId/tenantId that created the image Otherwise, accept the 'application_owner' (Older openstack+glance may not have 'owner' attribute) ...
fcb62a920e543b3468c54d5f67488f2ae1716672
613,553
def __zero_mat_list__(n=3): """Return a zero mat in list format. Args: n (int, optional): Length of the edge. Defaults to 3. Returns: list: List[List[int]] """ ret_list = [[0] * n for _ in range(n)] return ret_list
7070db52e3c82b4d7bbf1acb1edfd518cd15f606
613,554
def is_multiple(base, multiple): """Determine if base is a multiple of multiple Args: base (Integer): Base value multiple (Integer): Multiple value Returns: Boolean: True if base is a multiple of multiple, false otherwise """ if multiple == 0: return False ...
8950fa5a5e46db3647e78f0e147cf80b65ca2d08
613,557
import requests def report_instance_id(connection, report_id, instance_id, offset, limit, verbose=False): """ Get the results of a previously created report instance, using the in-memory report instance created by a POST /reports/{reportId}/instances request. :param connection: MicroStrategy REST API con...
4ada75c695e4b68a11dc037c0def2a022c0a7128
613,560
def folder_name(counter): """ Return the name of a folder generated by this plugin given a counter """ return f"fs{counter}"
4d1786a86aa1ee7d75dc394f392cdfe3ae6236af
613,561
def parse_time(timestring): """ Given a string of the format YYYY-MM-DDTHH:MM:SS.SS-HH:MM (and optionally a DST flag), convert to and return a numeric value for elapsed seconds since midnight (date, UTC offset and/or decimal fractions of second are ignored). """ date_time = timestrin...
7b4adbe36fbd5fd8f484b1e0b346c9673183e555
613,562
def prune_dataframe(df, columns, drop_allps=True): """ Keeps only specified columns. Drops duplicates and missing data. """ new_df = df.copy() if drop_allps: new_df = new_df.loc[new_df.content_audience != 'allps'] return new_df[columns].dropna().drop_duplicates()
c8527e8283274effe66ad8c20a73f4016f8d1b35
613,565
import yaml def get_settings(settings_file): """ Gets the settings from the settings file. Args: settings_file (str): Path to the settings file. Returns: dict: Dictionary of the settings. """ return yaml.load(open(settings_file, "r"), Loader=yaml.Load...
69f8ec125eee9563928e3e8bafee5c1e0eeed218
613,568
def atom_frac_cols(fracs): """Return columns corresponding to the average atom fraction :fracs: list str :returns: list str """ return ["<atom_frac({})>".format(f) for f in fracs]
22d59f9833ace20e4e6e52a828d0f0aca8658e23
613,569
def intToID(idnum): """ Returns the ID name for the given ID number, spreadsheet-style, i.e. from a to z, then from aa to az, ba to bz, etc., until zz. """ rid = '' while idnum > 0: idnum -= 1 rid = chr((idnum % 26) + ord('a')) + rid idnum = int(idnum / 26) return rid
06acc487972f28fdf6656f60d348efb1e3e5aaff
613,571
def subset_answer_choices(answer): """ If a user changes their answers multiple times, an iOS device will have redundant answers at the beginning and end of the list, so we remove them. Args: answer(list): List of changed answers Returns: answer(list): List o...
e3a3facbaacef20ce2ccce34b400118902d7b61f
613,572
import torch from typing import List def drop_connect(inputs: torch.Tensor, p: float, training: bool) -> torch.Tensor: """ Drop connect layer that drops individual connections. Differs from dropout as dropconnect drops connections instead of whole neurons as in dropout. Based on `Deep Networks with S...
4bc4ac13af28a605e6708e462b689d81f8f7a5af
613,578
def CheckBuildbotPendingBuilds(input_api, output_api, source_file_filter=None): """Check to see if there's a backlog on the pending CL queue""" return input_api.canned_checks.CheckBuildbotPendingBuilds( input_api, output_api, 'http://build.chromium.org/p/chromiumos/json/builders?filter=1', 6...
d4603c98b945a3e014d66b73d20ca1a40ef4f904
613,579
def bbox(tile_coord, grid): """ >>> from mapproxy.grid import tile_grid >>> grid = tile_grid(4326, bbox=(0, -15, 10, -5)) >>> bbox((0, 0, 0), grid) '0.00000000,-15.00000000,10.00000000,-5.00000000' >>> bbox((0, 0, 1), grid) '0.00000000,-15.00000000,5.00000000,-10.00000000' >>> grid ...
2968e66aecd446d26fca6539b5814808d7673de2
613,584
from pathlib import Path def cat(path: Path) -> str: """Concatenate contents of path to stdout.""" return path.read_text()
6adb743cc4e45625a6d3bf90fdf935b892d87824
613,585
import re def het(genotype): """ Determine whether a genotype in format A|G is het. :param genotype: genotype, str. :return: bool, True = het, False = hom. """ if ':' in genotype: genotype = genotype.split(':')[0] hap1, hap2 = re.split("/|\|", genotype) return hap1 != hap2
334c98c9cd7adc321094d2a37ad25c9cb1852ea0
613,586
def retr_lattice_vecs(xtalstr,ini0): """ Retrieve the lattice vectors. The lattice vectors are extracted from the structure instance. They are added to the dictionary passed in. The updated dictionary is returned. The lattice vectors are given in Bohr. """ # print(xtalstr.real_lattice) ...
4db659d12107ebe874990cdb4787441bbd5c8868
613,591
def format_memline(line): """Create the output string for a memory profile recording.""" return "MEM {0:.6f} {1:.4f}\n".format(*line)
f8dc26e1f562f9570c946a79bd4251793257d711
613,592
import re def str_from_text(text): """ Return content of a free form text block as a string. """ REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE) match = REGEX.match(text) if match: return match.group(1) else: return None
0a96ae04b154760422b4d928c28b3c8e622ec493
613,601
import base64 def bytesToStr64u(bytes): """ Convert and return bytes string to unicode base64 url-file safe version """ return base64.urlsafe_b64encode(bytes).decode("utf-8")
bb42b2a955ff40f2595ac1c059a6518a77cde6d1
613,602
def docker_cleanup(request): """Conditionally keep containers around by overriding the cleanup command.""" if request.config.getoption("--keep-containers"): # Print version and exit. return "-v" return "down -v"
7d57153c91b414aa74b5138a841926fbe1af621c
613,603
def gene_list_intersect(gmt_genes, dataset_genes): """return the intersection between the current gene list HGNC symbols and the columns in the dataset. return a second list, `missing` for any genes that are missing. """ intersect = [x for x in gmt_genes if x in dataset_genes] missing = [x for x...
24789b920f6aa856271bb2494d5cd754d03d3339
613,607
def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_t...
efa60134fa2e5606da2be232e3e40e16393a4ea3
613,608
import torch def move_to(obj, device): """ Transfer to gpu for nested objects from https://discuss.pytorch.org/t/66283/2 """ if torch.is_tensor(obj): return obj.to(device) elif isinstance(obj, dict): res = {} for k, v in obj.items(): res[k] = move_to(v, device) ...
403b2f66d4a9db311cb8a387f47782fc141bb1dd
613,611
def uleb128Decode(num): """ Decode uleb128 -> int num -- encoded uleb128 return -- list. [total, length] """ shift = 0 arr = [0,0] #total, length while True: b = num[arr[1]] arr[1]+=1 arr[0] = arr[0] | (int(b & 127) << shift) if b & 128 == 0: break shift += 7 return arr
ff613a3400a46e0f6970b459cce69260be4f4d04
613,617
import math def _factor(n): """Return list of factors of n <= sqrt(n).""" return [i for i in range(1, int(math.sqrt(n) + 1)) if n % i == 0]
9396123d17aa4023763abc14246657c1e67c9e32
613,618
def nfloat(source): """Convert to float or None >>> nfloat(b'') >>> nfloat(b'123.45') 123.45 """ if len(source) == 0: return None return float(source)
df595b5a4c46e2c829ce3774b5f10bfa4793278b
613,624
def generate_choicefield_description(model, enum_choice: str) -> str: """ Generates the description of the filtering fields for the API documentation generator :param model: Filtered model :param enum_choice: Enum with options defined in the model (subclass of django.db.models.TextChoices) """ e...
7e8d8b3db9cfde84d56571b0211fbd1b5cd9ab9c
613,625
def proposed_scaling_both(current, desired): """ identify a single scalar to scale the image by so that it is closer to the desired scaling (fills the space as much as possible) Arguments --------- current : tuple float tuple of current size of svg object desired : tuple fl...
a3bb42c10dfcfcbfc01e74a42198b7b14238453a
613,626
from typing import Tuple def get_f(n: int, func: int) -> Tuple[int, int]: """Return f(0), f(1).""" power = 1 << (n - 1) f1 = func >> power f2 = func & (1 << power) - 1 return f1, f2
3ef2859a1b3f3a318f2c29e9ebfaf786422f98af
613,629
import math def is_prime(x): """ Checks if x is prime """ if x <= 1: return False for i in range(2, round(math.sqrt(x)) + 1): if x % i == 0: return False else: return True
93d896b5068aac479036a554122772e9de843dcb
613,632
def quality_to_factor(quality): """ Calculate factor corresponding to quality Input: quality(float): Quality for jpeg compression Output: factor(float): Compression factor """ if quality < 50: quality = 5000. / quality else: quality = 200. - quality*2 return q...
d7577e66cedb84bfd50bb57ec1cc4ac940dc2961
613,637
def sequences_match(seq1,seq2,max_mismatches=0): """Determine whether two sequences match with specified tolerance Returns True if sequences 'seq1' and 'seq2' are consider to match, and False if not. By default sequences only match if they are identical. This condition can be loosen by specify a ...
82794a1d61084a7747d48e81bcf3e5f16b876a29
613,640
import base64 def base64_64format_encode(v: bytes) -> str: """ Encode in ``64'{base64encoded}'`` format. Example: .. code-block:: python base64_64format_encode(b"hello") == "64'aGVsbG8='" """ return "64'{}'".format(base64.b64encode(v).decode('ascii'))
ff992b2ffb9ba7a5484a18fa2d11f9cab61edcaf
613,649
def find_orbital_distance(obj_1, obj_2, ind_orbs): """ Takes two strings, obj_1 and obj_2 and a dictionary of all the direct and indirect orbits in the orbital map. Searches for a common orbit in the orbit lists of both objects and then determines the number of orbits from each object to the c...
0c306757bb21f3df2150fabbbc8e6efef56044a9
613,651
import math def distance(point_1, point_2): """Distance between the 2 points""" return math.sqrt((point_1[0] - point_2[0]) ** 2 + (point_1[1] - point_2[1]) ** 2)
c5fbf66a78088fbdaaf8fe161d7c5d628b4855f0
613,654
def get_layer(model, layer_name): """ Return the targeted layer (nn.Module Object) given a hierarchical layer name, separated by /. Args: model (model): model to get layers from. layer_name (str): name of the layer. Returns: prev_module (nn.Module): the layer from the model w...
687c33d87ffb24df2c6d216af0e3f64b331778b3
613,657
def build_vocab(sentences, verbose = True): """ build_vocab builds a ordered dictionary of words and their frequency in your text corpus. :param sentences: list of list of words :return: dictionary of words and their count """ vocab = {} for sentence in sentences: for word in senten...
4dacecc6ee86e7e3cae867d5a43d279ee1cc46c1
613,658
import logging def get_default_log_formatter(use_timestamp): """Creates a formatter with the default format [time] [name] [level] [message]""" format = "%(name)s - %(levelname)s - %(message)s" if use_timestamp: format = "%(asctime)s - " + format return logging.Formatter(format)
c556ff7df8d7be2c9f17f983acd315f9aaaf58a7
613,663
from typing import List def combine_name_list(names: List[str]) -> str: """Combines a list of names in the English comma, and format.""" if len(names) == 1: return names[0] return ", ".join(names[:-1]) + ", and " + names[-1]
5bbeaca166c2e7baca98a5b5b739415eabe095f9
613,664
def is_verilog_header(file_name): """ Vivado uses *_support.v for headers instead of .vh in some places """ return file_name.endswith(".vh") or file_name.endswith("_support.v") or file_name.endswith("_defines.v")
d18bc441ebccd02597cafaa67cb315a623803c62
613,665
def snake_to_camel(name): """convert a snake-cased string to camel-cased""" return name[0].lower() + "".join( "_" + ch.lower() if ch.isupper() else ch for ch in name[1:])
e528d448e46e3a493a586b45cde1ce198ab3e000
613,667
def native(obj): """ On Py3, this is a no-op: native(obj) -> obj On Py2, returns the corresponding native Py2 types that are superclasses for backported objects from Py3: >>> from future.builtins import str, bytes, int >>> native(str(u'ABC')) u'ABC' >>> type(native(str(u'ABC'))) ...
f25db7c0afd0b83516257e2980cbd02e30b5207e
613,669
from typing import Dict def copy_and_update(target: Dict, updater: Dict) -> Dict: """Copy and update dictionary. Copy dictionary and update it all in one operation. Args: target: The dictionary to copy and update. updater: The updating dictionary. Returns: Dict: A new dictio...
1e78387d531c5deffe2a8a8c4bcaade3c843f369
613,670
def load_file(infile): """Read and return text file as a string of lowercase characters.""" with open(infile) as f: loaded_string = f.read().lower() return loaded_string
0a78a660ddabc897f1c8344c4588e59700687f09
613,671
def possible_sums(interval): """All sums of two numbers in list where numbers are not equal.""" return {i+j for i in interval for j in interval if i!=j}
2f33750286ebfe9a048c6369da550ca83e84ff8f
613,672
def BulletedList(str_list): """Converts a list of string to a bulleted list. The returned list looks like ['- string1','- string2']. Args: str_list: [str], list to be converted. Returns: list of the transformed strings. """ for i in range(len(str_list)): str_list[i] = '- ' + str_list[i] re...
d46f63b66c01caaf384d9de3d549df85460e11d6
613,683
def make_msg(err_or_warn: str, file: str, line: int, msg: str): """ Formats the error message with a file and line number that can be used by IDEs to quickly go to the exact line """ return "{}: {}:{}, {}".format(err_or_warn, file, line, msg)
a93f1e59a0553fc3a0700c2838c31797df7048e3
613,684
def gather_records(file): """Gather up the set of database records that another Librarian will need if we're to upload *file* to it. Right now this function is fairly simple because the relevant code only works with one file at a time. You could imagine extending this function to take a list of fil...
f3016f8073ffe6b820395232dc0db6ffb5bb1d2a
613,691
def str_bool(b): """Convert boolean to a string, in the way expected by the API.""" return "true" if b else "false"
1750bc9cce3aee5c36b67efb86d9265faf012378
613,694
def expect_inv_beta_p_delta(bs_po, br_po, delta): """Compute the expectation of 1/(beta + delta)""" b_mean = br_po / (bs_po - 1) return 1 / (b_mean + delta)
2a38117020f39c483d5eea4f2b3d2560b6dbe97d
613,698
def get_run_type_from_backup_copy(backup_copy): """ Backup copy includes hostname where the backup was taken from. The function extracts the run type from the backup name. :param backup_copy: Backup copy name. :type backup_copy: str :return: Run type. :rtype: str """ chunks = backup...
343d4dcdb4c3c67e5f00dc47adf394d81efdacf0
613,699
def get_appliance_rest_stats( self, ne_pk: str, resource: str, portal_ws: bool, timedout: bool, time_from: int, time_to: int = 0, ) -> list: """Get summary of time used info of rest requests sent to appliances .. list-table:: :header-rows: 1 * - Swagger Section ...
a2639e59528c0cec1a41ebbddfb426632bba440f
613,700
def color_of_row(i, drow): """ determine the color of the circle for a record. * have an error -> red * have some OK/display/stream and no empty -> green """ error = drow["code_error"] n_ok = drow["code_ok"] display = drow["code_display"] stream = drow["code_stream"] empty = drow...
86f7a793f67527f803179a2e6f2c49a17f6126a3
613,705
import re def list_tables_in_sql(query_sql=None, filename=None): """Check and list tables in `query_sql` or `filename`. :param query_sql: str, SQLr :param filename: str, sql file :return: list, tables used in `query_sql` or `filename`. """ pattern = r"(?:from|FROM|join|JOIN|^\s*(?:\s*\[shuffl...
673f128a9cfaf8a3c37f4b863be8caef4c3996d3
613,707
def fluorescence_regional_integration( eem_df, region_bounds={ "excitation_bounds": (-float("inf"), float("inf")), "emission_bounds": (-float("inf"), float("inf")), }, ): """Fluorescence Excitation−Emission Matrix Regional Integration to Quantify Spectra for Dissolved Organic Matter....
de892d85af7a2ab6bc584da9a40f1e31498d59af
613,709
def get_opposite_azimuth(myazi, tolerance=20): """ Get the opposite azimuth plus/minus a tolerance. To be a reference radial, four criteria must be met. Second, these two initial reference radials should be separated by approximately 180. Parameters: =========== myazi: int Azim...
246127830897aaf8982af03388e8fa0e3a839b54
613,710
def state_to_props(state): """Map state to props relevant to component :param state: dict representing full application state :returns: ``state["colorbar"]`` or ``None`` """ return state.get("colorbar", None)
b2f54cf3309a194f896b4de7e54b2ccf8735bf68
613,711
def _texture_path(texture_bricks_name): """ Parameter --------- texture_bricks_name : str name of the world main texture Return ------ texture_path: (str) path corresponding to the texture_bricks_name Raises ------ ValueError : raised if texture_bricks_name is unkwnonw...
415cb3b8c14fbfd8ee2619b4ddab32a37e38e0d4
613,712
def accuracy(returned_scores, actual_scores, deviation): """ Function for computing the accuracy for a given list of scores. The accuracy returns the percentage of scores in returned_scores that differ by at most deviation from the respective score in actual_scores. returned_scores is inteded to st...
c52868eb7432c00845d288e8f5fc2ffed44634f5
613,714
import re def extract_doc_title(string): """Extracts a correctly parsed doc title from a string :param string: The raw doc title :type string: str :return: The normalized doc title, with excess blank lines removed :rtype: str""" doc_title = string.split("===")[0] # If there is a title, strip out excess line ...
fe5d1cef36d790feb70fbf241413b8a667669d9b
613,721