content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def rn_sub(a, b): """ a - b uses rn_sum and rn_neg to get the difference like a + (-b) :param a: RN object :param b: RN object :return: difference array """ return a + (-b)
483bdcaab4121139f967057082c362e89409093a
680,363
def scale_features(X, approach='standard'): """Scale feature matrix. Parameters ---------- X : torch.Tensor Tensor of shape (n_samples, n_channels, lookback, n_assets). Unscaled approach : str, {'standard', 'percent'} How to scale features. Returns ------- X_scaled : t...
c7e73e5789f9418f5215298da0cee9301e8a0447
126,726
def isFloat(string): """ is the given string a float? """ try: float(string) except ValueError: return 0 else: return 1
4605d2975523dab25ec598ee7ed0324c0c200b05
677,567
import time def time_strptime(*args, **kwargs): """Version of time.strptime that always uses the C locale. This is because date strings are used internally in the database, and should not be localized. """ return time.strptime(*args, **kwargs)
5410a4b4154471834f70818bf2a0a2356bdc25dd
29,135
def parse_filesize(filesize): """ Parse a human readable filesize string into a integer. Only the suffixes 'k' and 'M' are supported. """ try: if filesize.endswith('k'): return int(filesize[:-1]) * 1024 if filesize.endswith('M'): return int(filesize[:-1]) * 1048576 ...
9d3a496f07131d0f76fa66d3b5831b7b75555d2d
269,988
def normalize(img): """ Normalize an image array. Assume the image is stored as an array or matrix of uint8. Since the max value of uint8 is 255 we use 128 (255 / 2) as the constant in the formula below. Args: img: input image Returns: Normalized image """ normaliz...
116519372cb6d083fab056fcb635266fecd1c67d
137,904
def cmd_limits(targ): """ CMD limits for plotting. zoom1_kw is the top right axis, HB zoom2_kw is the bottom right axis, MSTO xlim, ylim is the main axis. (ylim order doesn't matter, xlim order does) """ kw = {'HODGE2': {'xlim': [0., 1.99], 'ylim': [26, 18.5], ...
49e37305720aa438f2e62f061d315e2779c3b5fe
323,991
def train_test_split(filepaths_and_text, train_size): """ Split dataset into train & test data Parameters ---------- filepaths_and_text : list List of samples train_size : float Percentage of entries to use for training (rest used for testing) Returns ------- (list,...
5f7007c6c2e46b4863a00369618096918e2dfd24
209,255
def compute_specificity(cm): """ Computes specificity for binary classification problems :param cm: A Numpy-like matrix that represents a confusion matrix :return: The specificity of the confusion matrix """ print(cm.shape) print(len(cm.shape)) assert len(cm.shape) and cm.shape[0] == cm....
4815d74db80be0b953dade3692092634ff7c9b7b
118,602
import time def time_helper(seperator = '_', to_sec = False): """ return a string like 2020_09_11_22_43_00 (if to_sec is True) or 2020_09_11_22_43 (if to_sec is False) """ localtime = time.asctime(time.localtime(time.time())) if to_sec: return time.strftime("%Y" + seperator + "%m" + sepera...
eac8b63681fe6ea666aebf5963ed443667421592
563,342
def sanitize_str(string): """ Sanitize string to uppercase alpha only """ return filter(str.isalpha, string.upper())
e693d61f19ab56103395a798c930a1b9937eafd5
693,547
def sort_batch_contributions(contributions): """Returns the list of contributions sorted by creation date (old -> young) and score (high -> low). """ by_creation = sorted(contributions, key=lambda x: x["created"]) by_score = sorted(by_creation, key=lambda x: x["score"], reverse=True) return by_...
d9cc0125813c158175e58198b64521db613a8e55
510,223
from typing import List def serial_order_to_spatial(hole_sequence: List[int], seq_positions: List[int]) -> List[int]: """ Converts a first-phase hole sequence and a list of serial order positions (at the choice phase) into a list of spatial holes at test. Args: hol...
23a8c158ba0821ea2960091d4b9fa8974f368249
620,919
def _get_date_from_filename(filename): """ Returns date (first part of filename) """ return filename.split("/")[-1].split("_")[0]
9dd84ef278fbbe48a421a5b708bb09200ef93912
661,496
import torch def unbatch(d, ignore=[]): """ Convert a dict of batched tensors to a list of tensors per entry. Ignore any keys in the list. """ ignore = set(ignore) to_unbatch = {} for k, v in d.items(): # Skip ignored keys. if k in ignore: continue if i...
e550883d2260fe6f4794ca28b67c3b16d938c9e2
308,386
def setdefaults(dct, defaults): """Given a target dct and a dict of {key:default value} pairs, calls setdefault for all of those pairs.""" for key in defaults: dct.setdefault(key, defaults[key]) return dct
fe6c9f2253757369dc12cd8fff087b114f0805b7
276,189
def parse_im_name(im_name, parse_type='id'): """Get the person id or cam from an image name.""" assert parse_type in ('id', 'cam') if parse_type == 'id': parsed = int(im_name[:8]) else: parsed = int(im_name[9:13]) return parsed
9b05fc76aa689bda9e0f482bfed6ce2c281d9bbc
596,563
import json def get_credentials(credentials_path="credentials.json"): """Access database credentials from JSON file Parameters ---------- credentials_path : str Location of the credentials JSON file Returns ------- credentials : dict Dictionary containing the database con...
9d5c06da334b90691985ab26cf071648600d210f
71,636
def filter_dictionary(dictionary, field_list): """ Takes dictionary and list of elements and returns dictionary with just elements specified. Also decodes the items to unicode :param dictionary: the dictionary to filter :param field_list: list containing keys to keep :return: dictionary with ju...
40b93742fc04e498865939665363e97cd8ee67b5
455,576
def get_tile_type(index_i, index_j, tile_arrangement): """ Gets the tile type at (`index_i`, `index_j`). Args: index_i (int): Row index. index_j (int): Column index. tile_arrangement (List[List[str]]): Arrangement of the tiles as a 2D grid. R...
025f4524067cce2d99d95ba1e5a131749475c089
392,012
from typing import OrderedDict def make_offset_dict(strand): """ Helper function for calculating offsets at which chains fall into in a model :param strand: Model to calculate offsets from, OrderedDict with chain names as keys :return: Dictionary of offsets """ offset_dict = OrderedDict.fromk...
8222644ee6bfb28980ac05530cef557439f46532
169,017
def int_or_float(x): """Return `x` as `int` if possible, or as `float` otherwise.""" x = float(x) if x.is_integer(): return int(x) return x
eacef4f2f88351f0d0a8832afcbebb12be305b26
679,662
import re import string def remove_special_chars(text: str) -> str: """ Removes all special characters from a string. """ chars = re.escape(string.punctuation) return re.sub(r"[" + chars + "]", "", text)
f73b047ef47ff965aadce56437dd6882c66e07fd
140,461
def strings_similarity(str1, str2, winkler=True, scaling=0.1): """ Find the Jaro-Winkler distance of 2 strings. https://en.wikipedia.org/wiki/Jaro-Winkler_distance :param winkler: add winkler adjustment to the Jaro distance :param scaling: constant scaling factor for how much the score is adjusted ...
a4f7a41d5869a1139409ac3dce21ae49b2d3f9d2
392,255
import re def rm_brackets(text: str) -> str: """ Remove all empty brackets and artifacts within brackets from `text`. :param str text: text to remove useless brackets :return: text where all useless brackets are removed :rtype: str :Example: >>> rm_brackets("hey...
3310e3cc0867f65bc680d6144f82813b469e2c6a
440,239
def integrate(i, dx): """Takes a list of values, i. i is split into n equal intervals of length dx, and contains the values of an arbitrary function at these points. With this data, this function will approximate the integral of the function using the trapezoidal rule.""" n = len(i) sum = i[0]+i[n-1] for k in ra...
6e276f6c8d753c26e96128f5a82cfb512cd84195
286,878
from typing import Tuple def parse_pr_url(url: str) -> Tuple[str, int]: """Parse the given pull request URL and return its information. :param str url: the PR URL from Github, formatted as: https://api.github.com/repos/<account>/<repo>/pulls/<pr_number> :return: the PR information as (full_repo_n...
9ac519e6ba1abcd9a3756e33a8a64669222b397c
602,153
def readme(root_path): """Returns the text content of the README.rst of the package Parameters ---------- root_path : pathlib.Path path to the root of the package """ with root_path.joinpath('README.rst').open(encoding='UTF-8') as f: return f.read()
4c1fca9ea070e4902b626abc4a751ae13893fa41
484,655
def is_in_t(pt): """Checks if a point is in the template triangle T. :param pt: The point to be checked. :type pt: tuple(float,float). :returns: True if pt is in T. :rtype: bool. """ flag = True if pt[0] < 0 or pt[1] < 0: flag = False if pt[0] + pt[1] > 1: ...
94f1f6baeed3a56d5f28f8cd3ad98a4e51cfdd21
223,730
from datetime import datetime def convert_to_date(transaction_date: str): """Convert the date-time string(dd/mm/yyyy hh:min_) to date time object""" if type(transaction_date) == str: date_, time = transaction_date.split() dd, mm, yyyy = [int(val) for val in date_.split("/")] hh, min_ =...
1f597c20eced07386bd2e936ac95a9d0d110f86d
461,054
def path2ParentPath(path): """ >>> path2ParentPath('/xxx/yyy/zzz/') '/xxx/yyy/zzz' >>> path2ParentPath('/xxx/yyy/zzz') '/xxx/yyy' >>> path2ParentPath('/xxx/yyy/zzz.gif') '/xxx/yyy' """ return '/'.join(path.split('/')[:-1])
cad66ccb11c8d7b7c9ae9117743a8bdd5c39e247
327,973
def logical_xor(a, b, unsafe=False): """logical xor without the bloat of numpy.logical_xor could be substituted with numpy.logical_xor !important: if unsafe is set to True, a and b are not checked. This improves speed but is risky. expects integers [0,1] or bools """ if not unsafe: ...
bc1981e81412f29fd91b1f5d57405a3d92ac4fa3
629,064
def to_index(char): """ Converts char to class index :param char: 0-9 =, a-z, A-Z :return: corresponding class index """ if ord(char) < 59: return ord(char) - 48 elif ord(char) < 95: return ord(char) - 55 else: return ord(char) - 61
62a5fdb9a164d745dfe813db85d3616f8e306703
307,975
def _discard_newlines(parm: str, start: int) -> int: """Discard any newline characters. :param parm: The parameter data. :param start: The start index. :return: The start index offset to discard any newlines """ pos = start while pos < len(parm): if parm[pos] not in ("\r", "\n"): ...
658adf55186376380de2ece36d06a97b2711dee6
510,140
def scheme_false(val): """Only False is false in Scheme.""" return val is False
aa9c77c53d22b17d925b09a88846ea67ad3107ae
578,401
from functools import reduce def get_value_or(dictionary, x_path, default=None): """ Try to retrieve a value from a dictionary. Return the default if no such value is found. """ keys = x_path.split("/") return reduce( lambda d, key: d.get(key, default) if isinstance(d, dict) else d...
9679fa8ea18473728348b6213b1d36145e01488a
448,037
def crop_other_columns(table, required_columns): """This function removes the columns that are not in required_columns list This would help getting rid of columns that are not to be displayed. Args: table: Type-pandas.dataframe required_columns: Type-list of str Returns: Retu...
05e80172a159e51303c58ba70a684875902e1451
505,965
def makes_false(operator, fact): """Returns true iff 'operator' makes 'fact' false""" return fact in operator.del_effects
3f23569945c3370f6cbed92f905dcb38cf72f297
300,527
def extract_total_individuals_and_the_ones_within_target_for_both_classes( individuals, target ): """ Extract the total number of individuals that pass through the model and the total number of individuals that exit the model within the given target. Parameters ---------- individuals : list...
e3ed2a5be7f28ad9aec90cd337c68e8f04867b7e
219,979
import torch def draw_shape(pos, sigma_x, sigma_y, angle, size): """ draw (batched) gaussian with sigma_x, sigma_y on 2d grid Args: pos: torch.tensor (float) with shape (2) specifying center of gaussian blob (x: row, y:column) sigma_x: torch.tensor (float scalar), scaling parameter along ...
4fe11c527ca12f8890c86138021b3cc4eedf8311
334,283
def post_process_response(token_ids, reader, merge=True): """Post-process the decoded sequence. Truncate from the first <eos> and remove the <bos> and <eos> tokens. Convert token_ids to words(merge=True) or tokens(merge=False) Args: token_ids: Token id sequence. merge: If true, merge s...
669ca779442a66a23fb10c053fd1c8c62bd519a6
637,038
import time import calendar def to_timestamp(dt): """ Converts a datetime object to a timestamp (seconds since epoch). :param dt: datetime object (naive or aware) :returns: timestamp (seconds since epoch) Native datetime objects will be treated as local time. .. note:: Epoch is defin...
49babc122876c32230df7e9e211500ef3d0dafe4
518,775
def _deduplicate_and_remove_empty_options(zipped): """Remove option-bitmap pairs where option is duplicate or empty. Args: zipped: list of tuples [(option, bitmap), ...]. Returns: `zipped` without such elements where `option` is duplicate in the list or is empty. """ stored_options = set() zip...
277a791c574ab5512aec24323480d514297689cf
84,713
def skymapweights_keys(self): """ Return the list of string names of valid weight attributes. For unpolarized weights, this list includes only TT. Otherwise, the list includes all six unique weight attributes in row major order: TT, TQ, TU, QQ, QU, UU. """ if self.polarized: return ['T...
f7e69f39abfbb35bd12b44a838ce76f3145cdfe7
686,834
def _flag_awakenings(hypno, thresh): """ Mark awakenings as Long or Short depending on threshold in minutes Parameters ---------- hypno : pd.DataFrame Hypnogram dataframe obtained through _read_hypno(). thresh : int or float, positive non-zero Minimum duration in minutes for awa...
a270665b50140117c0651b3bf3d8bbbb18725c00
90,691
import torch def get_rays_shapenet(hwf, poses): """ shapenet camera intrinsics are defined by H, W and focal. this function can handle multiple camera poses at a time. Args: hwf (3,): H, W, focal poses (N, 4, 4): pose for N number of images Returns: rays_o (N, H, W...
2e3c25b819753e8e482da49bb33c4d4247a0284a
633,071
def is_smth_near(profile, v1, rng=2): """ Return index of something near if something exists near the target position. Else return None. :param profile: list(int) - profile :param v1: int - target place :param rng: int - how far to search from target :return: int/None - either a place where we h...
c9f4e4087eca2c893e597f95fccabec7b383149d
554,740
def fetch_method(name, modules): """ Get function from list of modules. """ for module in modules: if hasattr(module, name): return getattr(module, name) raise ValueError('Cannot find method ' + name + ' in ' + ', '.join([module.__name__ for module in modules]))
8376655e59115bc5d95a0fb32ba54edb52e69188
556,643
import math def get_number_format(number_of_pages) -> str: """ Get the correct number formatting for pdftoppm's output numbering. E.g. a file with 10-99 pages will have output images named '01.png, 02.png, 03.png'; a file with 100-999 pages will output '001.png, 002.png, 003.png'. We need to use the s...
db8f3c205e9763566e20c6ae57fbd34cfc04d42f
692,167
import random def optimize_order(package_archives): """ Shuffle a list of package archives in random order. Usually when scanning a large group of package archives, it really doesn't matter in which order we scan them. However the progress reported using :class:`~humanfriendly.terminal.spinners.S...
754a132d063721457d7f523788c8a532a799124c
545,267
def get_bibtex(model_identifier): """ A method returning the bibtex reference of the requested model as a string. """ return """ @article{https://doi.org/10.48550/arxiv.2203.12601, doi = {10.48550/ARXIV.2203.12601}, url = {https://arxiv.org/abs/2203.12601}, author = {Nair, Suraj an...
bb3d4411cdca9dad09f40d19c779f5f87eb7e268
218,970
def DeserializeAttributesFromJsonDict(json_dict, instance, attributes): """Sets a list of |attributes| in |instance| according to their value in |json_dict|. Args: json_dict: (dict) Dict containing values dumped by SerializeAttributesToJsonDict. instance: (object) instance to modify. ...
e89274ccb47a2196303728c9f6d9f6ed5983be8a
174,360
def is_json(_path) -> bool: """Return True if file ends with .json, otherwise False.""" if _path.endswith(".json"): return True else: return False
ba2a3ec6b93675dc86d07fbd626fac7c75a14585
652,737
def remove_object(objs, label, none_val=0): """Remove object specified by id value""" objs[objs==label]=none_val return True
c62df57aebc323f85f318db982cc4de795c30e9a
46,822
def badge(message: str, badge_template: str) -> str: """Create color badge with message using template.""" return badge_template.format(message=message)
11fba2049db699ab95e7aa018b9f33d4e452d351
550,881
def user_unicode(self): """Return user's full name.""" return self.get_full_name()
409ff8558fa12d9fa375db238bdc4ec970e3037d
247,064
def get_action_by_name(client, cluster, name): """ Get action by name from some object Args: client: ADCM client API objects cluster: cluster object name: action name Returns: (action object): Action object by name Raises: :py:class:`ValueError` ...
9089b2e5d5b5b131eea0ddd9a16dace9decc5905
642,388
def count_recursive(contents_per_bag, bag_list): """ Count number of nested bags from the given list :param contents_per_bag: per-bag mapping :param bag_list: list of bag to inspect :return: number of bags """ nested_bag_qty = 0 for bag in bag_list: nested_bag_qty += 1 ...
d48e317ee73bf0f18021d27bc9857a3ad898759c
31,697
import yaml def data_file_read_yaml(filename): """ Reads a file as a yaml file. This is used to load data from fuzz-introspectors compiler plugin output. """ with open(filename, 'r') as stream: try: data_dict = yaml.safe_load(stream) return data_dict except ...
1ac2aa98d9628aab6637048a8f07f5ffa84aa750
650,093
import math def flip_phi(phi): """ Correct phi to within the 0 <= to <= 2pi range :return: phi in >=0 and <=2Pi """ Pi = math.pi if phi < 0: phi_out = phi + (2 * Pi) elif phi > (2 * Pi): phi_out = phi - (2 * Pi) else: phi_out = phi return phi_out
5f65525869b46d91ad1c6235eead873866a457ed
530,411
def get_neighbors(graph, node): """Return all neighbors for the given node in the graph :param graph: The given graph :type graph: nx.Graph :param node: The node to analyse :type node: tuple :return: List of all neighbors :rtype: list """ return graph.neighbors(node)
7fd45eb363fc64ee4f8b66d4505d18770858711a
153,773
def build_reverse_dictionary(word_to_id): """Given a dictionary for converting word to integer id. Returns a reverse dictionary for converting a id to word. Parameters ---------- word_to_id : dictionary mapping words to unique ids Returns -------- reverse_dictionary : a diction...
e306c09d99ef6a27eec715ddb8585db1a70b9f27
354,510
def leiaint(inteiro): """ --> Função que faz a validação da entrada de dados do tipo inteiro (int) :param inteiro: Mensagem para entrada de dados do usuário :return: retorna o valor digitado, caso este tenha sido um número inteiro :print: Escreve uma mensagem de erro na tela, caso o valor digitado n...
f402e7380ddc5b4dfab17535e5e1823236000a24
229,737
def linear_regression(x, y): """ Calculates a linear regression model for the set of data points. Args: x: a 1-d numpy array of length N, representing the x-coordinates of the N sample points y: a 1-d numpy array of length N, representing the y-coordinates of the N s...
33037a2d57172ff2eb386ed35787cda08eb8f11d
692,640
def get_bbox(element: dict) -> tuple: """Get a bounding box from a manga109 element. Args: element (dict): a manga element such as body, face, frame, and text Returns: tuple: a bounding box that comparises four integers -- (xmin, ymin, xmax, ymax) """ bbox_attrs = ("@xmin",...
994e103e22737e11c51c8a0ea9584539ad62c6fb
395,919
def get_symbol_name(result): """Returns the name used by this symbol based on availability""" if 'longName' in result: return result['longName'] elif 'shortName' in result: return result['shortName'] else: return result['symbol']
a45ef6c8feac4cef73470f3b7576e6fc97428cb3
86,487
def metalicity_nemec(period, phi31_v): """ Returns the Nemec formula metalicity of the given RRab RR Lyrae. The version of the formula used is from Skowron et al. (2016), where I band phi31 is used, as opposed to the original usage of Kp-passband phi31. (Nemec et al., 2013) (2) (Skowron et al....
ae9eb84da9be3e6d4610d25ae36ff0b95cd2e6fe
451,362
import six def is_str(x): """Whether the input is an string instance.""" return isinstance(x, six.string_types)
82a0e8ff501cd8264af5feec8e99b0a600cb8cd2
191,596
def calc_mean_std(feat, eps=1e-5): """Calculate mean and std for adaptive_instance_normalization. Args: feat (Tensor): 4D tensor. eps (float): A small value added to the variance to avoid divide-by-zero. Default: 1e-5. """ size = feat.size() assert len(size) == 4, 'The i...
a72daff9b7f4a718127eaf0da18e6206797ced27
379,108
import re def removePlexShowYear(title): """Removes any trailing year specification of the form '(YYYY)' as is often found in Plex show names""" return re.sub(r'([\s.\-_]\(\d{4}\))$', '', title)
8327eab02d7453f8f08371fa273770a45df4bfa8
123,173
import posixpath def shift_path_info(environ): """Shift a name from PATH_INFO to SCRIPT_NAME, returning it If there are no remaining path segments in PATH_INFO, return None. Note: 'environ' is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME. Note: when PAT...
6131be1027cde9e7d1149746e2daad73c79e4e65
308,792
def prefix(string, string_prefix): """ Check to see if a prefix is present in a string If not, add it :param string: string - string to check against :param string_prefix: string - prefix to check """ if string.startswith(string_prefix): return string else: return '%s%s'...
e65d7373cdf2014be8de6705c628489a6a9c2fbd
349,952
def ci(request, monkeypatch): """Parametrize all tests for CI Tasks may behave differently depending on whether they are running on a Continuous Integration (CI) server (where the environment variable `CI` will be set). This fixture makes sure all tests exercise tasks in both scenarios. """ ...
e95a445e2c731146e5c378f8ae5792aa40ed1e4d
407,971
import random import string def deadText(wordCount, wordLength, letterCase=None, printOut=None): """Generate random dummy text. Args: wordCount (int): The number of words the function will generate. wordLength (int): The length of each randomly generated word. letterCase (int, optiona...
4853aa56d0189b12030f51c84c4f31015f162264
145,599
def findXCoordinateFromDirection(direction): """ Returns delta X, when given a direction value """ if direction in (1, 5): return 0 elif direction in (2, 3, 4): return 2 elif direction in (6, 7, 8): return -2 else: error_template = "Unexpected direction value of: {0}"...
a69342e911255e21bde09a75b6d8cbb7229bdf39
324,144
import collections def transpose_dict(adict): """Transposes a dict of dicts to regroup the data.""" out = collections.defaultdict(dict) for k,v in adict.items(): for ik,iv in v.items(): out[ik][k] = iv return out
f97c7d664b78aef83f997e57bdcef8f943da3f7e
404,917
def onboarding_pipeline_patterns_pipeline_pattern_id_get(pipeline_pattern_id): # noqa: E501 """Get specific pipeline pattern # noqa: E501 :param pipeline_pattern_id: Pipeline pattern identifier :type pipeline_pattern_id: str :rtype: PipelinePattern """ return 'do some magic!'
453e0a9aa283e5ebe5de087e76305a3f1323942c
373,259
import re def cleaning(text): """ Cleans the provided text by lowering all letters, removing urls, removing emails, substituing punctuations with spaces Args: text (str): Input string to be cleaned Returns: text: cleaned text """ text = text.lower() text = re.sub('http...
beafd409f030f85105e6d3ac0bd50f93b8ccb4cd
96,728
from typing import OrderedDict def build_meta_layer(root): """ Build the meta layer from the provided root of the XML tree. :param root: The root element of the XML tree. :type root: :class:`etree.Element` :return: An OrderedDict containing the regulation metadata, suitable for direct tr...
e9d983e2fc2154015706d491aa95a92382457c36
181,397
import platform def is_platform_arm() -> bool: """ Checking if the running platform use ARM architecture. Returns ------- bool True if the running platform uses ARM architecture. """ return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith( "armv"...
5e487a5d8a6e3423f9752c1e7b520afd8a2d5f08
660,016
import torch def gae_rtg(x, gam, lam): """ This function calculates the rewards to go and at the same time the advantages with GAE. It works even if the length of the episodes is not the same for all of them. Args: x (tuple): Stores the rewards (R) as a list, the value estimates from ...
7ca6aef4872b7b6c1c49fc3e219333793d353fa0
136,087
def get_maximum_norm(p1, p2): """Return the inf norm between two points.""" return max(abs(p1[0]-p2[0]), abs(p1[1]-p2[1]))
0955c446d251ac561aaa6eb0bba5d63b9c94fc2e
240,081
def _is_section(tag): """Check if `tag` is a sphinx section (linkeable header).""" return ( tag.tag == 'div' and 'section' in tag.attributes.get('class', []) )
8605d8d95e9344c80e91dd1735bec79072507f7b
26,172
def aligned(value, func='vdec', aligned='w'): """Align specific size of 'w' or 'h' according to input func. Args: value (int): Input value to be aligned. func (str, optional): Alinged method for specified function. Defaults to 'vdec'. aligned (str, optional): Aligne `w` or `h`. Defaults...
239fc41ba4fdc6a292b625b768ed01d3997f78a3
456,034
def isUniversityEmail(email): """ Checks if the person has a university of windsor email """ return email.lower().endswith('@uwindsor.ca')
e56c66b59a6c938ffb1cc06d809edd306ce9ff6e
513,183
def _Backward3a_T_Ph(P, h): """Backward equation for region 3a, T=f(P,h) Parameters ---------- P : float Pressure [MPa] h : float Specific enthalpy [kJ/kg] Returns ------- T : float Temperature [K] References ---------- IAPWS, Revised Supplementary ...
a3c57b9e767ad48f6481a77dfb6dd87c09a17e95
241,082
def snake_case(word: str) -> str: """Convert capital case to snake case. Only alphanumerical characters are allowed. Only inserts camelcase between a consecutive lower and upper alphabetical character and lowers first letter. """ out = '' if len(word) == 0: return out cur_char: ...
004ac0095c18a13512e81611ba8a603e41aa901c
409,859
def is_hdfs_path(path): """ Check if a given path is HDFS uri Args: path (str): input path Returns: bool: True if input is a HDFS path, False otherwise >>>is_hdfs_path("/tdk") False >>>is_hdfs_path("hdfs://aa:123/bb/cc") True """ return path.startswith("hdfs://")
62cc9286f91fbad848541275d79d250bf62b4c99
38,690
def pprint_positions(position): """ custom print for TQSDK positions Args: position (tqsdk's position object) Returns: str: the formated string """ open_cost = 0 if position.pos > 0: open_cost = position.open_price_long elif position.pos < 0 : open_cost...
a168ff19b8294f7e2642e92a781e1059d21dcca2
363,881
import json def load_script(script_path): """Load script from a JSON file. Parameters ---------- script_path : str Path to JSON file. Returns ------- script : dict or dict[] Loaded JSON object. """ with open(script_path) as f: script = json.load(f) ...
be3dcd5411d51de7ad6cbc14e9770ac45d6b8b17
223,195
def get_tag(tags, key): """ Returns a specific value in aws tags, from specified key """ names = [item['Value'] for item in tags if item['Key'] == key] if not names: return '' return names[0]
630a50026b82e2beb8834df5a9b4d4220abafcbd
377,382
from datetime import datetime def convert_time(dt): """Convert datetime from ISO 8601 format to seconds since midnight.""" dt = datetime.strptime(dt[:19], '%Y-%m-%dT%H:%M:%S') return dt.hour * 60 * 60 + dt.minute * 60
bef7c8b4b31ba2807c3fb687af6ebf1aa895cdfa
488,899
import hashlib def generate_hash(algorithm, salt, password): """Generate the hash from the algorithm, salt and password.""" hash_obj = hashlib.new(algorithm) password_salted = salt + password hash_obj.update(password_salted.encode('utf-8')) password_hash = hash_obj.hexdigest() password_db_stri...
834cce7caf997b297c44283abaee7787fc01014e
502,406
import types def copy_func(f, name=None): """ Return a function with same code, globals, closure, and name (or provided name). """ fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__, f.__defaults__, f.__closure__) # If f has been given attributes fn.__dict__.upda...
65be84ec7e46c7f6726248fa627bfd9b800a24af
669,850
def do_while_loop(evaluator, ast, state): """Evaluates "do {body} while (cond)".""" while True: res, do_return = evaluator.eval_ast(ast["body"], state) if do_return: return res, True if not evaluator.eval_ast(ast["cond"], state): break return None, False
d083126f047a02abf1d83bb8a5daf60e5456b42a
512,259
def _get_top_vars(top, top_vars): """Generate a dictionary of values for the defaults directive.""" combining_rule_to_gmx = {"lorentz": 2, "geometric": 3} default_top_vars = dict() default_top_vars["nbfunc"] = 1 default_top_vars["comb-rule"] = combining_rule_to_gmx[top.combining_rule] default_to...
01fb2a132ec3c78ea36abc444c667db0f6faabc0
201,015
def group_cpu_metrics(metrics): """Group together each instances metrics per app/space""" grouped_metrics = {} for metric in metrics: grouped_metrics.setdefault(metric['space'], {}).setdefault(metric['app'], []).append(metric['value']) return [(app, space, metric_values,) for space,...
91b91601c359e2b80c31b80fcb80bd5915d5972d
41,915
def getMenuItemPrice (theDictionary, item): """Identifies the price of item. Assumes items are written in uppercase. :param dict[str, float] theDictionary: Dict containing menu items as keys and respective prices as prices. :param str item: The name of item to check the price o...
8395b692138dd911ed5c8fdd48d99e2da49f6f1e
324,988
def internal_dot(u, v): """Returns the dot product of two vectors. Should be identical to the output of numpy.dot(u, v). """ return u[0]*v[0] + u[1]*v[1] + u[2]*v[2]
3f8700d40bd703540fc67408ff7799d81d1c3f08
135,753
from typing import Any def create_null_type(name: str) -> Any: """ Creates a singleton instance of a custom nullable-type. This nullable-type acts much in the same way `None` does. It is a "Falsey" value, returns `None` when called, raises `StopIteration` when iterated, returns `False` when checking f...
e976a0a14e53ca63bdce3fc16252782960e0b3c5
576,789