content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def ifg_dates_dc_to_cum(ifg_dates): """Given the names of the daisy chain of interfergorams, find the names of the cumulative ones relative to the first acquisition. Inputs: ifg_dates | list | names of daisy chain ifgs, in form YYYYMMDD_YYYYMMDD Returns: ifg_dates_cum | list | names of cum...
756e8277887baeeb95d63dacd719878b1836c09c
662,414
import pickle import os def model_fn(model_dir): """Deserialize and return fitted model. Note that this should have the same name as the serialized model in the _xgb_train method """ model_file = "xgboost-model" model = pickle.load(open(os.path.join(model_dir, model_file), "rb")) return model
fb5470d6ddba3df734cca4d82e26de7c736fe43c
662,415
import os import stat def _filter_smw_worksheet(path): """ Identify worksheet objects of interest in an SMW config set. All worksheets should be considered for management by smwflow. Just ensure that the proposed file is a regular file and ends with '_worksheet.yaml' Args: path (string): ab...
d7259dc3e3a418fc59324777f0f96fb8d706e3cf
662,417
def is_none_p(value): """Return True if value is None""" print("is_none_p", value) return value is None
2b0ab594fab76c856058884fd43252a591f86e78
662,418
def trend(series, n): """Return the running average, minimum and maximum of a series for an n- element moving window.""" meanvals = [] minvals = [] maxvals = [] running = [] for val in series: running.append(val) if len(running) > n: running.pop(0) meanval...
3e40c734548d8773401e255fb844a6683ef1c871
662,420
def escape_string_json(st): """ Escaping string for json /Users/dusanklinec/workspace/monero/external/rapidjson/writer.h :param st: :return: """ ret = [] c = 0 ln = len(st) escape_chmap = { b'\b': b'b', b'\f': b'f', b'\n': b'n', b'\r': b'r', ...
35d1b3f1b5913752c4840df7eb475e05c9f07099
662,421
def isWild(card, wild_numbers): """returns true if a card is a wild""" if card.number in wild_numbers: return True else: return False
b9a10089d8befa8c5f3c8656e8e4834763caa8fd
662,422
def max_headroom_energy_rule(mod, prj, tmp): """ **Constraint Name**: GenVarStorHyb_Max_Headroom_Energy_Constraint **Enforced Over**: GEN_VAR_STOR_HYB_OPR_TMPS Can't provide more upward reserves (reserve provision times sustained duration required) than the available energy (from resource and from ...
63ff3634e157718affb25930aa17f12548e7fdf9
662,423
def max_value_in_tab(tab): """ Get the maximum value of a tab Parameters tab Returns the maximum value of a tab """ max = tab[0] for a in tab: if a > max: max = a return max
d82cad0375fa3f84b1c8f4f73891ad27fc95f8c7
662,424
from datetime import datetime def parse_date(json_date): """parses out the date in the json string and returns a python date object""" dateStr = json_date[6:len(json_date) - 2] return datetime.fromtimestamp(int(dateStr) / 1000)
00296a4b891af5df11e6303671d384bb92f5e847
662,425
import codecs def write_nullactors(event_dict, output_file): """ Formats and writes the null actor data to a file as a set of lines in a JSON format. Parameters ---------- event_dict: Dictionary. The main event-holding dictionary within PETRARCH. output_file: String. ...
636dd6acd941733c4b520d028044f0d26b23a1d3
662,426
import os def cache_dir() -> str: """ :return: chache directory """ j = os.path.join path = j(os.environ.get('XDG_CACHE_HOME', j(os.environ.get('HOME'), '.cache')), # type: ignore 'autogluon-utils') os.makedirs(path, exist_ok=True) return path
cd79dab7a3d21d38f9feda0f90eb90d50c74dee1
662,427
def hmean(C): """ Attributes: C (array-like, dtype=float, shape=(n,n)): Confusion matrix Returns: loss (float): H-mean loss """ tpr = C[1, 1] * 1.0 / (C[1, 0] + C[1, 1]) tnr = C[0, 0] * 1.0 / (C[0, 0] + C[0, 1]) return 1.0 - 2.0 * tpr * tnr / (tpr + tnr)
d4613e6a114caba436374e5b19b1e80cc731d21f
662,428
def combine(background, figure): """ :param background_img: str, the background image to be put behind the character :param figure_img: str, the image with the character which has green screen at the back :return: SimpleImage, combined image """ for y in range(background.height): for x i...
86f195383ac17889348a8e84339259ac85203c92
662,429
def check_string(string: str, chars: list) -> bool: """ Returns True if one element of chars is in the string. :param string: String to check. :param chars: list of strings to check if one of it is in the string. :return: bool """ return any((char in string) for char in chars)
10cbfdc573914c738b5c0dc2ea7dd4fa606703eb
662,430
from typing import Dict from typing import Set from typing import Tuple def aggregate_unique_objects(associations: Dict[str, Dict[str, Set[Tuple[str, str]]]]) -> Dict[ str, Dict[str, Set[Tuple[str, str]]]]: """ Utility method to calculate the "unique objects" metric from the object-type specific associati...
58fbb096bf82c2316e8be05be836d0055bdd1458
662,431
def _process_production_element(s): """ Each element in the PPDB production is either a non-terminal in the form [node,alignment] or it is a terminal word with no tag information. @return: (tag, word, alignment) """ if s[0]=='[': assert s[-1]==']', "problem with PPDB element %s"%s ...
f1344643e6f7b22418a0e1e8263ae252af91d6b3
662,432
def getCurrentPosition(grid, locationMarker='*'): """ Return the row and col coordinates of my location """ for row in range(len(grid)): for col in range(len(grid[0])): if grid[row][col] == locationMarker: return (row, col) return -1
3e7e8890f1a192fe367d5fb486cdc87161eacc59
662,433
import sys def import_from_path(path, args): """Imports a model from a specific path. Returns None if no model is found. path: File path to the directory where the .py file is placed. args: dictionary with model arguments. """ sys.path.append(path) try: module = __import__(args["model...
b00f72da5ad9fff9aa9830cb0561309f009ee4d7
662,434
import numpy def estimate_gradient(f, x, epsilon=1e-4, args=()): """Estimates the gradient for a given callable f Suppose you have a function :math:`f'(x)` that purportedly computes :math`\frac{\partial f(x)}{\partial x}`. You'd like to check if :math:`f'(x)` is outputting correct derivative values. You can ...
30e48698bb84ad18cbe01fc71ac93764f5b11a9c
662,435
def percentage(value, refer_to): """Return the percentage of the reference value, or the value unchanged. ``refer_to`` is the length for 100%. If ``refer_to`` is not a number, it just replaces percentages. """ if value is None or value == 'auto': return value elif value.unit == 'px': ...
81738835f31e5651f29bc49aac06d6ee0142439d
662,436
import inspect def _append_signature(func, kwname, kwdefault=None): """ Local helper to automate keyword argument insertions in function signatures Parameters ---------- func : callable Typically a (wrapped) Syncopy metafunction such as :func:`~syncopy.freqanalysis` kwname : str ...
9f7e8f1d41141432772543491906c8e428ac74f9
662,437
def index(): """ Render the landing page """ return """ <html> <head> <title>MolSeek Public API</title> </head> <body> <h1>MolSeek Public API</h1> <h3>For a simple Demo</h2> Try, <ul> <li><a href='/ncbi/cortisol'>Search for "cortisol"</a></li> <li><a href='/...
52aa82fad5147bffdfd3cee6d402ae3b0fb2fe6a
662,438
def validate_slug(slug, digits=8): """ Return true if a slug is a string and has the correct number of digits. """ return isinstance(slug, str) and len(slug) == digits
d8d3d30b20649bb1e3a1b2758b8e85de0fe27b39
662,439
import torch def safe_log(x, eps=1e-6): """ Prevents :math:`log(0)` by using :math:`log(max(x, eps))`.""" return torch.log(torch.clamp(x, min=eps))
ab6fe02812cde9e4330be365eac55e1e6b274b40
662,440
def flat_eq(x, y): """ Emulate MATLAB's assignment of the form x(:) = y """ z = x.reshape(1, -1) z = y return z.reshape(x.shape)
e39deae6e7df1afcb6e903348ab8480daa31b936
662,441
def is_select(status): """Returns true if the first word in status is 'select'.""" if not status: return False return status.split(None, 1)[0].lower() == "select"
95323a52e4d4b2911053c628b67b8da89deeec3d
662,442
import fileinput import csv def ReadMetaDataFile(metaDataFile): """File format: [id] [metadata] metadata format: "first_line" "second_line" "third_line" """ metaDataDict = dict() for line in fileinput.input([metaDataFile]): if line != "\n": for items in csv.reader([line], delim...
176934f3d46b9aab41df741caef844483f719209
662,443
def darpaNodeNetmask(): """Return IP subnet mask of radio node on DARPA's network.""" return '255.255.255.0'
714b7258285e4a947bffb1e1d93f4cad1df24cea
662,444
def assoc_in(d, keys, value, factory = dict): """ Update value in a (potentially) nested dictionary This function was inspired by toolz.update_in and adopted for bazel. Source: https://github.com/pytoolz/toolz/blob/master/toolz/dicttoolz.py Args: d: dictionary on which to operate ...
4d58539e11a16355f4d5414a23af8a7a7cfed820
662,445
def add_group(groups_collection, group_name): """Adds a new group to the groups collection if it doesn't already exit :param groups_collection: Mongo collection that maintains groups :param group_name: Name of group to be added :return: ObjectID of new group :return: None if group already exists ...
8dd424d573f55d56382ad0bf498a6b02db36a2ab
662,446
def trigger_timeout(session, Type='Int32', RepCap='', AttrID=1150008, buffsize=0, action=['Get', '']): """[Trigger Timeout (ms)] Sets trigger timeout to avoid instrument lock up when a trigger has not been received. The timer is started when the VSA is armed. Range of allowable values is 0 to 1100 seconds....
6035ad5d36a247767a761c08daea88fcc3b45bdb
662,447
def file_get_contents(filename): """ Returns file contents as a string. """ with open(filename) as file: return file.read()
2572068496a9a3cd185d4cd2f469bbe2f9669c6b
662,448
def is_contained(a, b): # Multiset: a < b """ bool: True if list a is fully contained in list b. """ b = b[:] try: [b.remove(s) for s in a] except ValueError as err: return False return True
ad828d4a8efb44d56f061eec745da125a3218f7d
662,449
def index_dependent_values(self, chromosome): """Test of the GA's ability to improve fitness when the value is index-dependent. If a gene is equal to its index in the chromosome + 1, fitness is incremented. """ # Overall fitness value fitness = 0 for i, gene in enumerate(chromosome): ...
20df3cc47ef566f34fbdba4eca84a85795a02408
662,450
def nice_time(seconds): """ Prints a time in a nice, legible format. """ seconds = round(seconds) m, s = divmod(seconds, 60) h, m = divmod(m, 60) ret = '' if h > 0: ret += f'{h}h' if m > 0: ret += f'{m}m' ret += f'{s}s' return ret
50787320afee7728e84e1e88fcc6345c501a79c5
662,451
def manhattan_dist(c1, c2): """ Compute Manhattan distance between two coordinates """ return abs(c1[0] - c2[0]) + abs(c1[1] - c2[1]) + abs(c1[2] - c2[2])
1c91e684dee200a4695e02e4a5cd4185cb995951
662,452
import yaml def read_yaml(yaml_absolute_path): """ 读取yaml文件 :param yaml_absolute_path: 参数为需要读取的yaml文件的绝对路径 :return: """ with open(yaml_absolute_path, "r", encoding="utf-8") as f: data_list = yaml.load(f, Loader=yaml.Loader) return data_list # 返回一个数据列表
cc736c9df2d481e5401ae9242d3f35351518b26c
662,453
def signature_matches(func, template_func): """ Checks if the given *func* is of type `function` or `instancemethod`. If it is, it also verifies if the argument count matches the one from the given *template_func*. When the function is not callable or the signature does not match, ``False`` is returned....
068f7d5b16123a47edad39136b087d1cc9b0d18c
662,454
def extract_parameter(in_array, index): """ Description: Extracts and returns a single value from an array. Used, for example, to extract the L0 PH434SI from the array holding the 24 sets of 4 light measurements made by the Sunburst SAMI-II pH instrument (PHSEN). Implemented by: ...
02e31e85174da50b62cb843f3d32a80094a3e58f
662,455
def prep_msg(msg): """ Prepare message """ msg += '\0' return msg.encode('utf-8')
89be32becc5b459bf22e597be3ce9bfae5f29e94
662,456
def get_currencies(trader, coin_info, interval): """ """ currencies = dict() for name, symbol, threshold in coin_info: currencies[name] = dict() currencies[name]["name"] = name currencies[name]["symbol"] = symbol currencies[name]["threshold"] = threshold curr...
3e3b29863e52cc56b48d4da45be1f4feadeb2593
662,457
import importlib import pkgutil def _walk_modules(path): """ Loads a module and all its submodules from the given module path and returns them. If *any* module throws an exception while importing, that exception is thrown back. """ # Support for namespace packages is added. See PEP 420. #...
73abe5071044157d2caddf4bfc0db676dd7010b3
662,459
def lookup_pipeline_parser_name(aset_name, pipe_name, parser_name): """Find the flattened name of a pipeline parser running under an analysis set. """ return f'{pipe_name}-~-{parser_name}-~-{aset_name}'
feb55c251bc9dd806546904a8f7e55bf9b6d4c70
662,460
def expected_defaults(): """A dict containing all expected default values for keys of any config.""" return { "version": 2, "name": "<Unnamed Scenario>", "scenario": {"serial": {"runner": None, "config": "salami"}}, "settings": { "gas_price": "FAST", "time...
8e160b4c1cbe0109e719cfaa295e009f15df0366
662,461
def child_fun(current_person): """This function checks whether the person has a child or not and works accordingly. Parameters: current_person: The current Person object. Returns: The picked child number and the children list as a tuple. """ ch_lst = current_person.get_chil...
6af533cd0c447e015eac0a69789e298368e408cd
662,462
import time def payload(username): """ try: user = User.objects.get(email=post_data['email']) user.match_password(post_data['password']) except (User.DoesNotExist, User.PasswordDoesNotMatch): return json_response({'message': 'Wrong credentials'}, status=400) payload = { ...
f612bbb89d00d8c7bd049f7acdf5d8e131f92ccc
662,463
import torch def iou_pt(box, others): """ returns ious between the box and every other boxes """ box, others = box.view(-1, 4), others.view(-1, 4) box = box.repeat(others.shape[0], 1) x1y1 = torch.max(box[:, :2], others[:, :2]) x2y2 = torch.min(box[:, 2:], others[:, 2:]) inter_edges = ...
65e98533bcbce90067185980a107021e9548cac4
662,464
def uses_all(word, letters): """return True if the word use all the letters""" for letter in letters: if letter not in word: return False return True
ddfba7bcdfd16d243c2b94fdc6e10afbc7887646
662,466
from typing import Pattern def _match_root(root, name): """ Args: root (str or re.Pattern): Root. name (str): File URL or path. Returns: bool: True if match. """ return (isinstance(root, Pattern) and root.match(name)) or ( not isinstance(root, Pattern) and name.st...
a51d8ef6c4dba4ad1405116f12a868999336b4e9
662,468
def fate_lr_decay(initial_lr, lr_decay, epochs): """ FATE's learning rate decay equation Args: initial_lr (float): Initial learning rate specified lr_decay (float): Scaling factor for Learning rate epochs (int): No. of epochs that have passed Returns: Scaled...
e8435afc466c0ca2b7156b2b95370bcd38fef0d5
662,469
import numpy def calculate_timestep(time): """Determine average spacing of time data (list). Data is assumed to be taken at a regular interval.""" steps = numpy.diff(time) timestep = numpy.mean(steps[2:]) stddev = numpy.std(steps[2:]) timemax = numpy.max(steps[2:]) timemin = numpy.min(steps[2:...
743082753f82735b835171638647d98106e14544
662,470
def adjust_height(h): """ 调整box高 """ heights = [11, 16, 23, 33, 48, 68, 97, 139, 198, 283] N = len(heights) for i in range(N-1): if h<=heights[i]+heights[i]*0.44/2: return heights[i] return h
9cb50f827e203a30cc20414ce72269e5de42786c
662,471
import torch from typing import Tuple from typing import Callable def sort_sequences(inputs: torch.Tensor, lengths: torch.Tensor) -> ( Tuple[torch.Tensor, torch.Tensor, Callable[[torch.Tensor], torch.Tensor]]): """Sort sequences according to lengths (descending) Args: inputs (tor...
6a0c3e05a809833a90bd68090880c3b09ef585ec
662,472
def bin2state(bin, num_bins, limits): """ :param bin: index in the discretization :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit of each discrete dimension, and row[1] are corresponding upper l...
04c5107946f72bddc1900dbaa5906203c597837a
662,473
def queryROAM(station): """ Query the Rail Opal Assignment Model provided by Transport for NSW and returns an occupancy status """ # requires login to TfNSW opendata platform # response = requests.request("GET", "https://tfnsw-prod-opendata-tpa.s3-ap-southeast-2.amazonaws.com/ROAM/2020-10/ROAM_20201...
bb041c7f63bc1921dd67b488ca124e4769a46c0e
662,474
def board_full(board): """ Utility function that returns True if the given board is full and False otherwise Arg board: board - the board you want to check """ for row in board: for piece in row: if piece == '*': return False; return True;
a4c5b71cd9aa95f848acb96c62f850afbbf4805e
662,475
def ztf(): """ Force Zwicky Transient Facility 3-band, DR2 survey conditions into your simulated dataset. Utilize this function by passing `survey='ztf'` in `deeplenstronomy.make_dataset()`. """ info = """ IMAGE: PARAMETERS: exposure_time: 30.0 numPix: 100 pixel_scale...
ff936533d34bf8e3935d98dc75d45d1404e0c596
662,476
def always_reversible(iterable): """An extension of :func:`reversed` that supports all iterables, not just those which implement the ``Reversible`` or ``Sequence`` protocols. >>> print(*always_reversible(x for x in range(3))) 2 1 0 If the iterable is already reversible, this function retur...
76442c9c7c020a10e168ce0a8d787afc6d15facc
662,477
def sortData(data): """sort data into a specific index""" sortedData = [] for i in data: for j in i: temp = [] i2c = j["i2c"] temp.append(j["time"]) temp.append(i2c[0]) temp.append(i2c[1][0]["x"]) temp.append(i2c[1][0]["y"]) ...
b44badeb223695ca462702744a3980b7a131ff35
662,478
def get_weatherstation_id(station_model="WS501-UMB", software_version=1): """ Identification in Modbus register ir 0 (30000). High byte: WS-Type, Low byte: Software version :param str station_model: the name of the weather station model being simulated :param int software_version: the version being si...
c49c794ea272b9f4a9c34f3640ce3dbf764cbf0b
662,479
def assert_single_element(iterable): """Get the single element of `iterable`, or raise an error. :raise: :class:`StopIteration` if there is no element. :raise: :class:`ValueError` if there is more than one element. """ it = iter(iterable) first_item = next(it) try: next(it) except StopIteration: ...
16cec15d07b47bc9ae75dddee5eace13eec22e15
662,480
def get_schema(): """Returns schema for Chicago taxi dataset.""" name_to_types = { 'company': 'string', 'dropoff_census_tract': 'float', 'dropoff_community_area': 'float', 'dropoff_latitude': 'float', 'dropoff_longitude': 'float', 'fare': 'float', 'payment_type': 'string', ...
43987c1b81afec19ed5b6e30d4d3584730733372
662,482
def collapse_includes_excludes(includes, excludes): """ :includes: dict Possible parsed `?fields=` data :excludes: dict Possible parsed `?excludes=` data :returns: tuple (dict, bool,) Where dict is includes or excludes, whichever was Truthy, a...
fee261b83964aa55f3bace5da37b509bb4b62552
662,483
def fasta_split(fasta_str): """ Splits a fasta file like: >sp|P10636|TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 SV=5 MAEPRQEFEVMEDHAGTYG SPRHLSNVSST >ANOTHER_TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 S...
84e02801132673a89a9d084630865b94c0abae04
662,484
import string import random def random_string(length=255, extra_chars=''): """ Generate a random string of characters. :param length: Length of generated string. :param extra_chars: Additional characters to include in generated string. """ chars = string.ascii_letters + extra_chars re...
fa434400b65343709d604d418c4d2f9f596e90cb
662,485
import time def timer(input_func): """ returns the execution time of a function wrapped by this decorator""" def timed(*args, **kwargs): start_time = time.time() result = input_func(*args, **kwargs) end_time = time.time() print("{0} took {1:0.5f} secs".format(input_func.__name_...
da477a47d5db6f1c2b449914ad6e1dd383754a5b
662,486
def scan_file(classifier, location): """ Run a license and copyright scan on file at `location`, using golicense-classifier. Parameters ---------- classifier : LicenseClassifier() `LicenseClassifier` instance for scanning files location : str Location of the file """ ...
f09ec02b6d00115f0bf067846418c6652eed4205
662,487
def std_var_norm (Spectrum , mean): """Compute normalisation coefficient for intensity normalisation""" norm=0 for i in range(len(Spectrum)): norm = norm + pow((Spectrum[i]-mean),2); norm = pow(norm, 0.5)/(len(Spectrum)-1) if norm == 0: norm = 1; return norm
3a41242105b8a0b7b9aae749195a4b3cb5a208c0
662,488
def get_line(sample): """Build a list of relevant data to be printed. Args: sample (dict): an object from project samples Returns: list(str): list of relevant data to be printed """ return "\t".join( [ sample.last_status.created.isoformat(), str(samp...
2849cd6e87b681199d9cb12b9e58c8a793f20e12
662,489
import re def parse_host_list(list_of_hosts): """Parse the comma separated list of hosts.""" p = set( m.group(1) for m in re.finditer("\s*([^,\s]+)\s*,?\s*", list_of_hosts)) return p
51c49f0ec1ada98ca08c7e30b169fffc858cf8dc
662,491
def filter_memids_by_nodetype(agent_memory, memids, nodetype): """ filters the list memids by corresponding MemoryNode's nodetype; outputs a (sub) list of memids """ node_children = agent_memory.node_children[nodetype] return [m for m in memids if agent_memory.get_node_from_memid(m) in node_chil...
f2ec10c20841eae2418d12447968a2bc473580ee
662,493
def inv_ensure_4d(x, n_dims): """Remove excess dims, inverse of ensure_4d() function.""" if n_dims == 2: return x[:, 0, 0, :] if n_dims == 3: return x[:, :, 0, :] else: return x
86e3b9fad06b6f85f8c883d0ae7ce88017a6a62d
662,494
import argparse def vpc_interface(iface_as_str): """ Nine-part VPC network interface definition: [INTERFACE]:INDEX:[SUBNET]:[DESCRIPTION]:[PRIV_IP]:[GROUP1,GROUP2,...]: [true|false]:[SEC_IP_COUNT|:SEC_IP1,SEC_IP2,...] """ if len(iface_as_str) == 0: raise argparse.ArgumentTypeError( ...
558e6ecc0c0e6258469b4763630b9cd187f01b4e
662,495
import hashlib def checksum_file(path): """windows has silly git behavior that adds newlines, and python does silly things if we just open(..., 'r').encode('utf-8'). """ with open(path, "rb") as fp: hashed = hashlib.sha256(fp.read()).hexdigest() return { "name": "sha256", "...
2ccc1a0ac03d0b5de3ede34e81a15482f36c6dfd
662,496
import subprocess def _find_common_parent_commit(git_dir: str, ref_a: str, ref_b: str) -> str: """Finds the closest common parent commit between `ref_a` and `ref_b`.""" return subprocess.check_output( ['git', '-C', git_dir, 'merge-base', ref_a, ref_b], encoding='utf-8', ).strip()
85f40fb8d3776156b973ddd9197478f6721c64bb
662,497
import requests import sys def _get_app_names(url): """Get app_names.json remotely""" apps = [] try: req = requests.get(url) for app_info in req.json(): apps.append(app_info[u'id']) except: print(u"Unable to get list of applications. Exit(2)", file = sys.stderr) ...
0cfe6c2c19233ed13d6ed54693e95407d1f94868
662,498
def recent_actions(context): """ Renders the recent actions list for the admin dashboard widget. """ return context
f03b5cd8f74226831d4325ac713f2a51c319ee60
662,499
def posix_invocations(trace_graph): """Return number of total POSIX API invokations""" return sum(map(lambda x: x[1], trace_graph.full_paths_dict.items()))
dd2fdde445ff7738ee06002dd9b9cc6cd1ebad2f
662,500
import argparse def parser_add_general_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: """ Adds general arguments to a parser. Adds properties `dry_run` and `verbose`. """ general = parser.add_argument_group('general') general.add_argument('--dry-run', ...
612c07be39fa4fac7c14ff3c4800e27f49c40540
662,501
def prim_Uninitialized(mapper, graph, node): """ 构造表示编译器永远不会使用的值的PaddleLayer,该节点转换为None。 TorchScript示例: %345 : bool = prim::Uninitialized() 参数含义: %345 (bool): 输出,为赋值的bool。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_outputs_name(node)[0] ...
8da1ab01ac5a355d535eee1578ddb20300b0eee9
662,502
async def mistyversion_header(request, handler): """Add Misty-Command-Version header """ response = await handler(request) response.headers['Misty-Command-Version'] = 'Current' return response
7339714e33fc2a73868e9a0ba8113991d5774340
662,503
def comp_surface_wind(self): """Compute the Slot inner surface for winding (by analytical computation) Parameters ---------- self : SlotW13 A SlotW13 object Returns ------- Swind: float Slot inner surface for winding [m**2] """ return 0.5 * (self.W2 + self.W3) * s...
45431b51775a18c29857049e0b958139d97ce1bc
662,504
def labels_to_generate(epitope_files, ppi_files): """ Takes 2 lists of files and extracts the chains for which to generate labels. """ all_files = epitope_files + ppi_files chains = [] for f in all_files: chain = f.split('.')[0].split('_')[-1] if not chain in chains: ...
a752d95572ee76e9cc6ce8af3fb86e6133d2c2c2
662,505
def elliptic_range(num_pages, current): """ Produce a list of numbers from 1 to num_pages and including current. Long runs of successive numbers will be replaced by "...". """ def gap(start, stop): if stop - start < 3: return range(start, stop) return ["..."] ret = []...
f27fd176abce07fc084ce8d7ae6ed04324cdd809
662,506
import math def x_f(x_i, v_xi, a_x, t): """ :rtype: object :param x_i: :param v_xi: :param a_x: :param t: :return: """ x_f = x_i + v_xi*t+1/2*a_x*math.pow(t,2) return x_f
6b49af102d0a731bb190d2b17443d69bddcaa074
662,507
def categorize_attendance(attendances): """ :type attendances: iterable of librus_tricks.classes.SynergiaAttendance :rtype: dict[librus_tricks.classes.SynergiaAttendanceType.short_name, list of librus_tricks.classes.SynergiaAttendance] """ attendance_dict = dict() for att in attendances: ...
09b6239ec7f5c645356a3f874df58ba83d676a97
662,508
import tempfile def tempdir(): """ tempdir - return the name of temporary folder """ return tempfile.gettempdir()
7cf0185b7b603c3f2c645081f4cc37fb6afaf4c1
662,509
def dd_valley_value_map_nb(record, ts): """`map_func_nb` that returns valley value of a drawdown.""" return ts[record['valley_idx'], record['col']]
c2f08fb8fb81be4d8e57dac949d8048d83c7dcec
662,510
def image(url, style=''): """Corresponds to ``image: url`` in the markup. :param url: a full URL or a ``/``-separated path to an image file. :param style: CSS for this image, e.g. ``'float: right;'``. Below \ ``image: url`` in the markup. """ style = style.strip() if not style...
03c583e5e5a37a13725b908d8c6541e5f2ba5783
662,511
from typing import List def part_2(expenses: List[int]) -> int: """Find the three entries in expenses that sum to 2020 and return their product. Args: expenses: List of integer expense values. Returns: Integer product of three entries that sum to 2020. """ return { a * b ...
5bc40d2d14f120eca021520c5063b4864dcf1bf7
662,512
def check_profiling_options(profiling_options=[]): """Check profiling options . Args: profiling_options: Profiling options. Return: Valid options Raise: If profiling_options is null or option is not `training_trace` or `task_trace`, `op_trace`'. """ error_mag = 'profiling options must be ...
34d77e738610980dd894edbd6848acc7f6eb0dfd
662,513
import re import numpy def get_threshold(data, threshold_str, axis=None): """Turn the user input threshold into a numeric threshold.""" if 'pct' in threshold_str: value = float(re.sub('pct', '', threshold_str)) threshold_float = numpy.percentile(data, value, axis=axis) else: t...
6a13f273d75b5ea01fe0f2c50cb2c84d4effeb59
662,514
def _get_lookup_value(code_lookup, name_key, group_key, desc_key): """ Returns dict with 'name' and optional 'desc' properties derived from code_lookup :param code_lookup: :param name_key: :param: desc_key: Can be the null string :param desc_key: Can be the null string :rtype: dict """ ...
0b6afdee7c2b6eca899387d2c1e4e8d203f7e622
662,515
def _semantic_feasibility(self, G1_node, G2_node): """Returns True if mapping G1_node to G2_node is semantically feasible. """ # Make sure the nodes match if self.node_match is not None: nm = self.node_match(self.G1.nodes[G1_node], self.G2.nodes[G2_node]) if not nm: retu...
28624359d9ccb89ceeb6b429b4ae51c1d7855ff4
662,516
def _quote(data): """Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data` with '"' and "\\" escaped using "\\". :return...
e9f05dff72ddc8b66d61c2a4ba5f7140c45e4665
662,517
import sys def create(db_dict): """Create a database. If it already exists, an exception of type weedb.DatabaseExistsError will be raised.""" __import__(db_dict['driver']) driver_mod = sys.modules[db_dict['driver']] # See note above if hasattr(db_dict, "dict"): return driver_mod.create...
2500f367102419e15461b2f042326cbe7a46f5e2
662,518
from functools import reduce from operator import mul def prod(iterable): """Like sum(), but for multiplication.""" return reduce(mul, iterable, 1)
ed22e4a1e09a7feae3adefc24da8cfdbf1bee562
662,519
import math def velocities(course, vel): """ Converts target velocities from course and modulus to vector components Vx and Vy :param course: target course :param vel: modulus of target velocity :return: Vector components Vx and Vy """ return round(vel * math.cos(math.radians(course)),...
474f340cd3a505e33a19753844b5b636561d5089
662,520
import os def make_dir(new_dir_path): """ create the new directory if it not exist :param new_dir_path: absolutely path , the new directory :return: absolutely path """ if os.path.exists(new_dir_path): pass else: os.makedirs(new_dir_path) return new_dir_path
841b58977fb5c2651cf1d3ca34318e8e2d2cfdb4
662,521