content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _transpose_order(row, forward=True): """ Swaps lines within a row to see if the number of crossings improve. """ len_ = len(row.end) if forward else len(row.start) order = list(range(len_)) if len_ < 2: return order crossings = row.count_crossings() improved = True while improv...
8a08a7ecce4340d270cf60842139d07bbbe1e353
685,422
def ycbcr_to_yuv(ycbcr, bit_depth=10): """ Converts from YCbCr(Limited Range) to YUV(float). Parameters ---------- ycbcr : numeric or ndarray. shape must be (n, 3) ycbcr data. bit_depth : integer bit depth of the ycbcr. Returns ------- numeric or ndarray YU...
97488ab60751182d6bd9d8895f99f1efa4cf8f8d
685,423
import random def get_tenran(var): """ 从var列表中随机提取十组6个元素 :param var: :return: """ first = random.sample(var, 10) tenRan = [] for j in first: k = var[:] k.remove(j) child = random.sample(k, 5) child.insert(0, j) tenRan.append(child) return ten...
af2b7dd28932cab4ee12da215ca6e3963090fe9a
685,424
import numpy def generate_sources(count, flux_mu, flux_sigma, size): """ generate a matrix containing random sources """ fluxes = numpy.random.normal(loc=flux_mu, scale=flux_sigma, size=count) x = numpy.random.uniform(low=0, high=size, size=count) y = numpy.random.uniform(low=0, high=size, siz...
2772f96950640ba2e151a08c801f0ae5f2393a93
685,425
def offset_error(x_gt, x_pred, loss_mask): """ masked offset error for global coordinate data. inputs: - x_gt: ground truth future data. tensor. size: (batch, seq_len, 2) - x_pred: future data prediction. tensor. size: (batch, seq_len, 2) - loss_mask: 0-1 mask on prediction range. si...
3ccd15a32d24c2461e15c74e4b94c958966fd8af
685,426
def obsolete(fonction_origine): """Décorateur levant une exception pour noter que la fonction_origine est obsolète""" def fonction_modifiee(): raise RuntimeError("la fonction {0} est obsolète !".format(fonction_origine)) return fonction_modifiee
59f3e71019720fc7cec938f164ca89d23e145cbd
685,427
def sqrt(x): """Compute square roots using the method of Heron of Alexandria. Args: x: The number to compute the square root of Returns: The square root of x. """ if x < 0: raise ValueError("Cannot compute square root of negative number {}".format(x)) guess = x i =...
788ff9bcc3dc8503f790b4e618b7128b285958fa
685,428
def mutate_hyper(individual: list): """Mutates an individuals personal set of hyperparams""" ind_hyper_params = individual[0] ind_hyper_params.mutate() # noinspection PyRedundantParentheses return (individual,)
a5d576301f28bdcc36595e0dcf0bbe2d4f09da8c
685,429
import ipaddress def is_default_route(ip): """ helper to check if this IP is default route :param ip: IP to check as string :return True if default, else False """ t = ipaddress.ip_address(ip.split("/")[0]) return t.is_unspecified and ip.split("/")[1] == "0"
321c610c02484f8231bf050bc9b6a39c8c48386a
685,430
import inspect def get_class_that_defined_method(method): """ Returns the class that defined the method Got implementation from stackoverflow http://stackoverflow.com/a/25959545/3903832 """ # for bound methods if inspect.ismethod(method): for cls in inspect.getmro(method.__self__._...
c1e32bbcc180dae66bc9e6e2447a163eaee993a4
685,431
from typing import List def group_by_prefix(strings: List[str]) -> dict: """ Groups strings by common prefixes """ strings_by_prefix: dict = {} for string in strings: if len(string.split("-")) <= 1: strings_by_prefix.setdefault(string, []) continue prefix, s...
86d0f68061a278dbd7d0bf04fa5e159b080397a9
685,432
def operate(op, left, right): """ Apply the indicated operator to support generality in cmp_exception() """ if op == '==': return left == right elif op == '!=': return left != right elif op == '<': return left < right elif op == '<=': return left <= right ...
29966596facb17c0284dfe6e614f47c72a1c5f06
685,433
def image_test(title, report_dir, info_list, figs): """ generates a snippet of markdown with a title, a list of information, and a plot Args: title (string): Title of the test info_list (list of strings): A list of info to print in the markdown fig (matplotlib figure): figure to print a...
8de674e3563f259751af774287cc42b8b1403c37
685,434
def expand_noderange(value): """Expand a given node range like: '1-10,17,19'""" ranges = value.split(',') nodes = [] for r in ranges: if '-' in r: start, end = r.split('-') nodes += [str(i) for i in range(int(start), int(end) + 1)] else: nodes.append(r...
5df0572ffb4f7b457038f90a81d02f6479fd1a8f
685,435
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) Space Complexity: O(n) """ if num == 0: raise ValueError("num cannot be zero") if num == 1: return "1" arr = [0, 1, 1] for i in range(3, num+1): ...
051a365ca424dce56ac6a8398e6ee3dd0f8be736
685,436
import os def fix_home_prefix(path): """ Try to replace a real path (/a/path/user) with a symlink path (/symlink/path/user), with clue from userhome and current working directory. """ userhome = os.path.expanduser("~") realhome = os.path.realpath(userhome) if path.startswith(realhome)...
353702140bcce87b5f508c558294f7022411a0ae
685,437
import subprocess import logging def exec_cmd(cmd): """Run a command in a subprocess. Args: cmd: command line to be executed. Return: int, the return code. """ try: retcode = subprocess.call(cmd, shell=True) if retcode < 0: logging.info(f"Child was termi...
db7c5dee3c81fe600c72347c095858fc2726140e
685,438
from datetime import datetime def datetimes_equal_minutes(dt1, dt2): """Assert that two datetimes are equal with precision to minutes.""" return datetime(*dt1.timetuple()[:5]) == datetime(*dt2.timetuple()[:5])
7d2ddd8fce7414d0ada4e95c93de552c5f7e49ec
685,439
import re def replcDeid(s): """ replace de-identified elements in the sentence (date, name, address, hospital, phone) """ s = re.sub('\[\*\*\d{4}-\d{2}-\d{2}\*\*\]', 'date', s) s = re.sub('\[\*\*.*?Name.*?\*\*\]', 'name', s) s = re.sub('\[\*\*.*?(phone|number).*?\*\*\]', 'phone', s) s = re...
5a877d752b72e38ac92435a83c3c20284f6ac8d1
685,440
from typing import List from typing import Optional def linear_search(elements: List[int], k: int) -> Optional[List[int]]: """ Thiis is a linear search to find a contiguous sequence of subelements of a list that sum to k. :param elements: the elements of the list :param k: the desired sum :return:...
140f642e4c249881f25b1d62cdb60f51c0306470
685,441
def prep_words(name, word_list_ini): """Prep word list for finding anagrams.""" print("length initial word_list = {}".format(len(word_list_ini))) len_name = len(name) word_list = [word.lower() for word in word_list_ini if len(word) == len_name] print("length of new word_list = {}".format(len(word_li...
dc5525c1486ada171560b7dbe2c92cad59664762
685,442
def _pathlib_compat(path): """ For path-like objects, convert to a filename for compatibility on Python 3.6.1 and earlier. """ try: return path.__fspath__() except AttributeError: return str(path)
5f91c9f5653451e381167c307d473f735b1d69e0
685,443
def _GetEnumValue(helper, name_or_value): """Maps an enum name to its value. Checks that a value is valid.""" if isinstance(name_or_value, int): helper.Name(name_or_value) # Raises EnumError if not a valid value. return name_or_value else: return helper.Value(name_or_value)
10656c8073d5bafd0b846bbcc30fcce4e7274881
685,444
def get_opacity(spectrum, mean): """ Calculate the opacity profile for the spectrum. This simply divides the spectrum's flux by the mean. :param spectrum: The spectrum to be processed :param mean: The mean background flux, representing what the backlighting sources average flux. :return: The op...
13cdf27a020c066b57a8eb7b4a5957a3cced26de
685,445
import argparse def get_args() -> argparse.ArgumentParser: """ Parse cmd-line arguments :returns: parser - ArgumentParser object containing cmd-line arguments """ parser = argparse.ArgumentParser(description="Scrape xkcd-comics images into a folder") # positional cmd-line argument for the directory path to st...
3e1ba30e918ce9c3ecf1c2986a561f0dae5a6b35
685,446
import torch def _rezise_targets(targets, height, width): """ Resize the targets to the same size of logits (add height and width channels) """ targets = torch.stack(targets) # convert list of scalar tensors to single tensor targets = targets.view( targets.size(0), targets.size(1), 1, 1, ...
2cbb2db0bd11f0d3cab3c558516a46f8e1fb1b6e
685,447
import hmac import hashlib import base64 def get_uid(secret_key, email): """ This function calcualtes the unique user id :param secret_key: APP's secret key :param email: Github user's email :return: unique uid using HMAC """ dig = hmac.new(bytes(secret_key.encode()), email.encode(), hash...
d12b1abbec92f8767a347b9cab173af4031bcc83
685,448
import argparse def parsing_arguments(): """Provide arguments from Command Line.""" # Initialize the parser parser = argparse.ArgumentParser() # Adding arguments parser.add_argument("username", help="Collects tweets of the user provided.") # Read the arguments from command line args = p...
3b6f9c2fbcf7f9e3bb3c041fe212ddc1a2d6900a
685,449
import platform import os def ping(ip, count=1): """ping 检查 Args: ip: ip count: ping检查次数 (Default value = 1) Returns: Bool: ping检查通过与否 """ # 根据平台适配不同的ping命令 if "linux" == platform.system().lower(): status = os.system("ping -c {} {}".format(count, ip)) else: ...
1dfd5c86ee86d9e6f8438bd4624317989ca02efe
685,450
from typing import Sequence from typing import Tuple def get_violations_count(individual: Sequence, queens_amount: int) -> Tuple[int]: """Get the amount of violations. A violation is counted if two queens are placed in the same column or are in the same diagonal. Args: individual (deap.creator.Si...
2c086cecfdf5545815b3431b9ade733b4eabc2ef
685,452
import os import sys import requests def translate(message): """Translate ``message`` from english to arabic""" yandex_token = os.environ.get("YANDEX_TRANSLATE_TOKEN") if not yandex_token: sys.stderr.write("Please Provide Yandex Translate Token") sys.exit(1) response = requests.post( ...
96b44798927accb5f5d2ee1487d54f1c05d85ece
685,453
import time def get_current_timestamp(): """ 获取本地当前时间戳(10位): Unix timestamp:是从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒 """ return int(time.time())
4d0719d687332b02530fb3bbba4ec3fb5c927123
685,454
def custom_sort(x: str): """ All sorted lowercase letters are ahead of uppercase letters. All sorted uppercase letters are ahead of digits. All sorted odd digits are ahead of sorted even digits. """ return ( not str(x).isalpha(), not str(x).islower(), str(x).isdigit(), ...
8d869acb48ed75ee8174bd7a0606688df61a6ab4
685,455
def ka_lt(v1, v2): """比较小于""" return eval(f"{v1}<{v2}")
babc390ae834bc65b6c8ed4081c3d4885e439c64
685,456
import os def get_resource_directory(): """Get the absolute path to the test resources directory. File is located based on the relative location of this file (util.py). """ here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, "resources")
b07aea0ddc3b92957b786d745943132d696f0a42
685,457
import jinja2 def parse(template, jinja2_env=None): """Parses Jinja2 template and returns it's NODE. :type template: basestring :type jinja2_env: :class:`jinja2.Environment` :rtype: :class:`jinja2.nodes.Template` """ if jinja2_env is None: jinja2_env = jinja2.Environment() return ...
71eb2c1d530c0e363973524d1d6382bd152a2540
685,458
def miles_to_kilometers(L_miles): """ Convert length in miles to length in kilometers. PARAMETERS ---------- L_miles: tuple A miles expression of length RETURNS ---------- L_kilometers: float The kilometers expression of length L_miles """ return 1...
bae2f8d6b11477461c84e098a90c6597cb986dad
685,459
def find_a_not_in_b(a: list, b: list): """找到a中存在b中不存在的元素 Parameter --------- Return ------ list """ # isinstance(a, float)是为了防止[空值]的情况 if isinstance(a, float) or isinstance(b, float): return a return [i1 for i1 in a if i1 not in b]
f8c64c655c7d12b806a3cc380283e3c6d440251d
685,460
def value(instance:dict, key:str) -> str: """ gets the first value of the AWS object `instance` tag, or "" if not found """ tags = instance.get("Tags", instance.get("TagList", [])) return next(iter(map(lambda c: c["Value"], filter(lambda t: t["Key"] == key, tags))), "")
d68e582c674d134db672ae7df100db2aead3be4c
685,461
def assign_pos_imp(df): """Calculate pos_imp for weighted position Arguments: df -- source DataFrame """ return df.assign(pos_imp=lambda x: x.position * x.impressions)
3307e166d0d6ba0f1bc622b6e72ddb136fe8a7f6
685,462
import argparse def parse_arguments(arguments): """ This function parses command line inputs and returns them for main() :method: parameter that determines the operation of the script either hash or check, can not be left empty :path: path to file to be worked on :config: full path t...
ab388340b095faa6e913f3e0061ed0b3dcce6e9b
685,463
from datetime import datetime def convdate(rawdate): """Returns integer data from mm/dd/YYYY""" day = datetime.strptime(rawdate, '%m/%d/%Y') return day.weekday()
3327c80027c7fcdbc924c2c90762f13849ab9075
685,464
def get_rds_snapshot(snapshot_identifier: str, rds): """Return single rds cluster snapshot""" return rds.describe_db_cluster_snapshots( DBClusterSnapshotIdentifier=snapshot_identifier, )["DBClusterSnapshots"]
fc5c03866d0c4c8e6d935b5d98d51cf00a3dcf1b
685,465
def matrix_empty(rows, cols): """ Cria uma matriz vazia :param rows: número de linhas da matriz :param cols: número de colunas da matriz :return: matriz preenchida com 0.0 """ M = [] while len(M) < rows: M.append([]) while len(M[-1]) < cols: M[-1]...
7ab47a7a5b23d37ae5ec8e07278adf323638b6e9
685,466
import logging def check_element_balance(elements, species, reaction, limit=1e-5): """Check the given reaction for their element balance.""" elm_sum = {key: 0.0 for key in elements.keys()} for spc, spc_nu in reaction.reactants.items(): for key in species[spc].thermo.composition: elm_s...
fbc760606a2d6cb2f1c9108c8896e44811f22cbd
685,467
def create_column_index(table, colindex): """creates index from column value to corresponding table row""" return dict([(row[colindex], row) for row in table])
f2a46d2750e1f1d134256c7a76f875bafb29fb30
685,468
async def get_queue_list(queue_array: list) -> str: """Return the queue list using the queue array.""" queue_list = "" for index, member in enumerate(queue_array, start=1): name = member["name"] current_turn = member["current_turn"] if current_turn: queue_list += f"<b><i...
8521d46ee7b223ce54e34c05daa516dcb14c2002
685,470
def get_domain_class_attribute_names(ent): """ Returns all attribute names of the given registered resource. """ return ent.__everest_attributes__.keys()
4ba022426397270942ce176b97a655c63f647c1d
685,471
def delete_last_bracket(unreadable_json_str) -> str: """最後に余計な閉じかっこが存在する場合に削除する""" reversed_list = list(reversed(unreadable_json_str)) for index, char in enumerate(reversed_list): if char == "}": del reversed_list[index] break # 削除する閉じかっこは一つだけ valid_order_list = reversed...
8481cace0261531f48cd437f3c3d7e96134243e0
685,472
import functools def replacedby(g): """Replace the function with another function.""" def wrapper(f): @functools.wraps(f) def wrapped(*args,**kw): return g(*args,**kw) return wrapped return wrapper
17f3804b0f96d8b6871a4af6972918e13adba4f0
685,473
def train_step(sess, model): """Train step.""" ce = model.train_step(sess) return ce
a6aaccfa296c42d3fc48e9bce386b6879c9ddd5e
685,474
def load_descriptions(doc): """ Loads description (Captions) :param doc: Caption text files :return: Captions mapped to images """ mapping = dict() # process lines for line in doc.split('\n'): # split line by white space tokens = line.split() if len(line) < 2: ...
77d8e960a46019bd2e803c9b54785ce984cc581b
685,475
def run_calc(calc, year, var_list): """ Parameters ---------- calc: tax calculator object year: year to run calculator for var_list: list of variables to return waited total of """ calc.advance_to_year(year) calc.calc_all() totals = {} for var in var_list: totals[var]...
a779fd27eef261a5ac346e7818216dee0e094eab
685,476
def find_mint_method(ABI): """ Tries to find the 'mint' method in ABI """ candidates = [ c for c in ABI if c.get("stateMutability") == "payable" and c.get("type") == "function" and "mint" in (c.get("name") or "").lower() ] print("mint candidates:...
259ccaebacf6a0ed24389ff312dc3bea5fb215a6
685,477
def split_by_max_length(sentence, max_text_length=128): """Standardize n_sentences: split long n_sentences into max_text_length""" if len(sentence) < max_text_length: return [sentence] split = sentence.split() new_n_sentences, text = [], [] for x in split: support_text = " ".join(...
4754d572aa1fea3b88274a75993461b89dc0dd75
685,478
def __format_class(origin_class, class_map): """ クラスをclass_mapに従って変換する """ if len(class_map) == 0: return origin_class for class_data in class_map: if origin_class in class_data['sub']: return class_data['label_id'] raise RuntimeError()
deab14d2617b15cf53b41fdd1010efd4d8e9ddf2
685,479
def apply_operators(obj, ops, op): """ Apply the list of operators ``ops`` to object ``obj``, substituting ``op`` for the generator. """ res = obj for o in reversed(ops): res = o.apply(res, op) return res
6abc7f7e9daf77d8f6d4480239361cfa9a139387
685,480
def batched_index_select_nd_last(t, inds): """ Index select on dim -1 of a >=2D multi-batched tensor. inds assumed to have all batch dimensions except one data dimension 'n' :param t (batch..., n, m) :param inds (batch..., k) :return (batch..., n, k) """ dummy = inds.unsqueeze(-2).expand...
b90f0f07e666837c8abf818754f30111b26768fe
685,482
def gq_get_vertex_user(user): """Create the gremlin query that returns a Vertex for a user given its uuid """ query = "g.V().hasLabel('user').has('uuid', '{}')".format(user.uuid) return query
52509c27280a3e0fd4eb57b44fe5fbec8c0c3b20
685,483
def remove_duplicates(list_with_duplicates): """ Removes the duplicates and keeps the ordering of the original list. For duplicates, the first occurrence is kept and the later occurrences are ignored. Args: list_with_duplicates: list that possibly contains duplicates Returns: A list ...
e72e26e69f9476669906ba2aa7864cec9eaf64d4
685,484
import torch def negate_bounds(bounds: torch.Tensor, dim=-1) -> torch.Tensor: """Negate a bounds tensor: (1 - U, 1 - L)""" return (1 - bounds).flip(dim)
f04725b6a6cc4b1a612f801c1c6252845c4a3a8e
685,485
import torch def padding_tensor_kspaces(batch): """ :param sequences: list of tensors :return: """ sequences = [item[2] for item in batch] max_0 = max([s.shape[0] for s in sequences]) max_1 = max([s.shape[1] for s in sequences]) max_2 = max([s.shape[2] for s in sequences]) out_tens...
d6cad68f267239584893a55920ca984cba2e9a7a
685,486
import glob def get_all_file_path_in_dir(dir_name): """ dir内の全てのファイルのパスを取得する関数 Args: dir_name (str): directory name Returns: All file path name str list """ all_file_path_list = [r for r in glob.glob(dir_name + '/*')] return all_file_path_list
87cfac66ea4d3d52fff7222f3b5363026fac213c
685,487
def always_ok(exec_op): """ This decorator leaves the original method unchanged. It is used as permissions checker when the request is a superuser_request """ return exec_op
de5c1b16ec68c8187d82474f120332e996ee9711
685,488
import ast def check_funcdefaultvalues(node): """ Returns if there are function definitions with default values. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_FunctionDef(self, node): self.gener...
d30f8c9f6115fb7a000c024c27e3cff108529a18
685,489
def adjust_height(v1, height): """ Increases or decreases the z axis of the vector :param v1: The vector to have its height changed :param height: The height to change the vector by :return: The vector with its z parameter summed by height """ return (v1[0], v1[1], v1...
5cc53853a6e93ec5c046b9937fceb6ca9262619d
685,490
import torch def rgb_to_hsv_torch(image: torch.Tensor) -> torch.Tensor: """ PyTorch implementation of RGB to HSV color conversion """ # https://torchgeometry.readthedocs.io/en/latest/_modules/kornia/color/hsv.html#rgb_to_hsv # https://en.wikipedia.org/wiki/HSL_and_HSV#General_approach # https://stacko...
f093b16c066b5f46dbeacac103ac024e5e751849
685,491
from typing import Tuple def pool_out_shape(h_w: Tuple[int, int], kernel_size: int) -> Tuple[int, int]: """ Calculates the output shape (height and width) of the output of a max pooling layer. kernel_size corresponds to the inputs of the torch.nn.MaxPool2d layer (https://pytorch.org/docs/stable/genera...
63a1b3809aad24c5a4f652211bec6290486192e6
685,492
import argparse def parse_arguments(): """ Parses the command-line arguments passed to the assembler. """ parser = argparse.ArgumentParser( description="Assembler for the Tandy Color Computer 1, 2, and 3. See README.md for more " "information, and LICENSE for terms of use." ) p...
c3e1eedcad0ad7cdaa8ac9fca60f90258569be44
685,493
import logging def _schedule_coeff(args, lr): # def _schedule_coeff(args, lr): """ Adjust the landscape coefficient """ if args.landmark_loss_coef_scheduler == 'inverse_lr': coeff = (args.learning_rate - lr + args.learning_rate_min) * args.landmark_loss_coef logging.info(f"landmark loss coeffi...
b3eee3db91284fe9b67bda5f52272f36e6cdb415
685,494
import base64 def encode_array(array): """Encodes array to byte64 Args: array (ndarray): array Returns: byte64: encoded array """ # Encoding of 3darray to save in database encoded_array = base64.b64encode(array) return encoded_array
8c5fde55762ed3520de48bf5197012f1ac925192
685,495
def make_blocks(N, bs=100000): """ creates block starts and stops of length bs """ starts = list(range(0, N, bs)) if N - starts[-1] < bs/4: del starts[-1] stops = starts[1:] + [N] return zip(starts, stops)
3479264ecf17b6c9bc4f9ed8bc7c3ac4dacf26af
685,496
import re def clean_arabic(word: str): """ This is to handle the strange Arabic text in Ontonotes, which has many more diacritics than most Arabic text found "in the wild". """ diacritics = [chr(1614),chr(1615),chr(1616),chr(1617),chr(1618),chr(1761),chr(1619),chr(1648),chr(1649),chr(1611),chr(161...
73bb641131c37835f7c84fecfd34aeaa4bb469ba
685,497
def truncate_errors(errors, limit=float("inf")): """If limit was specified, truncate the list of errors. Give the total number of times that the error was found elsewhere. """ if len(errors) > limit: start1, end1, err1, msg1, replacements = errors[0] if len(errors) == limit + 1: ...
4c70280185a12d1a7acb9a39d8dda2dde6ccc623
685,498
def _create_facilities(handler, facilities=None): """Initialize a facilities dictionary.""" if facilities is None: facilities = dict() for facility in handler.facility_names.keys(): if getattr(handler, 'LOG_%s' % facility.upper(), None) is not None: facilities[facility] = handler...
51f273005d2c685101366c0c5405568a19ffb925
685,499
def generate_vertice_faces(vertices, faces): """Return the list of faces belonging to the given vertices.""" vertice_faces = [[] for _ in vertices] for i, face in enumerate(faces): for vertice in face.vertice_ids: vertice_faces[vertice].append(i) return vertice_faces
fb92d4946302baeeb31a0871d8e64127300000c3
685,500
import os def change_dir(path, new_dir): """ Returns path but with new_dir instead of its directory """ return os.path.join(new_dir, os.path.basename(path))
0431a4678ec106069d06df66dbaac4de62147593
685,501
import os import shutil def copy_creds(top, target_dir): """ Copy credentials """ return fname = "config_gs.json" src = os.path.join(top, "..", "..", fname) dst = os.path.join(top, target_dir, fname) shutil.copyfile(src, dst) return 0
f538e5c442149873e39ce671dd3d09f22c058ff4
685,502
def isRequest(code): """ Checks whether a code indicates a request. :param code: code the code to check :return: True if the code indicates a request """ return 1 <= code <= 31
6bb336aee1393e296d0bd06d70f12d8d6b64ecb1
685,503
import json import requests def github_api(owner, repo, subpath, data=None, username=None, password=None): """ Takes a subpath under the repository (ex: /releases) and returns the json data from the api """ api_url = 'https://api.github.com/repos/%s/%s%s' % (owner, repo, subpath) # Use Github Authenticati...
e853acf1432ac926cbb510fdda3dc24cd2d43eda
685,504
import re def uc_sequence(x: str)-> str: """ Input: String Output: String Check if there is any word exists with first alphabet uppercase and else lower case. """ c = re.findall("[A-Z][a-z]*",x) if c: return "Yes" else: return "No"
2e5e3d118aa1cb2742a2803b7a3023911dc51e7a
685,505
def set_bit(a, order): """ Set the value of a bit at index <order> to be 1. """ return a | (1 << order)
e67f538dba4fc93d2a9511a116e7f30fbc16d0a2
685,506
def ensure_iterable(obj): """ Ensures that the object provided is a list or tuple and wraps it if not. """ if not isinstance(obj, (list, tuple)): obj = (obj,) return obj
f26dce0b19f5428179e0b8af058e675f81540edd
685,508
def parse_events(response_json): """ Build the events list """ fault_dict = {} for res_out in response_json['result']['faults']: if res_out['resolved'] is False: flt_details = res_out['details'] flt_node = res_out['nodeID'] flt_drive = res_out['driveID'] ...
f853df1802f2f09d31d2c11daa612ec99654f661
685,509
import random def random_rgb(): """ Generate a uniformly random RGB value. :return: A tuple of three integers with values between 0 and 255 inclusive """ return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
3ef820fbf08cc28ebccf1d8758e8649afe628e90
685,510
import string def isValidListOrRulename(word): """test if there are no accented characters in a listname or rulename so asciiletters, digitis, - and _ are allowed """ allowed = string.ascii_letters + string.digits + '-_' if not word: return for w in word: if not w in allow...
db040add03c4778f9b0e3482f8a98618d8787bb9
685,512
def gen_matchups(n): """ generate seed pairs for a round >>> gen_matchups(4) [(1, 4), (2, 3)] """ seeds = range(1, n+1) games = [] for i in range(n/2): low = seeds[i] hi = seeds[-(i+1)] games.append((low, hi)) return games
5fa0ba698764f8fcc4685d1c84a3679985217f3f
685,514
import re def regex_token_replace(sentence: str, token: str, replacement: str) -> str: """ replace all occurrences of a target token with its replacement :param sentence: input sentence to be modified :param token: target token to be replaced :param replacement: replacement word for the target tok...
ac63e2a85be1b4f05b98be8b6f42d1eb8f334961
685,515
def run_xar_main(**kwargs): """ Constructs the run_xar_main given the template arguments. If the {function} template argument is present, then the entry point {module}.{function}() is executed as main. Otherwise, {module} is run as the main module. """ run_xar_main = """ from __future__ impo...
7d9e51e95f0985902b468aa79e975c02f5dbdb0f
685,516
import sys def is_string(var): """For Python2/3 compatiblity""" if sys.version_info >= (3, 0): return isinstance(var, str) else: return isinstance(var, basestring)
bc850cde0b428b7057f6ac6f54a63eabda45f045
685,517
def build_catalog_url(account: str, image_digest: str) -> str: """ Returns the URL as a string that the policy engine will use to fetch the loaded analysis result from the catalog :param account: :param image_digest: :return: """ return "catalog://{}/analysis_data/{}".format(account, image_d...
cdcdd003e05c5d51ddcd7e05a6279897a226fd59
685,519
import copy def select_labels(dataset, label): """Return teh subset of the data with a specific label.""" dataset = copy.deepcopy(dataset) filt = dataset.targets == label dataset.data = dataset.data[filt] dataset.targets = dataset.targets[filt] return dataset
00b1610c6a93fe7293a4dd6f80d65a8283d368f1
685,520
def get_two_numbers(): """Returns two whole numbers entered by the user. () -> (whole number, whole number) """ while True: try: num_1, num_2, *etc = input('\nPlease, enter two whole numbers separated by the space: ').split() num_1, num_2 = int(num_1), int(num_2) ...
d6f51a53d3c0fbdba8e9934287982567e2a8dffd
685,521
def location(host=None, user=None, path=None, forssh=False): """Construct an appropriate ssh/scp path spec based on the combination of parameters. Supply host, user, and path.""" sep = "" if forssh else ":" if host is None: if user is None: if path is None: raise Valu...
b729d6a90fbe35954712a12e6993fbe70f7da408
685,522
def gradient_descent(learning_rate, parameters, gradients): """ Vanilla gradient descent. :param learning_rate: Learning rate. :param parameters: Additional parameters. :param gradients: Respective Gradients. :return: Update. """ updates = [(p, p - learning_rate * g) for p, g in zip(para...
878798d6c6698906a04c7e486c57e6d7295877ae
685,523
def getHistSeparation( sig,bkg ): """Compare TH1* S and B -- need same dimensions Copied from : https://root.cern.ch/doc/master/MethodBase_8cxx_source.html#l02740 """ assert sig.GetNbins()==bkg.GetNbins() separation = 0 nbinsx = sig.GetNbinsX() nbinsy = sig.GetNbinsY() integral_s =...
7a9b36ae48296921e4a0f97d28d2e89642ca7619
685,524
def has_common_element(a, b): """ Return True if iterables a and b have at least one element in common. """ return not len(set(a) & set(b)) == 0
d684000f89807e15150fc591e5ad1a5c9c459ada
685,525
import inspect def my_caller(up=0): """ Returns a FrameInfo object describing the caller of the function that called my_caller. You might care about these properties of the FrameInfo object: .filename .function .lineno The `up` parameter can be used to look farther up the...
e4ef0d3ab6bd4aac43d931d2c23bb84cfe5cce38
685,526
def anomaly_filter(distributions, configuration): """ Select those distributions that are close to the given patterns. :param distributions: computed distributions sum :param configuration: loaded application configuration :return: True if some distribution is similar, False otherwise """ #...
0a7a0bec7efe30797b3f9b40194eeed9d74364d7
685,527
def if_draw_surface(surf): """ This function determines whether a surface must be mapped to the 2D plane or not depending on the orientation of the surface. This function works hand-in hand with surface2poly and is dependent on how it is implemented. """ return (surf[1] - surf[0]).cr...
440f4f8c28c3fee2543ef946d70e6907c8ad65ff
685,528