content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def find_first(item, vector): """return the index of the first occurence of item in vector""" for i in range(len(vector)): if item == vector[i]: return i return len(vector)
162052704f346ce853e9c67ae13bc9e56220f22a
648,781
def get_split_name(test_dp=0.1, val_dp=0.1): """ 获取数据集的划分列表 :param test_dp: 测试集占整个数据集的比例,默认值为0.1 :param val_dp: 验证集占训练集的比例,默认值为0.1 :return: 返回一个所有划分集名称的列表 """ split_name_dict = { 'test': test_dp, 'val': (1 - test_dp) * val_dp, 'train': (1 - test_dp) * (1 - val_dp), ...
cffaec0139217cf148fcab86418feaf7f3ef8fd2
648,782
from itertools import zip_longest def v13_add(*matrices): """Add corresponding numbers in given 2-D matrices.""" try: return [ [sum(values) for values in zip_longest(*rows)] for rows in zip_longest(*matrices) ] except TypeError as e: raise ValueError("Given ...
5ccf6ca41b28a4ba204ebb2dc7317a85b8ff204f
648,783
import torch def affine_transform_pts(pts, trans): """ :param pts: (2, N) :param trans: (2, 3) :return: """ trans = torch.as_tensor(trans, device=pts.device, dtype=torch.float32) xy1 = torch.stack((pts[0], pts[1], torch.ones_like(pts[0]))).contiguous() return torch.mm(trans, xy1)
2257284a6848c829a8b513fac3745b8f059e43bb
648,785
def to_str(Q): """An informal, nicely printable string representation of the Quaternion object. """ return "{:.3f} {:+.3f}i {:+.3f}j {:+.3f}k".format(Q.q[0], Q.q[1], Q.q[2], Q.q[3])
8e5b560682563a9d70e4ad78ecd5940066c779d2
648,786
import re def decontracted(phrase): """ Change words abbreviations into their actual word meaning :param phrase: sentence we want to change :return: modified sentence """ # specific phrase = re.sub(r"won't", "will not", phrase) phrase = re.sub(r"can\'t", "can not", phrase) # gener...
97dcfc789b85382c5e72b6b737e1a5e7471448c0
648,787
async def get_alternate_id(db, name: str) -> str: """ Get an alternate id for an API key whose provided `name` is not unique. Appends an integer suffix to the end of the `name`. :param db: the application database object :param name: the API key name :return: an alternate unique id for the key ...
9bf86a1a47cc4da55ec0fdada1f0a491e051d6f2
648,788
import torch def compute_integrals(input, integral_powers): """Computes integrals of the input to the given powers.""" integrals = torch.zeros(input.size(0), len(integral_powers), 1) for i_q, q in enumerate(integral_powers): integrals[:, i_q, 0] = (input**q).view(input.size(0), -1).sum(1).cpu() ...
c4bcb501d9dc28fa0ab80a7b2c02ed8dd6f76183
648,789
def getPath(V): """Backtrack through lattice to retrieve path to optimal solution""" opt = [] max_prob = max(value["prob"] for value in V[-1].values()) previous = None # Get most probable state and its backtrack for st, data in V[-1].items(): if data["prob"] == max_prob: opt....
a78a9a0949f82e3965d852b3a192199968df480f
648,790
def __get_EW__(num): """Get east or west for longitudes num: Numeric value of longitude""" if((num > 0) & (num < 180)): return "E" elif((num < 0) & (num > -180)): return "W" else: return ""
95d7b9fbc961aef7f7608b9531120725c67b9dcc
648,791
def engine(request): """engine keyword argument for rolling.apply""" return request.param
964d9c4ba6ea419f233bf77c52fbccd285bcd7d8
648,792
from typing import Counter def compute_seq_lengths(sequences): """ Computes the sequence lengths. """ seq_lengths = [len(s) for s in sequences] seq_lengths = Counter(seq_lengths) return seq_lengths
6b04233d50b9c124321e452b18dfa2ee765eb73f
648,793
import hashlib def _hash_file_obj(obj): """Hash a file-like object.""" return hashlib.sha256(obj).hexdigest()
7b1eb0841d4dc3fe561603d3c5cdb2b230e20dee
648,794
def compute_sub_mask(outer_mask, outer_rect, inner_rect): """ Given a mask and sub-mask coordinates, extracts the sub-mask. No doubt numpy could do this in one line. :) outer_rect is the coords for the mask, and inner_rect is the sub-coordinates - contained entirely inside the outer_rect, nothing ou...
ab8d6ed926f1aba1ad943929189e1c15c7ca3425
648,795
from typing import Union from pathlib import Path def expand_path(path: Union[str, Path]) -> Path: """Convert relative paths to absolute with resolving user directory.""" return Path(path).expanduser().resolve()
fdcfa9aeefacde5ad15d21710e3f596e2597f6a3
648,796
def _VerifyDirectoryIterables(existing, expected): """Compare two iterables representing contents of a directory. Paths in |existing| and |expected| will be compared for exact match. Arguments: existing: An iterable containing paths that exist. expected: An iterable of paths that are expected. Raises...
40daa32a2ad239a2fc6f309b41ca7f4d64bb7b25
648,798
import re def is_http(what): """ Проверка, является ли строка http-адресом (очень простая) """ return re.match( r'^http://[a-z0-9.\-]+\.[a-z]{2,4}(.*)', what, re.I )
124a8bcf5a1a829459c7e76ae4399306a66a4d8e
648,799
def prime_factor_decomposition(num): """ Prime factor decomposition of a number. :param num: input number. :return: all prime factors of input number. """ primes = [2] for i in range(3, num): if i * i > num: break flag = True for j in primes: i...
0073e6646e7af9ed94ebb757aa47547f649f3856
648,800
def index_reset(x): """Reset index in the pandas dataframe. Args: x: original pandas dataframe Returns: x: data with new indice """ x = x.reset_index() if "index" in x.columns: x = x.drop(columns=["index"]) return x
f4ff9e8639c6f8dc9a21990a2f1e79fb169dac49
648,801
def avoid_duplicate_names(new_column_name, columns, suffix): """Adds a suffix in case of a column name collision in a recursive way :param new_column_name: a possible new column name :type: str :param columns: existing column names :type: list :param suffix: suffix to add to prevent collisions ...
61df74f97dc0026e0b4baa60c71ff7529dab32a1
648,802
def validate_list(value): """ Validate a list input. Parameters: value (any): Input value Returns: boolean: True if value is a list """ return isinstance(value, list)
652cc544a2132f655025e41cc7920334da1e6020
648,804
def p(key): """Returns PDT namespace prefix""" return '{http://ufal.mff.cuni.cz/pdt/pml/}%s' % (key)
67917be8b250839404e90d31547d035f209599bc
648,805
import torch def get_triple_filters(triples, graph, num_ents, ent2idx): """Given a set of triples, filter candidate entities that are valid substitutes of an entity in the triple at a given position (head or tail). For a particular triple, this allows to compute rankings for an entity of interest, aga...
59377292927ee851a559ec1b737386349642d2b1
648,806
def evaluate_llh(llh: float, gt_llh: float, tol: float = 1e-3): """Evaluate whether log likelihoods match.""" if llh is None: return False return abs(llh - gt_llh) < tol
ae044444a4a4739e90907c21e4e2cd967150f702
648,807
import pathlib def servo_yaml(tmp_path: pathlib.Path) -> pathlib.Path: """Return the path to an empty servo config file.""" config_path: pathlib.Path = tmp_path / "servo.yaml" config_path.touch() return config_path
cb51ed0830daf3abcbacfab8ca395071f4ec2574
648,809
def fake_invalid_auth_from_oc(mocker): """ Changes the return value of requests.post to be a custom response object so that we aren't validating external APIs in our unit tests """ class ExternalApiRequest(object): @classmethod def post(cls): return FakeExternalResponse(...
ef389edbe99b71e298f645e4bb4de4464d1384c4
648,811
def get_content_tagged(words, tags): """Return content words based on tag""" return [w for w, tag in zip(words.lower().split(), tags.split()) if tag in ("N", "^", "S", "Z", "A", "T", "V")]
c17ff7f0c6c56f58858cc4edd627417c3c698dd2
648,812
def cors_exempt(func): """ This decorator currently has bad compatibility with the REST framework. """ def wrap(request, *arg, **args): res = func(request, *arg, **args) res["Access-Control-Allow-Credentials"] = "true" # Allow all methods res["Access-Control-Allow-Metho...
37d60dc9408abca2a2c0b5106eddaff45a720ce3
648,814
import os import pickle def _load_db(target): """ Load database file from pickle, create new if not present """ # if a pickled file doesn't exist if not os.path.isfile('./database/{}.p'.format(target)): db = {} pickle.dump(db,open('./database/{}.p'.format(target),'wb')) else: ...
a56a83ef022041edbf679e91fe788f1b25674bbe
648,815
def split_sbts_nodes_comms(dataset): """ Returns processed database :param dataset: list of sentence pairs :return: list of paralel data e.g. (['first source sentence', 'second', ...], ['first target sentence', 'second', ...]) """ sbts = [] nodes = [] comms = [] edges = [] f...
696d2a8779f85d9f0c8e520781ad5dedb10a59de
648,816
def get_coords(x, y, params): """ Transforms the given coordinates from plane-space to Mandelbrot-space (real and imaginary). :param x: X coordinate on the plane. :param y: Y coordinate on the plane. :param params: Current application parameters. :type params: params.Params :return: Tuple c...
1b696016f69894ca7aad6d07ae8ec48dff5911c8
648,817
def batch_str2idx_with_flag(batch, vocab, unk=None, pad=None, sos=None, eos=None, reverse=False): """ Convert words in a batch into corresponding indices in the assigned vocabulary and append necessary flags. :param batch: the batch containing sentences :param vocab: the assigned vocabulary :param u...
a85a74352566441fe580efb89657c4b8ad346e21
648,818
import base64 def encodeImage(img): """Encodes a numpy array into a byte image :param img: :return: """ if type(img) is not bytes: bytes_img = img.tobytes() else: bytes_img = img processed_image_base64 = base64.b64encode(bytes_img) base64_string = processed_image_base64...
c5ed3a0d191d39149fd565a20cdf39c149428560
648,819
def and_(*, alpha=None, omega): """Define dyadic Boolean and. Dyadic case: 0 0 1 1 ∧ 0 1 0 1 0 0 0 1 """ return alpha and omega
756209b051891ef8fd9c90423865e865abae3587
648,822
def descend_density_tree(data_point, node): """given some test data and decision tree, assign the correct label using a decision tree""" if data_point[node.split_dimension] < node.split_value: if node.left is not None: # no leaf node return descend_density_tree(data_point, node.left) ...
623af036d6d8471406ccc93306091e0662a247eb
648,823
def __version__(): """Return a brief version string and statement for this class.""" return str('1.0'), str('Class DynamicStockModel, dsm. Version 1.0. Last change: July 25th, 2019. Check https://github.com/IndEcol/ODYM for latest version.')
5a64668f54d202743a7490106ce9397d7e30c0b0
648,824
def xor_decrypt(ciphertext: str, key: int) -> str: """ Decrypt a hex-encoded ciphertext into plaintext. Args: ciphertext (str): The hex-encoded ciphertext key (int): The single-byte key Returns: str: The plaintext """ return ''.join(chr(b ^ key) for b in bytes.fromhex(ciphe...
c54cc86fe47c6f4ae6682c55e7df99cf2114a94b
648,826
def CreateFile(fileName): """ Create an empty file as per passed path and name """ try: f = open(fileName, "w+") f.close() return 0, None except Exception as e: return -1, e
fed0605b3175220e187794452f82a881c9d83b7e
648,827
def fnCalculate_AntennaBeamwidth(k,wavelength,radius): """ Calculate the Half Power Beam Width for a parabolic antenna k == 57.3 usually Output is in [deg] not [rad] Created: 31 May 2017 """ return (k*wavelength/(2.*radius))
34da904f549a45e0e6912633e743249722f29218
648,828
def DictionaryLower(dictionaryForward: dict): """ Function to convert dictionaries with string entries to upper case. Args: dictionaryForward: Simple 1-dimensional dictionaries. Returns: dictionary forward in lower case key/values. """ return dict((str(k).lower(), v.lower()) for k, v i...
391b4876b2d61aa6ab55b989e12a59a9733ae363
648,829
def get_trees_max_depth(state, max_depth): """ >>> s = [6, True, -5, True, 0, True, 9, True] >>> get_trees_max_depth(s, 2) ([(0, 1, 7)], [(4, False, False), (6, False, False), (2, 3, 5)]) >>> s = [2, True, 1] >>> get_trees_max_depth(s, 2) ([(0, 1, -1), (2, -1, -1)], []) >>> s = [2, True...
5b421be65e8d0cd54939c072bef5e51200202cfe
648,830
import itertools def flatten(x): """ Flatten list of lists """ flatted_list = list(itertools.chain(*x)) return flatted_list
b12eb6aa09676d1cd5d6b166fe4e8dc554f7a409
648,831
def extract_model_parameters(state_dict): """ Extracts model parameters from state dict loaded from PyTorch :param state_dict: Dict from torch.load() :return: Tuple containing ESRGAN model parameters """ in_nc = None out_nc = None nf = None nb = None scale2 = 0 max_part = 0 ...
aa3b778b427b2e58b08b2b29ed73469b242f6fed
648,832
import torch def hits_at(scores: torch.Tensor, k: int = 5) -> float: """ Tested | Accepts one (n,) tensor """ rank = (torch.argsort(scores, dim=0) == 0).nonzero()[0] + 1 if rank <= k: return 1.0 else: return 0.0
0ca1b4af6591764ad74a391d60eca52ed227b16d
648,833
import base64 def base64_from_int(value): """Converts the number into base64 representation. Args: value: int. Integer value for conversion into base64. Returns: *. Returns the base64 representation of the number passed. """ return base64.b64encode(bytes([value]))
98b9a7201b326d0a6232f431730ad692b1283600
648,834
def divideList(x, k): """ Divide list @x into roughly @k parts. """ if k > len(x): return [[elem] for elem in x] part_len = int(len(x) / k) parts = [] start = 0 while start < len(x): parts.append(x[start: start + part_len]) start += part_len return parts
5f9ec0f2d1e016491b7f37ee8e2e0c11d1b4f0e4
648,835
import time def epoch(value): """ Convert datetime to unix epoch time. Alternatively you can you this {{ my_date|date:"U" }} :param value: datetime instance :return: int """ try: return int(time.mktime(value.timetuple()) * 1000) except AttributeError: return ''
c2d530542570911412b11c801d20a92af6c8a724
648,836
from functools import reduce def to_atomic_mass(mfrac_field): """Conversion function from field names to atomic masses.""" numeric = filter(lambda char: char.isnumeric(), mfrac_field) return int(reduce(lambda a, b: a + b, numeric))
2503493b46574abd2b9ffae8933225572c9e444f
648,837
import sys from io import StringIO import traceback def get_error(e): """ String format error massage and trace back """ exc_type, exc_value, exc_traceback = sys.exc_info() sio = StringIO() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=100, f...
ff79ee9277b1e518bdcda15a5f939fb06813a9ec
648,838
import torch def smooth_l1(input, target, beta=1. / 9): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ n = torch.abs(input - target) cond = n < beta loss = torch.where(cond, 0.5 * n ** 2 / beta, n - 0.5 * beta) return loss
bdc4c12f4dfd921ee77788a31c62dc8e80749d4a
648,839
def invert_mask(attention_mask): """Turns 1->0, 0->1, False->True, True-> False""" assert attention_mask.dim() == 2 return attention_mask.eq(0)
352d67acdeb1eaf0643b4453ddada7ac7fdc2e74
648,841
def to_byte(byte): """Make sure an object really represents an integer from 0 to 255, and return the integer. """ byte = float(byte) assert byte.is_integer(), f"Got a non-integer byte: {byte}!" byte = int(byte) assert byte >= 0, f"Got a negative value for a byte: {byte}!" assert byte <=...
abbe94e31f28be1b6e59a8d7b246a56b25553945
648,843
def ifelse (pred:bool, cons, alt): """ If predicate consequent else alternative """ if pred: return cons else: return alt
421c170e8c1650950e295882267d5f5946e29d08
648,844
def get_multi_string(request, attr_name): """Extracts multi data from request.POST :param request: Request object :param attr_name: Attribute name to extract data from :return: """ return [attr for attr in request.GET.getall(attr_name)]
e3fb79cdba022fd71bbf37a0fd1b554e871dd2bd
648,846
def as_pairs_seq(iterable): """ Return the given Python iterable as a sequence of nested (item, next) pairs. No iteration! """ itr = iter(iterable) # Use a sentinel object to indicate the end of iteration rather than # exception handling because that is more functional in style. # Since...
67b3d161c28997ad8ca32c56b363158fa1f9788b
648,847
def parse_config(path): """ This method parses a config file and constructs a list of blocks. Each block is a singular unit in the architecture as explained in the paper. Blocks are represented as a dictionary in the list. Input: - path: path to the config file. Returns: - a list co...
2f529c167abd9b2360ed424384aaea228e5352be
648,848
import re def parse_arches_from_config_in(fname): """Given a path to an arch/Config.in.* file, parse it to get the list of BR2_ARCH values for this architecture.""" arches = set() with open(fname, "r") as f: parsing_arches = False for line in f: line = line.strip() ...
af1d8de9a5a210f4e009b942cf069f1c6d6c4e47
648,849
def test_module(client): """ Test connection to Azure by calling the list incidents API with limit=1 """ client.http_request('GET', 'incidents', params={'$top': 1}) return 'ok'
b8878699e67d08b7b9d7e34804315abce1311d83
648,850
def _ward_clustering(X_init, ward, train_index): """Ward clustering applied to full X but computed from a subsample of X""" ward = ward.fit(X_init[train_index, :]) X_reduced = ward.transform(X_init) return X_reduced, ward
27e28ad614321327ff16b5d92dc04b46fa4a9ef2
648,851
from typing import Mapping from typing import Sequence from typing import Union from typing import List import itertools def hyper_grid( grid_dict: Mapping[str, Sequence[Union[str, int, float]]] ) -> List[Mapping[str, Union[str, int, float]]]: """Converts a param-keyed dict of lists to a list of mapping. Arg...
a62493e187be204ac6cd2995c4a997cf153990c1
648,854
def readable_timedelta(days): # docstring with """ """Takes a value in days and returns weeks with days remaining """ weeks = days // 7 remainder = days % 7 total_time = "{} week(s) and {} day(s)".format(weeks, remainder) return total_time
7352e50583cbc96699b61057d10d566b16bccafd
648,855
def self_multiply(tensor_tuple: tuple): """ :param tensor_tuple: :return: """ tensor_list = list(tensor_tuple) if None in tensor_list: tensor_list.remove(None) if len(tensor_list) == 0: return 0 s = tensor_list[0] for i in range(1, len(tensor_list)): s *= ten...
35041c78b77b5360234e9c553a6c4456c7789861
648,856
def compute(expression: str) -> int: """Compute a Polish Notation expression.""" return 0
1db3aa9b136244474a874d1eead5d348e25a0a35
648,857
def dict_to_qs(dct): """ Takes a dictionary and uses it to create a query string. """ itms = ["%s=%s" % (key, val) for key, val in list(dct.items()) if val is not None] return "&".join(itms)
5a670ca6d195ccac38a807c52fb227e5d43a3fa2
648,858
def remove_surrogates(s, errors='replace'): """Replace surrogates generated by fsdecode with '?' """ return s.encode('utf-8', errors).decode('utf-8')
c06e803cb201e4e0820b328f54409d140f2e983e
648,860
def factorial(n): """Factorial function. This will be used in the power series""" if n==1: return 1 return n * factorial(n-1)
92442a4b079722ca42517ddb400096a00f471a1b
648,861
async def get_request(client, url) -> dict: """ Make get request to the url """ resp = await client.get(url) return resp.json()
90d5bcaf1d01cb4a82fd30860514b96dfe09de8d
648,862
import os def get_tumor_cell_count(instance_dir, max_time): """ @return tumor cell count value from fname or -2, if file doesn't exist, or -1 if run terminated prematurely. """ tumor_cell_count = '-2' fname = '{}/output/metrics.txt'.format(instance_dir) if os.path.exists(fname): wi...
dfdfec193d0cc031b17e71add4b44b0d606dfa91
648,863
def csv_to_set(x): """Convert a comma-separated list of strings to a set of strings.""" if not x: return set() else: return set(x.split(","))
eed054487d137b4ba134401bb4a0bb4b6d70e4a3
648,864
def checkin_list(event): """Returns an checkin list instance""" return event.checkin_lists.create(name="Test Checkinlist", all_products=True)
8caa8ef56fc527b5fc9cdb9971ba6fed10db1e95
648,865
import re def optimade_filter_conversion(filter_expr): """ Convert optimade filters to oqmdap formationenergy filters Input: :str : original filter expression Output: :str : converted filter expression """ filter_expr_out = filter_expr # General conversion filter_expr_...
b954d1fffe48f7578cef687adea23d3684d8a030
648,866
def tokenized_pretty_print(tokens): """" Pretty print function for strings tokenized by tokenize_words :param tokens: list of tokens :return: string """ out = "" for t in tokens: if t in ".,):!?": if out[-1] == " ": out = out[:-1] out += t + "...
6ad4e58e4c6d5cf78ddd570175a9589a5a607918
648,868
import inspect def isderivedclass(klass, parent): """ Test if klass is derived from a parent class. Parameters: klass A <class 'klass'> object. parent Class type or string name of the parent class. Returns True or False. """ try: name = parent.__name__ except AttributeError: nam...
755810c78e4fd6b1ffef2861187b0b999fa904d7
648,869
def argmin(l): """ Get index of min element in list """ return min(zip(l, range(len(l))))[1]
8160e171d1d430f3a390e76e0abbcb6c39e27592
648,870
def matchRatings(data): """matches ratings data to lables""" matchedData = [] lable = [] lable.append("5-star") matchedData.append(data.count(5)) lable.append("4-star") matchedData.append(data.count(4)) lable.append("3-star") matchedData.append(data.count(3)) lable.append("2-star...
3fdf935602f651a8bbfd569408145160bbdd5f74
648,871
def date_range_overlap(start_1, end_1, start_2, end_2): """ Based on: https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation-in-python """ latest_start = max(start_1, start_2) earliest_end = min(end_1, end_2) delta = (earliest_end - latest_start).days + 1 return...
58be73b32620f606fcb6c12f3b74dad631c19d5e
648,872
def _maven_artifact(group, artifact, version, packaging = None, classifier = None, override_license_types = None, exclusions = None, neverlink = None): """ Generates the data map for a Maven artifact given the available information about its coordinates. Args: group: *Required* The Maven artifact c...
25eef1787010ab5fd16fbc28b42082e23e086866
648,873
def average_above_zero(table): """ Args: Une liste Returns: Une moyenne type float exception si l'ardument n'es pas une liste exception si la liste est vide exeption si il y a des valeur différente dans la liste """ #test du type de variable if not(isinstance(table, list)): r...
0ccbc26d903989cb7b46f36fe08affac8442285c
648,874
from typing import Type from enum import Enum def string_to_konan_enum( enum_string: str, enum_class: Type, ) -> Enum: """Create an enum object from enum_string. If the enum_class does NOT have a corresponding enum_string, then return enum_class.Other enum_class must include the Other type :p...
5ec02ac680b9983957e79249ce4972b0c18f80e1
648,876
import bs4 def is_navigable_string(obj): """Is navigable string.""" return isinstance(obj, bs4.NavigableString)
7cf8f2c1e6a1ca87aa62cd9a22930d0e53fc8e6d
648,877
def parse_filename(filename): """ Example filename: bio_E_PLT_13.5cms_40Hz_2pedal_0.1step Args: filename (str): Returns: """ meta = filename.split("_") source = meta[0] if source not in ['bio', 'neuron', 'gras', 'nest']: raise Exception("Cannot recognize source") muscle = meta[1] if muscle not in ['E'...
b8b0082e6e9380dcbec906e8c07c883a602cdf4e
648,878
def core_result_type(selectable, s): """Given a SQLAlchemy Core selectable and a connection/session, get the type constructor for the result row type.""" result_proxy = s.execute(selectable.limit(0)) return result_proxy._row_getter
5ce237376289bb03c1b465f94b597124ff3af8d4
648,879
def f(x, y): """ Function that will be optimized Parameters ---------- x : float Value for parameter x. y : float Value for parameter x. Returns ------- float Function value for f(x,y). """ if (x**2 + y**2) <= 2: return (1-x)**2 + 100*((...
2000faddd9bc0cb37e71bf64c86072a51ec1e9da
648,880
import math def normalize_weight(weight): """AS3 accepts ratios between 0 and 100 whereas Octavia allows ratios in a range of 0 and 256, so we normalize the Octavia value for AS3 consumption. We also round up the result since we want avoid having a 0 (no traffic received at all) when setting a we...
83a66d9dd3b58229f48b9510382f05f5e803abe6
648,881
import os def get_plugin_full_name(partial_module_name: str) -> str: """ Return full module name. The partial name should be relative to the test/unit/data/model directory. """ path = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, os.pardir) path = os.path....
c2a92b0adf993b189be8c92bad573de18fd2b970
648,882
def isOdd (intValue): """Determines if an integer is odd. Assignment: This function will return True if intValue is odd, otherwise it returns False. :param intValue: Integer to be tested if odd :type intValue: int :return: A determination if intValue is odd :rtype: bool :raise Type...
a1ad9c6882847df308fa3bc213e9661f21285a19
648,883
def sgi_1973_to_2016(sgi_id: str) -> str: """ Convert the slightly different SGI1973 to the SGI2016 id format. :examples: >>> sgi_1973_to_2016("B55") 'B55' >>> sgi_1973_to_2016("B55-19") 'B55-19' >>> sgi_1973_to_2016("E73-2") 'E73-02' """ if "-" n...
8109c96b66ca7b0707536ec61d4d457410f5967e
648,884
def valid_user_input(ui: str) -> bool: """Determines if the passed string is a valid RPS choice.""" if ui == "rock" or ui == "paper" or ui == "scissors": return True return False
648484999fcc3a81cce06e4480a1bb6bd5ed5069
648,886
def null_heuristic(state, problem=None): """Return a trivial heuristic. In general a heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. """ return 0
e9308278bbe92ca7fb81163e8bb25d8c3e566331
648,887
def filter_data(data, condition): """ Remove elements that do not match the condition provided. Takes a data list as input and returns a filtered list. Conditions should be a list of strings of the following format: '<field> <op> <value>' where the following operations are valid: >, <, >=, <=,...
7f966c8337f84ce516525c370a217f790b2f27a6
648,888
import os import importlib def _parse_config_path(config_path: str) -> str: """Turns config_path into path to the config in python system path. Path is split into head and filename using `os.path.split`. The head is treated as a Python package and the filename as a gin file. Path to where the package is loca...
0717883cad55ca1b1a69ecbcf3793d7ee4fe1cfb
648,889
def vec_neg(a): """ Negates a vector element-wise Parameters ---------- a: list[] A vector of scalar values Returns ------- list[] The negated vector of a """ # return [-a[n] for n in range(len(a))] return [*map(lambda ai: -ai, a)]
01a6c434eb1fbd3854bf1e7e8557b3154bc735bb
648,890
def SumString(table : list) -> str: """ Connects all the strings in the list to a single string, optimal for the output of JLua.GetLuaString() :param table: A string list like generated by readlines() or GetLuaString() :return: The Connected string """ sumstring = "" for string in table: su...
f6e187b3087bae1407df4948215f8dd2c62c489f
648,891
from typing import Any from typing import Mapping from typing import Collection def is_arraylike(obj: Any) -> bool: """Determine if the provided object is an non-mapping generic container type such as an array,\ tuple or set. Example: >>> from collectionish.utils import is_arraylike >>> ...
69ed931d76da77b71a248a790a5beb6f9d87d3f0
648,892
def paint_text(text_str, color_str): """ Adds markup around given text. Supports some colors by name instead of hexadecimal. :param text_str: :param color_str: (str) Hexadecimal color. :return: (str) """ return '[color={color_str}]{text_str}[/color]'.format(text_str=text_str, ...
256dde931eeec82250fc178d28d9bdc07cd651c8
648,893
import csv def read_csv_data_from_filepath(csv_file_path): """ Reads csv from provided file path and returns csv data in dictionary params: run_path: current run path for script for use in finding config file returns: csv_data: dictionary of data read by the csv python lib """ ...
1092d7e70fa9309ca90476e2cfbaf06ee497f681
648,894
from pathlib import Path def get_files_under_dir(root, pattern): """Construct list of path objects given pattern under the root directory. """ root = Path(root) if root.exists(): return [p for p in root.glob(pattern) if p.is_file()] else: raise FileNotFoundError(f"Direcotry {root}...
79a762c94b5edea9631ef6f96f53035f07faeded
648,895
def compute_r_parameter(ago_susceptible: int, current_susceptible: int, current_infected: int) -> float: """ Function for compute infection ratio parameter based od SIR model. Parameters ---------- ago_susceptible: int, required Amount of susceptible people one interval before current itera...
cd33abad340a178ce03e669d135a065f1b78b2ea
648,896
def rotate_right(x, y): """ Left rotates a list x by the number of steps specified in y. Examples: >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return x y = len(x) - y % len(x) retur...
bbf75b17d2d31bd9d9a648a168c229367c8b77c5
648,897
import re def ssdp_locations(scan): """ Convert ssdp_scan or ssdp_filter result to virtual device location """ pattern = re.compile(r"location\s*:\s*(.+).$", re.I | re.M) output = [pattern.search(i) for i in scan] output = [i for i in output if i] output = [i.group(1) for i in output] ...
286425a662f4c60fb72799712c93a5f31bfb5563
648,898