content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import pprint def get_data_from_webhook_json(res): """ 从wehbook反推给我们的数据中获取需要的信息并格式化输出 :param res: :return: """ push_branch_info = res.get("ref") push_branch = push_branch_info.split("/")[-1] commit_info = res.get("commits")[0].get("message") author = res.get("commits")[0].get("auth...
988de5f857aaed1953c1f9866cb92e00839f298f
635,376
import os import yaml def get_yaml(): """ 解析 yaml :return: s 字典 """ path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '_config.yaml') try: with open(path, 'r', encoding='utf-8') as file: config = yaml.safe_load(file) # config = yaml.load(file, Lo...
a16563d8b25a674368bfa0d4e3611f913b83933c
635,377
from typing import Tuple def extract_start_stop(reading : str) -> Tuple[int, int]: """ Parameters reading - of form '19.6 C', '99%', 'South East" returns distance from the end of the reading the distance from the end of the units """ if type(reading) != str: readi...
262f15f2ad2ae39404e7e3cc2474d6a683a09edc
635,378
import random def random_number(): """ """ return random.randrange(100000, 999999)
4b5dd172be00674fc19f48e918a43f72c699322b
635,379
def pipe_Do(Di, WT): """Calculate pipe outer diameter, given the pipe inner diamater and wall thickness. """ Do = Di + 2 * WT return Do
2c044187e3b8700cc3c7524d8b0524639a93c5dd
635,380
def compute_asdp_size(manifest): """ Computes the total size of the ASDP from the manifest entires Parameters ---------- manifest: list list of dicts containing the manifest entries Returns ------- asdp_size: int the total size in bytes associated with "asdp," "validate...
ff92053b5c8022e76ff9973be928a9e32a678e90
635,381
def get_nav_context(): """Using get nav context method is not a reliable as changing the settings! This will change all of the views with this context, but will not change other views like the login page. Use the settings to change the login page. """ context = {'site_name': 'demo_app', 'PRIMARY_COLOR':...
14f858484ac38c6a8a57d10b6e3275b0bf4d1d9a
635,383
def check_sim_running(env): """ determines if a sim is already running for a given environment """ try: fname = './.virl/{}/id'.format(env) with open(fname, 'r') as f: sim_name = f.read() if sim_name: return sim_name else: return None ...
f8900fc63ab45c6023a537a8d530239b32b1f708
635,384
def decode_label(label): """Spit the label to return a dict with the main information""" label_dict = {"full": label} label_split = label.split("_") # Decode Lamination label if len(label_split) > 0: # Label like "Stator-X" label_dict["lam_label"] = label_split[0] if "-" in ...
acdc06bdab3dcfff9922d9a503e7d79c4db66633
635,385
def general_acquisition_info(metadata): """General sentence on data acquisition. This should be the first sentence in the MRI data acquisition section. Parameters ---------- metadata : :obj:`dict` The metadata for the dataset. Returns ------- out_str : :obj:`str` Outpu...
6836afb1670c22bb718f34e75bc11c24a45ad0aa
635,386
import logging import logging import requests def get_sra_download_url(run_accession, protocol="fasp"): """Try getting the sra-download URL from CGI endpoint""" # Ex: curl --data "acc=SRR6718414&accept-proto=fasp&version=2.0" \ # https://www.ncbi.nlm.nih.gov/Traces/names/names.cgi cgi_url = "https:/...
6559dfffe4589ecbe6f89d3150e085d0e0aee0ac
635,387
def write_source_commands(): """Generate object files""" text = """%.o: %.cc \t$(CXX) -c $(CFLAGS) $^ -o $@ %.cu.cudao: %.cu.cc \t$(NVCC) -c $(CFLAGS_NVCC) $^ -o $@ %.cudao: %.cc \t$(CXX) -c $(CFLAGS_CUDA) $^ -o $@ """ return text
01d2e874a1776660c36b49697e2f03c9ee49f412
635,388
def get_bulb(zid, bulbs): """Retrieve a bulb by its zid from a list of Bulb objects.""" for bulb in bulbs: if bulb.zid == zid: return bulb return None
19e579e2394cbbc30553f1a9432e1e1871c3bbc6
635,389
def _choose_from_enum(en, request_text="Please choose from following options:", default_number=0): """ show a menu for the user to choose from different enum possibilities :param en: enum to choose from :param request_text: request to be shown to the user :param default_number: default enum value to...
97838fb6f70522f6fc63a74aabc6a70cd6c71019
635,390
def GetOrcaOutXyz(fn): """ Get xyz from Orca out file. :param fn: filename :return: xyz data set """ f = open(fn, 'r') content = f.read() f.close() target = content.rfind("CARTESIAN COORDINATES (ANGSTROEM)") target += 68 endtar = content[target:].find("---------------------...
dd14c2be48c675e6afc0707c9c23123fc7ef91c8
635,391
def echo(app, need, needs, text, *args, **kwargs): """ .. versionadded:: 0.6.3 Just returns the given string back. Mostly useful for tests. .. code-block:: jinja A nice :need_func:`[[echo("first")]] test` for need_func. **Result**: A nice :need_func:`[[echo("first")]] test` for need_f...
a2a95cdcb925a3c981f2c9348529d4ce48990b8a
635,392
def _get_proto_name(proto): """Get the value of a proto's name field or return the proto type name. Args: proto: Proto to query. Returns: Human readable name of the proto. """ if 'name' in proto.DESCRIPTOR.fields_by_name: return proto.name return proto .DESCRIPTOR.name
dafd11d1b42c86a29bf273fe22b02b9257b74fcf
635,393
def get_func_name(func): """ 获取函数名称 :param func: 传入函数 :return: """ try: func_name = str(func.__name__) + '()' except AttributeError: func_name = str(func) return func_name
18ada106e21fae1684f46e4ab91a911ae232f027
635,394
import sys def _get_new_option(): """ Print \n--> and wait for input """ print("\n---> ", end='') sys.stdout.flush() try: selection = input() except EOFError: selection = '<empty>' return selection
5940312c7c843abf099ac02bd276d29681617c02
635,395
def cnv_filter(gd_bt, cnv_path, cnv, max_cov): """ Exclude GDs based on overlap by common CNVs (while matching on CNV type) """ gd_wcov = gd_bt.coverage(cnv_path) gd_bt_filt = gd_wcov.filter(lambda x: x[4] != cnv or float(x[-1]) <= max_cov).\ cut(range(len(gd_bt[0].fields)...
1c505c70ba33da51cedb1123958b3a5dac20543d
635,396
import torch def gpu_mem_allocate_mbs(n, fatal=False): """ Try to allocate n MBs on the current device. Return the variable holding it on success, None on failure. fatal=True will throw an exception on failure to allocate (default is False). """ # don't try to allocate less than 6MB as it'd...
ad44279b4e01c614057f680cea2527442bbd4107
635,397
from typing import List import os import subprocess import sys def upload_files(target_uri: str, files: List[str]): """ Uploads regular PDFs or attachments to their correct place on the aclweb server. """ for file in files: os.chmod(file, 0o644) file_list = " ".join(files) command = ...
5c1d5d29dd06e4c1de420a963f3c6e35c86a445f
635,398
def find_triggers(labels): """ :param labels: ['B-Conflict:Attack', 'I-Conflict:Attack', 'O', 'B-Life:Marry'] :return: [(0, 2, 'Conflict:Attack'), (3, 4, 'Life:Marry')] """ result = [] labels = [label.split('-') for label in labels] for i in range(len(labels)): if labels[i][0] == 'B...
c38f192bebc6252baf01517d7522404157d3a6d5
635,399
def all_combinations(l): """returns all the combinations of the sublist in the given list (i.e. l[0] x l[1] x ... x l[n]).""" if len(l) == 0: return () if len(l) == 1: return [(a,) for a in l[0]] r = [] for a in l[0]: r.extend((a,) + b for b in all_combinations(l[1:])) return r
d962b76270e9aafeb312c882f2f9f1750fb68eff
635,400
def calculate_total(books): """ Returns the minimum cost of books for any conceivable shopping cart """ # We store the discounted price of occurences of each type d = { 0: 0, 1: 800, 2: 1520, 3: 2160, 4: 2560, 5: 3000 } total_cost = 0 tota...
56b99e54c9fb8b56f3012e809c792e90f63f58d0
635,401
from typing import Sequence def wrap_with_any_of(schemas: Sequence): """Take multiple JSON schemas and combine them using the `anyOf` JSON schema notation""" if len(schemas) == 1: return schemas[0] else: return {"anyOf": schemas}
6379b991dad8f4c989d40879e496e45573bd57e1
635,402
def get_neighbours(x, y): """Get neighbours for an x, y location Args: x (int): x coord y (int): y coord Returns: List: list of tuples with x,y coords """ neighbours = [] neighbours += [(x-1, y)] neighbours += [(x, y-1)] neighbours += [(x, y+1)] neighbours += ...
f39155b3ab26a757c802fdefb6237f3115c57836
635,403
def get_roots(pred_calls, sort_key = str): """Returns list of all roots of the given predicate calls. >>> aststs = functools.partial(ast, sts) >>> preds = list(map(aststs, [sl.tree("x"), sl.list("h"), sl.tree("a"), sl.list.seg("h", "t")])) >>> get_roots(preds) [a, h, x] >>> get_roots(preds, str...
01e3ade08c4b4937c08688e812ea8f44fd7b567e
635,404
def get_index_dictionary(filepath, delimiter='\n'): """Generates a dictionary of words to their respective indices. Args: filepath (str): File path. delimiter (str, optional): Delimiter separating words. Defaults to '\n'. Returns: Dictionary mapping words to their indices. """ ...
687cd9d7996ddff3a9223373b013249fec0574ab
635,405
def _match_request(http_request, stored_request): """Determines whether a request is similar enough to a stored request to cause the stored response to be returned.""" # Check to see if the host names match. if (http_request.uri.host is not None and http_request.uri.host != stored_request.uri.host): ...
f4373d6207814d62e645e95dc2199d7234a0e742
635,406
def is_same_class(obj, a_class): """ type(obj) == a_class (True) """ return type(obj) is a_class
aeb013a2ca60570a4ebeba79a601d5af11eee069
635,407
import functools def listify(fn=None, wrapper=list): """ A decorator which wraps a function's return value in ``list(...)``. Useful when an algorithm can be expressed more cleanly as a generator but the function should return an list. Example:: >>> @listify ... def get_lengths(i...
2ec1e9e873535b456d69d1745dac0e50ff675f79
635,408
import math def ddpg_state_rescale(state, state_num, goal_dir_range=math.pi, linear_spd_range=0.5, angular_spd_range=2.0): """ Rescale DDPG states to make them same scale with SNN input :param state: single ddpg state :param state_num: number of states :param goal_dir_range:...
2d8f64ccd3cea1d49e83aa11fa65c4b0671006de
635,409
def boards_filter(boards, resource): """Фильтр табло""" result = [] for board in boards: for attr, val in board.items(): if attr == 'resources' and resource in val: result.extend([board]) return result
12de6f4ff4282fe4bb59b5543782e6c5558227fa
635,410
def qname_and_mate(qname): """ Removes mate sequence from qname. qname: original qname Return value: tuple (qname, mate sequence, which could be empty) """ split_name = qname.split('\x1d') mate = split_name[1].rpartition(':') split_name[1] = mate[0] + ':' return ('\x1d'.join(sp...
c55d4b4ca4814c17bd39fac98bc916025697114b
635,411
def new_file_path(photo_date): """ Get the new file path for the photo. An example would be 2019/January/31st :param photo_date: The list for the date that is supplied from the exif data :return: Array of all the new file paths """ if len(photo_date) == 3: month = photo_date[0] d...
579e903e073dae027057f2462e2e05198771a704
635,412
def flow_number_poly(cappa): """Calculate flow number for a given pump's typical number. The polynomial has been calculated applaying the curve fitting at nodes cappa .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1 1.2 phi .080 .093 .100 .110 .120 .130 .140 .150 .160 .165 .170 weights ones(cappa)...
56dcf6cfee4a8a6110f6b29a934e8acfb35b20b5
635,413
def is_missing_atom_map(molecule): """ Checks if any atom in molecule is missing a map index. If even only one atom is missing a map index will return True Parameters ---------- molecule: oechem.OEMOl Returns ------- bool """ MISSING_ATOM_MAP = False for atom in molecule.Ge...
617b4fb51c777daf89d4ce0c8b6ba71752306dad
635,414
import sys import os def _guess_caller_path(): """Since we are a module, we can't use ``__file__`` to determine a starting directory for the closest environment search. But we can try with the ``sys.argv[0]``, if the value has not been manipulated before a call to envie. It should contain a path to th...
f90b7168d8fb8fb9fe0b7a577eb951f406fbca5e
635,415
def get_directory(instance, filename): """Determine the upload_to path for every model inheriting Attachment.""" org = instance.organisation.organisation_name app = instance._meta.app_label # noqa return "{}/{}/{}/{}".format(org, app, instance.__class__.__name__.lower(), filename)
8cc0f78a34fcbfa381b88bf9bdfabfca492f5635
635,416
def stringify(hitObject): """Turns a TaikoObject into a string that TITaiko understands""" ret = str(int(hitObject.offset)) + ':' + str(hitObject.objType.value) # Add a third parameter if the object is a long note if (hitObject.length != None): ret += ':' + str(int(hitObject.length)) return ret
1fbd8d57377fe30975c1535cc4c6a3b9b31438d9
635,417
import torch def encode(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_pri...
9e8b8b413cc0a7ff5b5d9054b1c1a2e33e2d0815
635,418
def score_the_line(matches, normalizing_stats = [71.73, 26.70, 254.71, 94.19], angle_weight=1.0, length_weight=1.0, num_lines=None): """ Scores the lines striking a balance between angle (vertical lines preferred) and length (long lines preferred). The scoring method is based on a composi...
a59048ff5d5807a4355f0621b8caf4741aa70f56
635,419
def errors_to_string(errors: dict) -> str: """ A function to flaten out the default error object from serializer classes to a string """ error_string = [] for _, error in errors.items(): error_string.append(error[0]) return "\n".join(error_string)
76a51e3c2936c5846bf04cef675bab420c3eda7e
635,420
from typing import List def process_data(data: str) -> List[List[int]]: """Parse the raw data. Return list of rows, each row item is integer. """ rows = [row.split("\t") for row in data.strip().split("\n")] return [[int(item) for item in row] for row in rows]
25f374a649cb49c8ea932a0ffa3bf4fbf5917534
635,421
import time def datetime2utc(dt): """ Sends a :class:`datetime.datetime` object. Returns :class:`int` time value. :param dt: :class:`datetime` object """ return int(time.mktime(dt.timetuple()))
067cdc8b68db27f71bbc32022ddb3c61bc098e20
635,422
def product(l): """Multiply together the elements of a list.""" prod = 1 for x in l: prod *= x return prod
1f0a8ddbff84b5fc01ff4e974b39b3b0b5f8695d
635,423
def expected_errors(snippets): """Get and normalize expected errors from snippet.""" out = snippets.pop(0) assert out.startswith("[GraphQLError(") return " ".join(out.split()).replace("( ", "(").replace('" "', "")
57ff4693779ef221daf400d0b2fef68bfbd4d581
635,424
def my_hash(text): """Create unique hash from name. Used to keep track of type names in different contexts. Keyword arguments: text -- string to hash """ return hash(text)
a3fabebeb5eaf7098cde224281b7985b6dc0b607
635,425
def twoStrings(s1, s2): """Compares two strings to find matching substring using set.""" a = set(s1) if len(s1 >= s2) else set(s2) for i in s1: if i in s2: return "YES" return "NO"
e2d20480c9b8c06f0b5c311b1a0e612d3ca20bea
635,426
import logging import os import subprocess import shutil def build(env, need, needs): """ Builds a sphinx-project in demos/ and copies the build-result to the current sphinx project build folder under "demos/demo-id". """ log = logging.getLogger(__name__) demo_path = os.path.abspath(os.path.j...
eb59bc67581c5b00444ccd5fd480a24cb98bc57e
635,428
def build_clnsig(clnsig_info): """docstring for build_clnsig""" clnsig_obj = dict( value = clnsig_info['value'], accession = clnsig_info.get('accession'), revstat = clnsig_info.get('revstat') ) return clnsig_obj
2518ea5a4de17cffeed0067d298f0a6ac85f32ec
635,429
def avoids(w, s): """ Check if the word contains any of the characters specified in a string. Return True if it does not """ for l in w: if l in s: return False return True
fc0bcc308cac9c7abef00c66116e3698f55afbfa
635,430
def check_settings_changed(updated, existing): """Since updating the settings requires closing the index, we don't want to do it unless it's really needed. This will check if all the updated settings are already in effect.""" if not isinstance(updated, dict) or not isinstance(existing, dict): re...
bf19420a02ac6a86ae39d0c04fa4aff5b0dc5e97
635,431
def RT_BIT_64(iBit): # pylint: disable=C0103 """ 64-bit one bit mask. """ return 1 << iBit;
5ee360af2dedb5499214aaf06b3460ca13ed0e68
635,432
import time def dateToDBFmt(strVal, fromFmt="%m/%d/%Y"): """Convert a date from the specified fromFmt (a string accepted by time.strptime) to "yyyy-mm-dd", the format used by databases. """ try: dateTuple = time.strptime(strVal, fromFmt) except ValueError: raise ValueError("%s not ...
38acc3f2c66b803050dd63ef77408623fa51b7ae
635,434
def add_or_rule(cmd, client, resource_group_name, account_name, policy_id, source_container, destination_container, min_creation_time=None, prefix_match=None): """ Initialize rule for or policy """ policy_properties = client.get(resource_group_name, account_name, policy_id) ObjectR...
dcc662439d318d3c652d84a2446e4c2484b79c14
635,436
from typing import Set def is_new_hash(hash_: str, hashes: Set[str]) -> bool: """Check if current hash is still in set of unique hashes and remove if true.""" if hash_ in hashes: return False else: hashes.add(hash_) return True
9824d2610396ed03c5c0868578351d530f9ca936
635,437
def always_true(): """Always return ``True``.""" return True
2b8dc756bf0770ae2484fd722774426a99c1e9b6
635,438
def has_test(args): """Returns if some kind of test data is given in args. """ return (args.test_set or args.test_source or args.test_dataset or args.test_stdin or args.test_datasets)
bb773c87f4bc3e046e50a49a1003714fe10a2cf2
635,439
import os def islinux(): """is the current platform Linux?""" (sysname, nodename, release, version, machine) = os.uname() return sysname == 'Linux'
52f5dd13bd0af389788c0a749fdd66580b58e8a8
635,440
def is_tachycardic(age, heart_rate): """Determines if a given heart rate indicates tachycardia Every time a new heart rate is added to the server, it is necessary to ensure that the given heart rate does not indicate tachycardia in that given patient. This function reads in an age and a heart rate,...
bb7227b3ebcceb014cb064710a23001f3b7e8a50
635,441
def is_valid_path(path_obj, path_type): """Verify path_obj is valid by type, returns bool.""" valid_path = False if path_type == 'DIR': valid_path = path_obj.is_dir() elif path_type == 'KIT': valid_path = path_obj.is_dir() and path_obj.joinpath('.bin').exists() elif path_type == 'IMG': valid_path ...
2c30072e5ed34b3c0e959703e0934c79d93dc006
635,442
def partitions_conversion(data): """ Convert the start or length data in the partition table through multiply 1024 * 1024 and return the data. :param data: start or length data :return : """ if data == '0': return 0 elif data.endswith('M'): return int(data[0:-1]) * 1024 *...
55c8330165355b70dc660b07681b4865c66cdb42
635,443
def suppress_value(valuein: int, rc: str = "*", upper: int = 100000000) -> str: """ Suppress values less than or equal to 7, round all non-national values. This function suppresses value if it is less than or equal to 7. If value is 0 then it will remain as 0. If value is at national level it will ...
fd453134fe64d913a5c54d34982aa8c4d0c05d69
635,444
def get_policy(et, policy, match_fields, i): """Recursively determines matching policy""" if(i == len(match_fields)): return policy curr_policy = None et_attr = str(getattr(et, match_fields[i])) if et_attr in policy: curr_policy = get_policy(et, policy[et_attr], match_fields...
cd22657648102f26fd5923878389e52b9bfc7bb7
635,445
def get_cg(list_of_coordinates): """gets CG of list of coordinates""" l = len(list_of_coordinates) if l == 0 : return [0, 0] s = [0.0, 0.0] for coor in list_of_coordinates: s[0] += coor[0] s[1] += coor[1] return(s[0]/l, s[1]/l)
d5d398677325f925d767219684326db344b56cc3
635,446
def lt(x, y): """ Implementa o operador de "menor que" """ return x < y
525afeaedbd779a09dbb6171596ec32c3c74f3de
635,447
def _switch_wos(): """ in case db_src='wos', use these specifications args: None returns: wos: the wos specifics """ # define web of science specifics wos = { 'columns': [ 'TI', 'AU', 'AF', 'RI', 'OI', 'SO', 'PY', 'VL', 'IS', 'TC', 'Z9', 'CR',...
b352a6d6ef4dd95698e1eb9161d0ec5251c239b0
635,448
from typing import Optional import click def _get_delimiter(item: str) -> Optional[str]: """ Returns the delimiter found in the item if any. It may raises an error if delimiter starts or ends and item or if there is more than one delimiter in the item. :param item: the item to determine delimiters. ...
d7408bf52ac48a595c0f46f53c9c95b11c4cae19
635,449
def _route2url(route): """Convert host from openshift route to https:// url""" return f"https://{route['spec']['host']}"
4690d8900f251e5badf8a742a309d51b576be52b
635,450
def search_array_dict(array, id_name, id): """指定キーで配列から検索する - Search from the array with the specified key Args: array (arr): array id_name (str): key id (str): id Returns: dict: array item """ for item in array: if item[id_name] == id: return it...
8b716e0522ed4a4a0637a4f1d7e3832fea8543ef
635,451
def getUsersWithCompetencies(categories, usercompetencies): """ Lists competences and their corresponding user IDs and returns the user ID matching the needed competence :param categories: Needed competence category :type categories: list :param usercompetencies: User IDs and their competences ...
e693942f676fb608431720bd5c1d39e130c15c85
635,452
def _arg_olen1(dvi, delta): """Optionally signed, length *delta*+1 Read *delta*+1 bytes, returning the bytes interpreted as unsigned integer for 0<=*delta*<3 and signed if *delta*==3.""" return dvi._arg(delta + 1, delta == 3)
d5073c0feb12289c07b8c19b556dbc29c0aff10f
635,453
def BandwidthToString(bandwidth): """Converts a bandwidth to string. Args: bandwidth: The bandwidth to convert in byte/s. Must be a multiple of 1024/8. Returns: A string compatible with wpr --{up,down} command line flags. """ assert bandwidth % (1024/8) == 0 bandwidth_kbps = (int(bandwidth) * 8) /...
55caf2dc557e9a4b499020b5c57d663e91bf8845
635,454
import logging def _read_gold_and_pred(gold_fpath, pred_fpath): """ Read gold and predicted data. :param gold_fpath: the original annotated gold file, where the last 4th column contains the labels. :param pred_fpath: a file with line_number and score at each line. :return: {line_number:label} dict...
d1bb7f79115b2914193881ad8b966448e080dad8
635,455
import requests import time import os def get_pdf_template(basename, file_url): """ Downloads data mapping from a source """ r = requests.get(file_url, stream=True) chunk_size = 2000 ts = time.time() template_pdf = os.path.join(basename, 'template/tmp_' + str(ts) + '.pdf') try: ...
b8b0d1be5f65157f4622ca8a56052e0ee0f397c0
635,456
def normalize_tag_name(name_tag): """ docker-py provides "RepoTags", which are strings of format "<image name>:<image tag>" We want to strip off the tag part and normalize the name: some.domain.com/organization/image:tag -> organization/image organization/image:tag -> organiz...
bd8f049e4a815835e702cbe28c414bebec1fcbc8
635,457
def get_tags(hyps_edits, tags_map, keep_inserts): """ from the edits, generate the sequence of tags """ tags = list() for hyp_edit in hyps_edits: operation = hyp_edit.o if operation=="I": if not keep_inserts: continue else: tag ...
05e24557cd2bf399a417d909124bf61fdc20a8cb
635,458
def find_last_word(s): """Find the last word in a string.""" # Note: will break on \n, \r, etc. alpha_only_sentence = "".join([c for c in s if (c.isalpha() or (c == " "))]).strip() return alpha_only_sentence.split()[-1]
aaa163496a6c6ba4a5b8113b98e28390398fcbf9
635,460
import os def get_basepath_or_cwd(model_file): """ inspects the model_file variable for a directory name. if no directory is found, returns current working dir. """ basepath = os.path.dirname(model_file) if not os.path.isdir(basepath): basepath = os.getcwd() return basepath
01b916c3605b574e8753f3dc290ba5efca614765
635,461
import torch def SOR(x, k=2, alpha=1.1): """ SOR Defense: Statistical Outlier Removal """ x = torch.from_numpy(x.reshape((1, ) + x.shape)).to("cpu") # so that it seems like a batch of point clouds pc = x.clone().detach().double() B, K = pc.shape[:2] pc = pc.transpose(2, 1) # [B, 3, K] inner ...
0082c54f22426fa355a9da1ce8f88e0939c2802f
635,462
def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] ...
dedbd8aa482a16d4d6cd61e46fe68347ee3697e6
635,463
def min_level(db_samples_signal): """Calculate the minimum value of the series of levels (dB) collected over time (samples) Parameters ---------- db_samples_signal : numpy.ndarray array in which each line is the db values of a sample. Outputs ------- minimum : numpy.ndarray ...
58a9c1c77ddaedc4f7cc924c56c2a97904c87142
635,464
def jump_to_match(input_file, regex): """Jump to regex match in file. @param input_file: File object @param regex: Compiled regex object @return: True if successful, False otherwise """ for line in input_file: if regex.match(line): return True return False
9ecae9a2218d3f334e2183cc1979d839113c995b
635,465
def conjoin_args(args): """ Conjoin from left to right. Args: args (list): [<something> CONJUNCTION] <something> Returns: dict: MongoDB filter """ if len(args) == 1: return args[0] conj = f"${args[1].value.lower()}" return {conj: [args[0], args[2]]}
feafb1dc37fc5df1d37bf1c22456a46d3968d043
635,466
def multAll(lst): """Multiplies a list of variables together""" if len(lst) == 0: return 0 out = lst[0] for i in range(1,len(lst)): out *= lst[i] return out
6d985d8c69b25f35b14b2bc94cc4e45be8f826e0
635,467
def coding_endpoints(strand, min_cds, max_cds): """Determine coding_start and coding_end coordinates""" if strand == '+': return min_cds - 1, max_cds - 1 else: return max_cds - 1, min_cds - 1
3ef1d0999be00f3572eea2d41d6fb4424e81c5b7
635,468
from typing import Union import ast from typing import List def get_assign_targets(node: Union[ast.Assign, ast.AnnAssign]) -> List[ast.expr]: """ An AnnAssign `target` is a single node. An Assign `targets` is a list of nodes. Example: `a = b = 1` return [ast.Name('a'), ast.Name('b')] ...
9c12b6ba8ab7401c29e62b9fa1c73c1d5f995c1f
635,469
def extract_between(source: str, start: str, end: str) -> str: """Extract all of the characters between start and end. :param source: The input string from which to extract a substring. :param start: The substring that marks the extraction starting place. :param end: The substring that marks the place ...
7f3c5f428cbfa80adc1781ae01ea15788ed9a3e8
635,470
def form_page(): """Form credenziali di accesso """ html = """<!DOCTYPE html> <html> <head> <title>Casetta della Buonanotte</title> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet"> <style> html, body { display: flex; justify-content: cente...
0e86f0d2730287249e25f2604809e1e048291fc2
635,471
import torch from typing import Optional def one_hot(labels: torch.Tensor, num_classes: int, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, eps: Optional[float] = 1e-6) -> torch.Tensor: """Converts an integer label x-D tensor to a one-ho...
7ecc2eaf0b32ccb4b7abea8a870aaa302e4cffc6
635,472
def DictToObj(ctdict,targetObj,force=False): """ dict 转换对象 :param ctdict: 字典 :param targetObj: 目标对象 :param force: 是否强制覆盖已有值的属性 :return: """ for key in ctdict: if hasattr(targetObj, key): if force : setattr(targetObj, key, ctdict[key]) else...
dfda73b7d1998c1e5ce1bf94311a8339fa3b4add
635,473
from typing import Iterable from typing import Any from typing import Iterator from typing import Tuple import itertools def pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]: """Return iterator of overlapping pairs of items from an iterable. Will return an empty iterable if the passed iterable ...
9d61ed5c0dd2b165ac93d6c59b0a62700a0ddbe8
635,474
def normalize_ctu_name(name): """Ensure name is in the normal CTU form.""" return name.title().replace('Ctu', 'CTU').replace('Iot', 'IoT')
b530f8d6316a559c3e3935c7a46d0753477b87f6
635,475
def count_string_dictionary(list_of_strings): """ Count the number of instances in a list and return them in a dictionary where the keys are the strings and the value the number of times it appeared in the list """ to_return = {} for e in list_of_strings: try: to_ret...
56b4613eb2f5eb63db4575462c9891471509e7ba
635,476
import torch def gradient(models): """ Returns the gradient of the given models as a single vector :param models: :return: """ gs = [] for model in models: for param in model.parameters(): if param.requires_grad: gs.append(param.grad.data.view(-1)) ...
7c4a799a7934bda9bf610d9762268389beb8886e
635,477
def bpe_decode(code_array, tokens, max_char_code): """Decode a BPE code array into a string Parameters ---------- code_array: array of int64 The code array to decode tokens: list of unicode_type The string representations of learned codes max_char_code: int64 The maxim...
f94a1878c6b3c9b6ea9958feb7c56623482d2a4d
635,478
from typing import Union from pathlib import Path import os def safe_file(path: Union[str, Path]) -> Union[str, Path]: """ Ensure that the path to the file exists, then return the path. For example, if the path passed in is /home/entilzha/stuff/stuff/test.txt, this function will run the equivalent of...
40652b0a25ee55fa181c134cea002fdb8a3c1652
635,479
def _parse_ctab_bond_block(contents): """ """ bond_block = [] for row in contents: bond_block.append(row.rstrip('\n')) return bond_block
b3d17e745c6e65fc942f63e56fbbbe0fa3318621
635,481