content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _resize_row(array, new_len): """Alter the size of a list to match a specified length If the list is too long, trim it. If it is too short, pad it with Nones Args: array (list): The data set to pad or trim new_len int): The desired length for the data set Returns: list: A copy of the input `array` that has been extended or trimmed """ current_len = len(array) if current_len > new_len: return array[:new_len] else: # pad the row with Nones padding = [None] * (new_len - current_len) return array + padding
810be7f94234e428135598dc32eca99dd0d3fcca
48,738
def pdact(a: float) -> float: """Partial derivative of activation function.""" return a * (1 - a)
98007d118b050911a16776cf604fcbbe9898bc15
48,740
def deep_encode(e, encoding='ascii'): """ Encodes all strings using encoding, default ascii. """ if isinstance(e, dict): return dict((i, deep_encode(j, encoding)) for (i, j) in e.items()) elif isinstance(e, list): return [deep_encode(i, encoding) for i in e] elif isinstance(e, str): e = e.encode(encoding) return e
6541695e741cb2f47d7d2fe87a45f1d8d8ca67fe
48,742
def simplify_arg_role_name(role_name: str): """Converts the name of the argument role to the simple form (e.g. "Time-Within" to "Time"). """ cols = role_name.split("-") if len(cols) > 1 and cols[0] != "Time": print(cols) return cols[0]
b9cba2234da2656055945da7c39896b1d4d29416
48,749
def find_nth_loc(string=None, search_query=None, n=0): """ Searches the string via the search_query and returns the nth index in which the query occurs. If there are less than 'n' the last loc is returned :param string: Input string, to be searched :type string: str :param search_query: char(s) to find nth occurance of :type search_query: str :param n: The number of occurances to iterate through :type n: int :return idx: Index of the nth or last occurance of the search_query :rtype idx: int :return id_count: Number of identifications prior to idx :rtype id_count: int """ # Return base case, if there's no string, query or n if not string or not search_query or 0 >= n: return -1, 0 # Find index of nth occurrence of search_query idx, pre_idx = -1, -1 id_count = 0 for i in range(0, n): idx = string.find(search_query, idx+1) # Exit for loop once string ends if idx == -1: if pre_idx > 0: idx = pre_idx+1 # rest to last location # If final discovery is not the search query if string[-len(search_query):] != search_query: idx = len(string) break # Keep track of identifications if idx != pre_idx: id_count += 1 pre_idx = idx return idx, id_count
1293bda0ee8a681e8b8647e10fcbadda2a788df5
48,755
from typing import Sequence def count_number_of_depth_increases(depths: Sequence[int], window_size: int = 1) -> int: """Counts the number of times depth increases in a sequence of sonar measurements.""" depth_changes = ( sum(depths[i : i + window_size]) - sum(depths[i - 1 : i - 1 + window_size]) for i in range(1, len(depths) - window_size + 1) ) return sum(d > 0 for d in depth_changes)
8435c3ea61c204ee3db9565f929e0b510420e127
48,756
def validate_tag(tag): """ Chceks if tag is valid. Tag should not be empty and should start with '#' character """ tag = tag.strip().lower() return len(tag) > 1 and tag.startswith("#")
16e112376368567dee7d03faed8f37f14931328b
48,760
def expose_header(header, response): """ Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value """ exposedHeaders = response.get('Access-Control-Expose-Headers', '') exposedHeaders += f', {header}' if exposedHeaders else header response['Access-Control-Expose-Headers'] = exposedHeaders return response
049383730da4fbc5a6286ed072655c28ea647c1e
48,768
def unique(lst): """ Returns a copy of 'lst' with only unique entries. The list is stable (the first occurance is kept). """ found = set() lst2 = [] for i in lst: if i not in found: lst2.append(i) found.add(i) return lst2
6e50803439b65a3fa71814956e947103ca2b634d
48,769
import math def pickLabelFormat(increment): """Pick an appropriate label format for the given increment. Examples: >>> print pickLabelFormat(1) %.0f >>> print pickLabelFormat(20) %.0f >>> print pickLabelFormat(.2) %.1f >>> print pickLabelFormat(.01) %.2f """ i_log = math.log10(increment) if i_log < 0 : i_log = abs(i_log) decimal_places = int(i_log) if i_log != decimal_places : decimal_places += 1 else : decimal_places = 0 return "%%.%df" % decimal_places
a91372f7b1b770531b23147a6704a20bf8a5e689
48,770
def ensure_valid_model_type(specified_type, model_type_list): """ Checks to make sure that `specified_type` is in `model_type_list` and raises a helpful error if this is not the case. Parameters ---------- specified_type : str. Denotes the user-specified model type that is to be checked. model_type_list : list of strings. Contains all of the model types that are acceptable kwarg values. Returns ------- None. """ if specified_type not in model_type_list: msg_1 = "The specified model_type was not valid." msg_2 = "Valid model-types are {}".format(model_type_list) msg_3 = "The passed model-type was: {}".format(specified_type) total_msg = "\n".join([msg_1, msg_2, msg_3]) raise ValueError(total_msg) return None
6708e44d7ea381c89ea31343cb8f435f40fc279f
48,772
import heapq def top10(m): """Return the top 10 keys from a dict ordered by their values.""" return heapq.nlargest(10, m.keys(), key=m.get)
3e5e5eddf6c11a4a46fcb0e3e9bc342cfa219826
48,773
from typing import Union def find_error_character(chunk: str) -> Union[str, None]: """Find the first illegal character for a given chunk.""" stack = [] bracket_mapping = {")": "(", "]": "[", "}": "{", ">": "<"} open_brackets = ["(", "[", "{", "<"] for char in chunk: if char in open_brackets: stack.append(char) else: top_char = stack.pop() if top_char != bracket_mapping[char]: return char return None
fd5aa5360f68b2e61f7d658caedbf1ec67b9de99
48,774
import platform def generate_user_agent(package_name: str, package_version: str) -> str: """Generate a user-agent string in the form <package info> <python info> <os info>. Parameters ---------- package_name : str Name of the package to include in the user-agent string. package_version : str Version of the package to include in the user-agent string. Returns ------- str User-agent string. """ python_implementation = platform.python_implementation() python_version = platform.python_version() os_version = platform.platform() return f"{package_name}/{package_version} {python_implementation}/{python_version} ({os_version})"
adb7d164de435c606a01abc35c963b0f8d5505e8
48,776
def summary(txt): """ Returns the first line of a string. """ lines = txt.split('\n') return lines[0]
eb86e9a5225f2b99b500b79927ef3af1ccc7fabb
48,778
def dict_no_none(*args, **kwargs) -> dict: """ Helper to build a dict containing given key-value pairs where the value is not None. """ return { k: v for k, v in dict(*args, **kwargs).items() if v is not None }
de0dbf04f0cea588f190f9ae52cf2696e0c5c6ea
48,779
from typing import Any def shortname(obj: Any) -> str: """Get object name (non-qualified).""" if not hasattr(obj, '__name__') and hasattr(obj, '__class__'): obj = obj.__class__ return '.'.join((obj.__module__, obj.__name__))
78a3d85ad11e8262d515fb2bead6c9d9fdbf085b
48,780
def unique(sequence): """ Returns a unique list preserve the order of original list """ seen = set() return [x for x in sequence if not (x in seen or seen.add(x))]
433bc766e21f1e0a6e983383054f51ba84cd5636
48,783
def flatten(items): """Removes one level of nesting from items Parameters ---------- items : iterable list of items to flatten one level Returns ------- flattened_items : list list of flattened items, items can be any sequence, but flatten always returns a list. Examples -------- >>> from skbio.util import flatten >>> h = [['a', 'b', 'c', 'd'], [1, 2, 3, 4, 5], ['x', 'y'], ['foo']] >>> print(flatten(h)) ['a', 'b', 'c', 'd', 1, 2, 3, 4, 5, 'x', 'y', 'foo'] """ result = [] for i in items: try: result.extend(i) except TypeError: result.append(i) return result
5c280d08911e4fdbd32de3e20e75410e871b1d57
48,784
def get_help_text(instance, field_name): """ Returns help_text for a field. inspired by https://stackoverflow.com/questions/14496978/fields-verbose-name-in-templates call in template like e.g. get_help_text <classname> "<fieldname>" """ try: label = instance._meta.get_field(field_name).help_text except Exception as e: label = None if label: return "{}".format(label) else: return "No helptext for '{}' provided".format(field_name)
b2432ee430744c28630efe27489c68607ca0a495
48,785
def _format_collider_string(colliders): """ Write the string for the bath gas collider and their efficiencies for the Lindemann and Troe functional expressions: :param colliders: the {collider: efficiency} dct :type colliders: dct {str: float} :return: collider_str: Chemkin string with colliders and efficiencies :rtype: str """ collider_str = ' ' # name_buffer collider_str += ''.join( ('{0:s}/{1:4.3f}/ '.format(collider, efficiency) for collider, efficiency in colliders.items())) collider_str += '\n' return collider_str
4e4aa8ae46dfcf05f00222b4cf5c95384977d651
48,788
def is_users_personal_account(context, account): """ Return `true` if the current path is for the user's personal account. Used to determine which items to show in the settings submenu. """ request = context["request"] return account.is_personal and ( request.path.startswith("/me/") or request.user.is_authenticated and request.path.startswith(f"/{request.user.username}/") )
9a5938761fb3a8c5876152bb326f008b8e607f95
48,793
def layer_size(X, Y): """ Get number of input and output size, and set hidden layer size :param X: input dataset's shape(m, 784) :param Y: input labels's shape(m,1) :return: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size of the output layer """ n_x = X.T.shape[0] n_h = 10 n_y = Y.T.shape[0] return n_x, n_h, n_y
81add6bf528cfe872e62f622161bb25fb7dcb1d3
48,800
from typing import Set def done(job: str, completed: Set[str]) -> str: """Convert set membership into `Yes` for `No`. :param job: The job to check if it was acted on :param completed: The jobs acted on, :returns: Yes or No """ return 'Yes' if job in completed else 'No'
6d056f2471dafb3cab274ffb916e073c2fb62cf6
48,801
from typing import get_origin from typing import get_args def has_origin(typ, origin, num_args=None): """ Determines if a concrete class (a generic class with arguments) matches an origin and has a specified number of arguments. This does a direct match rather than a subclass check. The typing classes use dunder properties such that ``__origin__`` is the generic class and ``__args__`` are the type arguments. Note: in python3.7, the ``__origin__`` attribute changed to reflect native types. This call attempts to work around that so that 3.5 and 3.6 "just work." """ t_origin = get_origin(typ) if not isinstance(origin, tuple): origin = (origin,) return t_origin in origin and (num_args is None or len(get_args(typ)) == num_args)
9ba281ac18f1e152d9456103a61070e8e6c70e09
48,804
def extend(cls, static=False): """Extends the cls class. Parameters ---------- cls : class Class to extend. static : boolean, default = False Wheter extend as a static method. Returns ------- decorator Decorator for extending classes. """ if static: return lambda f: (setattr(cls, f.__name__, staticmethod(f)) or f) else: return lambda f: (setattr(cls, f.__name__, f) or f)
ab3456d11b2ce7edde1a468e743fc77bcc1e3f58
48,807
def create_collector(collector_class, result_dir, test_name): """Return a new Collector of the given class :param collector_class: The collector class to be used. :param result_dir: Directory with test results :param test_name: Test to be run :return: A new CollectorController. """ return collector_class(result_dir, test_name)
5780297706e8ee00b3e7cc7cfd5da7997fd5dd66
48,808
from typing import Dict def multimodel_num_layers() -> Dict[str, int]: """Number of layers in each of sub-models in `multimodel` fixture.""" return { 'encoder': 2, 'forecaster': 6, 'combined': 10, }
115e274decf2e18f5fae31d07fca46183853f513
48,810
def sublist(list1: list, list2: list) -> bool: """ Check if all the element of list1 are inside list2, preserving the order and subsequence of the elements :param list1: list1 of element to find :param list2: list2 target list :return: a boolean which represent True if the statement is respected """ _list2_idx = 0 for element in list2: if element == list1[0]: _list1_idx = 1 _list2_iterator = _list2_idx+1 while _list1_idx < len(list1): try: _value = list2[_list2_iterator] except Exception as ex: return False if _value != list1[_list1_idx]: break _list2_iterator +=1 _list1_idx +=1 if _list1_idx == len(list1): return True _list2_idx +=1 return False
6981a35efe0bb18b9d2ca2593a9f38ea049acb28
48,811
from typing import Dict from typing import List def get_available_languages(localisation: Dict) -> List[str]: """Get list of languages that are available for outputting human readable procedure descriptions. Args: Dict: Localisation collection, e.g. ``PlatformClass().localisation`` Returns: List[str]: List of language codes, e.g. ['en', 'zh'] """ available_languages = ['en'] for _, human_readables in localisation.items(): for language in human_readables: if language not in available_languages: available_languages.append(language) return available_languages
25506eb7a7819f89b54df05e67e65c44f58285bb
48,815
def sql_number_list(target): """ Returns a list of numbers suitable for placement after the SQL IN operator in a query statement, as in "(1, 2, 3)". """ if not target: raise ValueError elif not isinstance(target, list): target = [target] return "(%s)" % (", ".join(["%d" % (i,) for i in target]))
386a8d10ed9fb7f625080eb3636f9d3909cacc6a
48,816
import torch def fold(input: torch.Tensor, window_size: int, height: int, width: int) -> torch.Tensor: """ Fold a tensor of windows again to a 4D feature map :param input: (torch.Tensor) Input tensor of windows [batch size * windows, channels, window size, window size] :param window_size: (int) Window size to be reversed :param height: (int) Height of the feature map :param width: (int) Width of the feature map :return: (torch.Tensor) Folded output tensor of the shape [batch size, channels, height, width] """ # Get channels of windows channels: int = input.shape[1] # Get original batch size batch_size: int = int(input.shape[0] // (height * width // window_size // window_size)) # Reshape input to output: torch.Tensor = input.view(batch_size, height // window_size, width // window_size, channels, window_size, window_size) output: torch.Tensor = output.permute(0, 3, 1, 4, 2, 5).reshape(batch_size, channels, height, width) return output
92a68279b357f8b977d4b144fd249540de833fb5
48,817
from typing import Optional from pathlib import Path def to_uri( path: str, local_basedir: Optional[Path] = None, relative_prefix: str = "" ) -> str: """ Given a path or URI, normalize it to an absolute path. If the path is relative and without protocol, it is prefixed with `relative_prefix` before attempting to resolve it (by default equal to prepending `cwd://`) If path is already http(s):// or file://... path, do nothing to it. If the path is absolute (starts with a slash), just prepend file:// If the path is cwd://, resolve based on CWD (even if starting with a slash) If the path is local://, resolve based on `local_basedir` (if not given, CWD is used) Result is either http(s):// or a file:// path that can be read with urlopen. """ local_basedir = local_basedir or Path("") if str(path)[0] != "/" and str(path).find("://") < 0: path = relative_prefix + path prot, rest = "", "" prs = str(path).split("://") if len(prs) == 1: rest = prs[0] else: prot, rest = prs if prot.startswith(("http", "file")): return path # nothing to do elif prot == "local": # relative, but not to CWD, but a custom path rest = str((local_basedir / rest.lstrip("/")).absolute()) elif prot == "cwd": # like normal resolution of relative, # but absolute paths are still interpreted relative, # so cwd:// and cwd:/// are lead to the same results rest = str((Path(rest.lstrip("/"))).absolute()) elif prot == "": # relative paths are made absolute if not Path(rest).is_absolute(): rest = str((Path(rest)).absolute()) else: raise ValueError(f"Unknown protocol: {prot}") return f"file://{rest}"
6ebe76a1574fe844d808ac4889afe163d9d3131a
48,818
import torch import math def sym_diag(mat): """Diagonal of a symmetric matrix Parameters ---------- mat : (..., M * (M+1) // 2) tensor A symmetric matrix that is stored in a sparse way. Its elements along the last (flat) dimension are the diagonal elements followed by the flattened upper-half elements. E.g., [a00, a11, aa22, a01, a02, a12] Returns ------- diag : (..., M) tensor Main diagonal of the matrix """ mat = torch.as_tensor(mat) nb_prm = int((math.sqrt(1 + 8 * mat.shape[-1]) - 1)//2) return mat[..., :nb_prm]
23c29d1c6429089e88720e9ba7d3d6f8968f9ca0
48,831
def intersect(seq1, seq2): """Returns a list of elements in both seq1 and seq2.""" ret = [] for elem in seq1: if elem in seq2: ret.append(elem) return ret
b7cb43616e8000427005c350b2b07a59768f2995
48,833
def code(value: int) -> str: """Constructs an ANSI code with the provided `value`.""" return f'\033[{value}m'
48b499b5055d616bc7f51043e96429be123b5dd2
48,834
def unwrap_filter(response, category): """ Strips one layer of aggregations (named by <category>) from a ElasticSearch query response, leaving it still in proper ES response format. :param response: An Elasticsearch aggregation response dictionary. :param category: Name of the topmost aggregation in the response. :returns: The same response, with one level of aggregation removed. """ unwrapped = response.copy() unwrapped['aggregations'] = response['aggregations'][category] return unwrapped
82d6533edf8091e5a6b353f903f652bcb700dcde
48,836
def get_longest_consecutive_chars(string): """ Given a string, return the longest consecutive character sequence. """ longest_consecutive_chars = '' current_consecutive_chars = '' for char in string: if char not in current_consecutive_chars: current_consecutive_chars += char else: current_consecutive_chars = char if len(current_consecutive_chars) > len(longest_consecutive_chars): longest_consecutive_chars = current_consecutive_chars return longest_consecutive_chars
4607a1adada254c36e46a28c036cb852992544a5
48,837
import math def root_mean_squared_error(LeadDay,df,model,observed): """ Args: LeadDay: specifically applies to forecast models with lead times if no lead day is available input None LeadDay is desired Lead day (int) df: data frame where Observed and Model data is found model & observed : column name (string) Return: Root Mean Squared Error Function: subtract model values from observed square result and sum all squares divide by number of values """ count = 0 total = 0 if LeadDay is None: for a, j in zip(df[observed], df[model]): diffsquared = ((j) - (a))**2 total += diffsquared count +=1 else: for a, j in zip(df[LeadDay][observed], df[LeadDay][model]): diffsquared = ((j) - (a))**2 total += diffsquared count +=1 avg = total/count return math.sqrt(avg)
0bd5b5627fa2dda1ef444bd12c69f670daa18e44
48,838
def module_file(module): """Return the correct original file name of a module.""" name = module.__file__ return name[:-1] if name.endswith('.pyc') else name
4fbda2b1c839690f880a6f6c1bcba2ca4168a701
48,857
def clamp(value, smallest, largest): """Return `value` if in bounds else returns the exceeded bound""" return max(smallest, min(value, largest))
8ce129fd2bccacf7b45d9b4924f69a54bbb15e3b
48,859
def oid_outside_tree(oid1, oid2): """ Return True if oid2 outside of oid1 tree Used by SNMPSession.walk """ try: if oid2.startswith(oid1): return False return True except: return True
a1957c9d6b04dcd97db321f8d8779c349d14e265
48,867
def calculate_iou(bb1, bb2): """ Calculates the Intersection Over Union (IOU) score of the two bounding-boxes (the overlap between two bounding boxes). each bounding-box coordinates are in the form of: (x_min, y_min, x_max, y_max). """ bb1_x_min, bb1_y_min, bb1_x_max, bb1_y_max = bb1 bb2_x_min, bb2_y_min, bb2_x_max, bb2_y_max = bb2 # get the intersection's coordinate: intersection_x_min = max(bb1_x_min, bb2_x_min) intersection_x_max = min(bb1_x_max, bb2_x_max) intersection_y_min = max(bb1_y_min, bb2_y_min) intersection_y_max = min(bb1_y_max, bb2_y_max) # calculate the intersection's width, height, and area: intersection_w = max(intersection_x_max - intersection_x_min, 0) intersection_h = max(intersection_y_max - intersection_y_min, 0) intersection = intersection_w * intersection_h # calculate the union's area: union = ((bb1_x_max - bb1_x_min) * (bb1_y_max - bb1_y_min) + # bb1 area (bb2_x_max - bb2_x_min) * (bb2_y_max - bb2_y_min) - # bb2 area intersection) # calculate the IOU: iou = intersection / union return iou
5a0379085bbe428e812b2b0a39b39046cc0adefc
48,868
def string_to_seq(seq_str): """Return a codepoint sequence (tuple) given its string representation.""" return tuple([int(s, 16) for s in seq_str.split("_")])
1021578ecb694ec9fc974f0b590ef0fc7c71f20a
48,872
import torch def create_pytorch_model( number_of_features, number_of_categories_by_label, label_to_test, **kwargs ): """ Create a toy PyTorch model that has the right shape for inputs and outputs """ class TorchToy(torch.nn.modules.module.Module): def __init__(self, number_of_features, number_of_categories): super(TorchToy, self).__init__() self.fc1 = torch.nn.Linear(number_of_features, 128) self.relu1 = torch.nn.ReLU() self.fc2 = torch.nn.Linear(128, number_of_categories) def forward(self, x): x = self.fc1(x) x = self.relu1(x) x = self.fc2(x) return x number_of_categories = number_of_categories_by_label[label_to_test] model = TorchToy(number_of_features, number_of_categories) return model
d27a82bd581accb4fccba3c09f88f26b00127eab
48,873
from typing import Counter import collections def numericalize_tok(tokens, max_vocab=50000, min_freq=0, unk_tok="_unk_", pad_tok="_pad_", bos_tok="_bos_", eos_tok="_eos_"): """Takes in text tokens and returns int2tok and tok2int converters Arguments: tokens(list): List of tokens. Can be a list of strings, or a list of lists of strings. max_vocab(int): Number of tokens to return in the vocab (sorted by frequency) min_freq(int): Minimum number of instances a token must be present in order to be preserved. unk_tok(str): Token to use when unknown tokens are encountered in the source text. pad_tok(str): Token to use when padding sequences. """ if isinstance(tokens, str): raise ValueError("Expected to receive a list of tokens. Received a string instead") if isinstance(tokens[0], list): tokens = [p for o in tokens for p in o] freq = Counter(tokens) int2tok = [o for o,c in freq.most_common(max_vocab) if c>min_freq] unk_id = 3 int2tok.insert(0, bos_tok) int2tok.insert(1, pad_tok) int2tok.insert(2, eos_tok) int2tok.insert(unk_id, unk_tok) tok2int = collections.defaultdict(lambda:unk_id, {v:k for k,v in enumerate(int2tok)}) return int2tok, tok2int
48fafe61938203bde66edcab90ded616ed23aa82
48,874
import multiprocessing def get_n_jobs(n_jobs): """get_n_jobs. Determine the number of jobs which are going to run in parallel. This is the same function used by joblib in the PoolManager backend. """ if n_jobs == 0: raise ValueError('n_jobs == 0 in Parallel has no meaning') elif n_jobs is None: return 1 elif n_jobs < 0: n_jobs = max(multiprocessing.cpu_count() + 1 + n_jobs, 1) return n_jobs
53fe32e94c771095bdab2601abba1761548f2d4c
48,875
def extract_position_relations(qdmr_step): """Extract a relation regarding entity positions in a QDMR step. Relevant for VQA data Parameters ---------- qdmr_step : str string of the QDMR step containg relative position knowledge. Either a FILTER of BOOLEAN step. Returns ------- str string of the positional relation. """ if ' left ' in qdmr_step: return 'POS_LEFT_OF' elif ' right ' in qdmr_step: return 'POS_RIGHT_OF' elif (' between ' in qdmr_step) or (' middle of ' in qdmr_step): return 'POS_BETWEEN' elif (' behind ' in qdmr_step) or (' rear of ' in qdmr_step): return 'POS_BEHIND_OF' elif (' in ' in qdmr_step and ' front ' in qdmr_step) or \ (' infront ' in qdmr_step): return 'POS_IN_FRONT_OF' elif ' touch' in qdmr_step: return 'POS_TOUCHING' elif ' reflect' in qdmr_step: return 'POS_REFLECTING' elif (' cover' in qdmr_step) or (' obscur' in qdmr_step) or \ (' blocking' in qdmr_step) or (' blocked' in qdmr_step) or \ (' hidden' in qdmr_step) or (' obstruct' in qdmr_step): return 'POS_COVERS' elif (' near' in qdmr_step) or (' close ' in qdmr_step) or \ (' closer ' in qdmr_step) or (' closest ' in qdmr_step) or \ (' next to ' in qdmr_step) or (' adjacent ' in qdmr_step): return 'POS_NEAR' else: return None return None
ca3ca61ac66419c0fb48ad784a6397a67ba3d653
48,881
def get_module_properties(properties): """ Get dict of properties for output module. Args: properties (list): list of properties Returns: (dict): dict with prop, der and contrib """ module_props = dict(property=None, derivative=None, contributions=None) for prop in properties: if prop.startswith("property"): module_props["property"] = prop elif prop.startswith("derivative"): module_props["derivative"] = prop elif prop.startswith("contributions"): module_props["contributions"] = prop return module_props
8f69335538b738a4a6523e6919b8e5080ab045af
48,885
def to_int_float_or_string(s): """ Convert string to int or float if possible If s is an integer, return int(s) >>> to_int_float_or_string("3") 3 >>> to_int_float_or_string("-7") -7 If s is a float, return float(2) >>> to_int_float_or_string("3.52") 3.52 >>> to_int_float_or_string("-10.0") -10.0 >>> to_int_float_or_string("1.4e7") 14000000.0 Otherwise, just return the string s >>> to_int_float_or_string("A3") 'A3' """ try: s_int = int(s) # int(s) will truncate. If user specified a '.', return a float instead if "." not in s: return s_int except (TypeError, ValueError): pass try: return float(s) except (TypeError, ValueError): return s
18fbc417edb85219f3fbd2ae8e5eb8aa4df61d87
48,889
def get_urs_pass_user(netrc_file): """ retrieve the urs password and username from a .netrc file :param netrc_file: this is a path to a file that contains the urs username and password in the .netrc format :return: [tuple] (user_name, password) """ with open(netrc_file, 'r') as f: text = f.read() words = text.split() # find urs.earthdata.nasa.gov url = 'urs.earthdata.nasa.gov' url_loc = words.index(url) user_name_loc = words[url_loc:].index('login') + 2 user_name = words[user_name_loc] pword_loc = words[url_loc:].index('password') + 2 pword = words[pword_loc] return user_name, pword
a72938a04c5d0b50608446d87bbbd819cd9c9607
48,890
def merge_left(b): """ Merge the board left Args: b (list) two dimensional board to merge Returns: list """ def merge(row, acc): """ Recursive helper for merge_left. If we're finished with the list, nothing to do; return the accumulator. Otherwise, if we have more than one element, combine results of first from the left with right if they match. If there's only one element, no merge exists and we can just add it to the accumulator. Args: row (list) row in b we're trying to merge acc (list) current working merged row Returns: list """ if not row: return acc x = row[0] if len(row) == 1: return acc + [x] return merge(row[2:], acc + [2*x]) if x == row[1] else merge(row[1:], acc + [x]) board = [] for row in b: merged = merge([x for x in row if x != 0], []) merged = merged + [0]*(len(row)-len(merged)) board.append(merged) return board
96af9931dffee9193c565efbe89b463e93921151
48,892
import typing def filesDiffer(a:typing.List[str], b:typing.List[str]) -> bool: """ Compares two files for meaningingful differences. Traffic Ops Headers are stripped out of the file contents before comparison. Trailing whitespace is ignored :param a: The contents of the first file, as a list of its lines :param b: The contents of the second file, as a list of its lines :returns: :const:`True` if the files have any differences, :const:`False` """ a = [l.rstrip() for l in a if l.rstrip() and not l.startswith("# DO NOT EDIT") and\ not l.startswith("# TRAFFIC OPS NOTE:")] b = [l.rstrip() for l in b if l.rstrip() and not l.startswith("# DO NOT EDIT") and\ not l.startswith("# TRAFFIC OPS NOTE:")] if len(a) != len(b): return True for i, l in enumerate(a): if l != b[i]: return True return False
41f01627e0b51841a116f65c1cc3fc2fed14e91d
48,895
def multiply_1(factor: int): """ Example where input argument has specified variable annotation. This example is showing how to cast variable. And assert in order to check for any error at the early stage. :param factor: :return: results: int """ # This will print a data type of this variable e.g. int, float, string. print(type(factor)) # Casting variable into another data type (Casting is when you convert a variable value from one type to another.) factor_var = int(factor) # Check if data type is what we expect to be. assert type(factor_var) == int # Return function can return a single variable as well as execute function. # Return causes the function to stop executing and hand a value back to whatever called it.return causes the # function to stop executing and hand a value back to whatever called it." return int(factor_var * 23.233223)
5bbd5ec6c7636775855a9e3c63a1ee30d6eabb95
48,896
def get_util_shape(row): """Get utility term shape based on ROI. Parameters ---------- row : pandas.core.series.Series Row of func_df DataFrame. Returns ------- str If 'chest' or 'rib in row['Roi'], then return 'linear'. Otherwise, return 'linear_quadratic'. """ if any([roi in row['Roi'].lower() for roi in ['chest', 'rib']]): return 'linear' return 'linear_quadratic'
4ebb50dd0991f3edda7f33ad17fb3a3dfaf39de3
48,897
from typing import Optional from typing import Match import re def _replace_html_saving_export_path_by_doc_path(code: str) -> str: """ Replace html saving interace's export path argument value in the code by document path. Parameters ---------- code : str Target Python code. Returns ------- code : str Replaced code. html saving interface argument, for example, `save_overall_html` `dest_dir_path` will be replaced by './docs_src/_static/<original_path>/'. """ match: Optional[Match] = re.search( pattern=( r"save_overall_html\(.*?dest_dir_path='(.+?)'\)" ), string=code, flags=re.MULTILINE | re.DOTALL) if match is None: return code original_path: str = match.group(1) while original_path.startswith('.'): original_path = original_path.replace('.', '', 1) if original_path.startswith('/'): original_path = original_path.replace('/', '', 1) if not original_path.endswith('/'): original_path += '/' code = re.sub( pattern=( r"(save_overall_html\(.*?dest_dir_path=).+?\)" ), repl=rf"\1'./docs_src/source/_static/{original_path}')", string=code, count=1, flags=re.MULTILINE | re.DOTALL) return code
0bfcfdd234ae72c70feafb1efd9799387b75c8f1
48,900
from typing import List def body_25_to_coco_18(keypoints: List[float]) -> List[float]: """ noqa BODY_25 to COCO_18 key mapping based on the following: https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/output.md The only difference is that COCO_18 doesn't have the MidHip (#8), Toes, Heels and Background (#19-#25) keypoints. """ return keypoints[:8 * 3] + keypoints[9 * 3:19 * 3]
6945a1057e94fbe306810e6b1aa3f7a5dd1ad6df
48,901
def factory_register(SuperClass, ClassName): """Register an concrete class to a factory Class.""" def decorator(Class): # return Class if not hasattr(SuperClass, "_factory"): setattr(SuperClass, "_factory", {}) SuperClass._factory[ClassName] = Class setattr(Class, "_factory_type", ClassName) return Class return decorator
891fd2419fbb545507f3fe79ad1ad27e28cdf2d0
48,903
def _type_error(actual, expected): """Returns a ValueError that the actual type is not the expected type.""" msg = 'invalid type: %s is not in %s' % (actual.__name__, [t.__name__ for t in expected]) return ValueError(msg)
fc9b09c6bd684a1132ca7c0a792aca9da37be2e9
48,906
def extract_callback_args(args, kwargs, name, type_): """Extract arguments for callback from a name and type""" parameters = kwargs.get(name, []) if parameters: if not isinstance(parameters, (list, tuple)): # accept a single item, not wrapped in a list, for any of the # categories as a named arg (even though previously only output # could be given unwrapped) return [parameters] else: while args and isinstance(args[0], type_): parameters.append(args.pop(0)) return parameters
9ed14a40dee7799d49f0001818c20e9e2935c69b
48,908
def truncate_line(line: str, length: int = 80) -> str: """Truncates a line to a given length, replacing the remainder with ...""" return (line if len(line) <= length else line[: length - 3] + "...").replace("\n", "")
1bc7e34b85afc59ff5afcfa9a57b575aa3d032fe
48,909
def track_point(start, direction, z): """ This function returns the segment coordinates for a point along the `z` coordinate Args: start (tuple): start coordinates direction (tuple): direction coordinates z (float): `z` coordinate corresponding to the `x`, `y` coordinates Returns: tuple: the (x,y) pair of coordinates for the segment at `z` """ l = (z - start[2]) / direction[2] xl = start[0] + l * direction[0] yl = start[1] + l * direction[1] return xl, yl
72313aa592d8014641d8533acbe40661142df1c0
48,912
def mod(n, size): """Returns the position of a cell based on modulo arithmetic""" size -= 1 if n < 0: return size elif n > size: return 0 return n
d035bb05f5553671ac35abfcfdc1d9914482721d
48,913
import json def _load_query(query_file: str) -> str: """ Load the advanced query from a json file. :param query_file: path to the json file. :return: advanced query in json string format (single line). """ with open(query_file, 'r', encoding='utf-8') as file_pointer: query = json.load(file_pointer) # return single line json string return json.dumps(query)
eebc23785499010b780c1a671ef12fad12fe3c37
48,918
def create_scatter_legend(axi, color_labels, class_names, show=False, **kwargs): """Generate a legend for a scatter plot with class labels. Parameters ---------- axi : object like :class:`matplotlib.axes.Axes` The axes we will add the legend for. color_labels : dict of objects like :class:`numpy.ndarray` Colors for the different classes. color_names : dict of strings Names for the classes. show : boolean, optional If True, we will add the legend here. kwargs : dict, optional Additional arguments passed to the scatter method. Used here to get a consistent styling. Returns ------- patches : list of objects like :class:`matplotlib.artist.Artist` The items we will create a legend for. labels : list of strings The labels for the legend. """ patches, labels = [], [] for key, val in color_labels.items(): patches.append( axi.scatter([], [], color=val, **kwargs) ) if class_names is not None: label = class_names.get(key, key) else: label = key labels.append(label) if show: axi.legend(patches, labels, ncol=1) return patches, labels
3e7551f5b9f3b7f74181aa75adfe092d5389ddbb
48,919
def is_float(potential_float: str) -> bool: """ Check if potential_float is a valid float. Returns ------- is_float : bool Examples -------- >>> is_float('123') True >>> is_float('1234567890123456789') True >>> is_float('0') True >>> is_float('-123') True >>> is_float('123.45') True >>> is_float('a') False >>> is_float('0x8') False """ try: float(potential_float) return True except ValueError: return False
19d907f3cba743f3b6a9867c7c29ad505f6a26e4
48,923
def styblinski_tang(ind): """Styblinski-Tang function defined as: $$ f(x) = 1/2 \sum_{i=1}^{n} x_i^4 - 16 x_i^2 + 5 x_i $$ with a search domain of $-5 < x_i < 5, 1 \leq i \leq n$. """ return sum(((x ** 4.) - 16. * (x ** 2.) + 5. * x for x in ind)) / 2.,
9e060448b02558e33e7b6b2aa74ce1a2806f3c0b
48,925
def clean_path(path): """ remove index.html from end of a path, add / if not at beginning """ path = path.split("index.html")[0] if not path.startswith("/"): path = "/" + path if not path.endswith("/"): path += "/" return path
55360f0e0729b9cb0510308f5e5be32a404f1e70
48,930
import re def _extract_subcats(pattern, categs): """Extract the category names matching `pattern`.""" return {cat for cat in categs if re.match(pattern, cat)}
1092e247b2fdd3290759ceedb309691ef640058b
48,934
def my_key(t): """ Customize your sorting logic using this function. The parameter to this function is a tuple. Comment/uncomment the return statements to test different logics. """ # return t[1] # sort by artist names of the songs return t[1], t[0] # sort by artist names, then by the songs # return len(t[0]) # sort by length of the songs # return t[0][-1] # sort by last character of the songs
ae416506de1820290d97d558ff899ba930d68705
48,937
def parse_query(query_to_parse): """ Converts a comma or space-separated string of query terms into a list to use as filters. The use of positional arguments on the CLI provides lists (which we join and resplit to avoid any formatting issues), while strings passed from pssh.py just get split since those should never come over as a list. """ if isinstance(query_to_parse, list): _query = ','.join(query_to_parse) else: _query = query_to_parse.replace(' ',',') split_query = _query.split(',') ### Pick up passed --region query from pssh.py parsed_query = [x for x in split_query if not x.startswith('--region=')] region_query = [x for x in split_query if x.startswith('--region')] parsed_regions = ','.join([x.split('=')[1] for x in region_query]) return parsed_query, parsed_regions
edd1cb6b42cd895a2eeb5f4f024dc1f2c92743af
48,941
def str_has_one_word(search_str): """ Test if string which has a substring in quotes, that has wildcards. >>> str_has_one_word(r"test* 12?") False >>> str_has_one_word(r"test**") True """ if len(search_str.split()) == 1: # has more than 1 word return True else: return False
203d6468d01b17216ffdc89dcf6e40d44b8a3b77
48,942
from typing import Union def tab(text:Union[list, str], pad=" ") -> Union[list, str]: """Adds a tab before each line. str in, str out. List in, list out""" if isinstance(text, str): return "\n".join([pad + line for line in text.split("\n")]) else: return [pad + line for line in text]
bc6e20dfa9ed51b0e8058020feafe92cd1bdcbe8
48,946
def is_final_id(id_path, pda, acceptance): """Helper for final_id --- If the id of id_path meets the acceptance criterion that is passed in, then it is "final"; else not. """ (id, path) = id_path (q, inp_str, stk_str) = id if (acceptance == "ACCEPT_F"): return (inp_str=="" and q in pda["F"]) else: assert(acceptance == "ACCEPT_S") return (inp_str=="" and stk_str=="")
8b93568a61f0470813a237f6cde17ff15f701f9d
48,948
import re def find_text(text): """ Find string inside double quotes """ matches = re.findall(r'\"(.+?)\"', text) return matches[0]
55238d27db4c3a8b682e4616b253d63db1af38fd
48,949
def user_exist(username): """ 判断用户是否存在 :param username: 用户名 :return: True or False 用户是否存在 """ with open("db", "r", encoding="utf-8") as f: for line in f: result = line.strip().split("@") # 判断是否是存在该用户 if username == result[0]: return True else: # 不存在则返回False return False
0040f75562103397f7d5ad9e0e4d3ba3e2d7b11b
48,957
def iou(box1, box2): """ Calculate intersection over union between two boxes """ x_min_1, y_min_1, width_1, height_1 = box1 x_min_2, y_min_2, width_2, height_2 = box2 assert width_1 * height_1 > 0 assert width_2 * height_2 > 0 x_max_1, y_max_1 = x_min_1 + width_1, y_min_1 + height_1 x_max_2, y_max_2 = x_min_2 + width_2, y_min_2 + height_2 area1, area2 = width_1 * height_1, width_2 * height_2 x_min_max, x_max_min = max([x_min_1, x_min_2]), min([x_max_1, x_max_2]) y_min_max, y_max_min = max([y_min_1, y_min_2]), min([y_max_1, y_max_2]) if x_max_min <= x_min_max or y_max_min <= y_min_max: return 0 else: intersect = (x_max_min-x_min_max) * (y_max_min-y_min_max) union = area1 + area2 - intersect return intersect / union
4de8ce8314c1833d56fcd81a254f65d2d8a02df9
48,959
import torch def extract_tensors(from_this): """ Given a dict from_this, returns two dicts, one containing all of the key/value pairs corresponding to tensors in from_this, and the other containing the remaining pairs. """ tensor_dict = {k:v for k, v in from_this.items() if type(v) is torch.Tensor} other_keys = from_this.keys() - tensor_dict.keys() if tensor_dict else from_this.keys() other_dict = {k: from_this[k] for k in other_keys} return tensor_dict, other_dict
d557ab786e6af935a1b6f093d2257e32dae2357c
48,960
from datetime import datetime def Date(year, month, day): """Construct an object holding a date value.""" return datetime(year, month, day)
1994d9f8720bf19c9b7493ec2164bc9e74d1a72a
48,961
import six import re def isidentifier(s): """ Check whether the given string can be used as a Python identifier. """ if six.PY2: return re.match("[_A-Za-z][_a-zA-Z0-9]*$", s) return s.isidentifier()
7769d6b93cd2a49bbd104558c354c60d8d27530d
48,962
def L_shaped_context(image, y, x): """This grabs the L-shaped context around a given pixel. Out-of-bounds values are set to 0xFFFFFFFF.""" context = [0xFFFFFFFF] * 4 if x > 0: context[3] = image[y][x - 1] if y > 0: context[2] = image[y - 1][x] context[1] = image[y - 1][x - 1] if x > 0 else 0 context[0] = image[y - 1][x + 1] if x < image.shape[1] - 1 else 0 # The most important context symbol, 'left', comes last. return context
84a7a298b43ffddf697986f2f9af6402990b832c
48,963
def wrap_fn(newname: str, doc: str): """ Decorator which renames a function. Parameters ---------- newname: str Name of the new function. doc: str Docstring of the new function. """ def decorator(f): f.__name__ = newname f.__doc__ = doc return f return decorator
248999597b06665d52246656cb8ee8f3322b4338
48,967
def hsl_to_hsv(h :float, s :float, l :float) -> tuple: """ HSL to HSV color conversion. https://en.wikipedia.org/wiki/HSL_and_HSV#Interconversion Args: h: `float` in [0.0, 1.0] corresponding to hue. s: `float` in [0.0, 1.0] corresponding to saturation. l: `float` in [0.0, 1.0] corresponding to light. Returns: The corresponding HSv normalized tuple. """ v = l + s * min(l, 1 - l) s = 0 if v == 0 else 2 * (1 - l/v) return (h, s, v)
77b7613f276cac51bf5f851e175fa42790084036
48,968
def rescale(value, in_min, in_max, out_min, out_max): """ Maps an input value in a given range (in_min, in_max) to an output range (out_min, out_max) and returns it as float. usage: >>> rescale(20, 10, 30, 0, 100) <<< 50.0 """ in_range = in_max - in_min out_range = out_max - out_min return (value - in_min) * (out_range / in_range) + out_min
69444386da45b2747cea3b304bba0f2fcc4a8978
48,969
def get_bbox_from_gt(gt): """ Get bounding box from ground truth image """ return gt.convert('RGB').getbbox()
d7b7bcf9c5963393c04ae6f355981fdecae72088
48,973
def titlecase_keys(d): """ Takes a dict with keys of type str and returns a new dict with all keys titlecased. """ return {k.title(): v for k, v in d.items()}
8c5d2cbdc8bc28e384798c3e5b0f096068926945
48,979
def printable_device(device): """Returns a printable form of a device record.""" if device is None: return "<device NULL>" output_list = [] assert device.StartSize + len(device.DeltaValue) - 1 == device.EndSize for index in range(len(device.DeltaValue)): output_list.append( "%d %d" % (device.StartSize + index, device.DeltaValue[index]) ) return "<device %s>" % (", ".join(output_list))
2b3bdea992402188687e7270fca47bf612d76e13
48,983
def parse_date(date): """Parse date int string into to date int (no-op).""" if date is None: return 0 return int(date)
46cba9bcc9a0ba90028579994df4e92b9165a1b8
48,984
import math def giantstep_babyStep(m, c, n, phi, group) : """ With c = m^e % n given m, c, n, 𝜙(𝑛), and the target group This function will find out e % group in time O(√N). Give : @m : plaintxt data @c : cipher data @n : module @phi : 𝜙(𝑛) @group : A factor in phi Return : @e : what exponent this m is taken in group field. """ # Raising to subgroup assert phi % group == 0, f"This phi didn't make {group} group" e = phi // group sqf = math.ceil(math.sqrt(group)) gf = pow(m, e, n) gsqf = pow(gf, sqf, n) table = {} # Giant step ygna = pow(c, e, n) for a in range(sqf): table[ygna] = a ygna = (ygna * gsqf) % n # Baby step gb = 1 for b in range(sqf): if gb in table : a = table[gb] ki = (b-a*sqf) % group return ki gb = (gb*gf)%n
9afaeef7ad647d8c1cd3bfeac01711642282f7f7
48,985
async def root(): """ Simple welcome message for GETs to the root, directing to the documentation. """ return {"message": "Welcome! Check out the interactive documentation at /docs"}
08482501d5a5a45bdcf53b52be1929d431f9c9c7
48,989
def isRetrovirus(lineage): """ Determine whether a lineage corresponds to a retrovirus. @param lineage: An iterable of C{LineageElement} instances. @return: C{True} if the lineage corresponds to a retrovirus, C{False} otherwise. """ for element in lineage: if element.rank == 'family' and element.name == 'Retroviridae': return True return False
e4f0aa37a673e9640ca6c6ed0c76d993d6eefb82
48,990
def compute_transitions(bands,in_list,fin_list): """ Compute the (positive) transition energies for the bands (on a single kpoint). The `fast` index is associated to the bands in the fin_list list. Args: bands (list) : list with the energies in_list (list) : indexes of the bands used as starting points of the transitions fin_list (list) : indexes of the bands used as final points of the transitions Returns: :py:class:`list` : list with the transition energies for each possible couple of (distinct) in and out bands """ transitions = [] for v in in_list: for c in fin_list: if c > v: transitions.append(bands[c]-bands[v]) return transitions
09bc38199f7f36aa80cc7834e13f3e5f55546099
48,997
def contains(first, second): """Returns True if any item in `first` matches an item in `second`.""" return any(i in first for i in second)
0157fd1c9ad3e48f9a6e9aef39e58240dbcb64e8
48,998
def _uprank(a): """Get `a` as a rank-two tensor, correctly handling the case where `a` is rank one. Args: a (tensor): Tensor to get as a rank-two tensor. Returns: tensor: `a` as a rank-two vector. """ if a.ndim == 1: return a[:, None] else: return a
f2aa483234d4dbe98989984eb28b3011ad7a4194
49,002
def unflat_len(obj): """Return number of non-list/tuple elements in obj.""" if not isinstance(obj, (list, tuple)): return 1 else: return sum([unflat_len(x) for x in obj])
d11c1c05b3f80f166781006ad573176dbf4752db
49,003
def _scale(dimen: str, scale: float = 1) -> int | str: """Get a scaled dimen. Args: dimen (str): dimension in px scale (float): scale Returns: Optional[int, str]: scaled dimen (min=1) """ if scale == 1: return dimen return max(int(int(dimen) * scale), 1)
450a969f658f5768b1e3988859c4f20ff6b2dfd3
49,005
from typing import List def scale_prev(prev_vals: List[float], fraction: float) -> float: """ Apply a multiplier to the previous value. """ return prev_vals[-1] * fraction
9685214aaece3a6935886cbf91472e877f7e3619
49,008
def convert (hour): """ converts Hours in to seconds (hours * 3600) Args: hours(int) return: (int value) number of seconds in hours """ seconds = 3600 result = hour * seconds return result
1c7d06da2582c0c580ed48ddc18f142727001fa8
49,011
def _r_count_num_m(n, factors_d, i): """Count of numbers coprime to d less than end; sum( gcd(m, d) == 1 for m in range(n, n+i) ) Uses inclusion exclusion on prime factorization of d """ if n == 0: return 0 if i < 0: return n return _r_count_num_m(n, factors_d, i-1) - _r_count_num_m(n // factors_d[i], factors_d, i-1)
2d5eacf6d1df2d4277bd9abd760bc132a09452d8
49,013
def NormalizeLineEndings(s): """Convert string containing various line endings like \n, \r or \r\n, to uniform \n.""" return '\n'.join(s.splitlines())
8dc5c3cf579427fe402ee84cc15b73ccc2bbe88d
49,014