content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compare_lr_test(model_result, restricted_result): """ Likelihood ratio test to test whether restricted model is correct Parameters ---------- model_result : Result instance restricted : Result instance The restricted model is assumed to be nested in the current model. The r...
3169cc7c8d1f18176a2ed744409649ec0a14a045
3,602,563
def vgg13_bn(num_classes=1000, pretrained='imagenet'): """VGG 13-layer model (configuration "B") with batch normalization """ model = models.vgg13_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg13_bn'][pretrained] model = load_pretrained(model, num_cla...
935ff120fbee9319840f270412ae262266bb2aec
3,602,564
def absolute(operand: ValueOrExpression) -> Expression: """ Constructs an absolute value expression. """ return ArithmeticUnary(operators.ArithmeticUnaryOperator.ABS, ensure_expr(operand))
39888a9108d1cabbe45cad58c11c1ba39912ba8a
3,602,565
def covariance_matrix(X): """ Args: X (ndarray) (m, n) Return: cov_mat (ndarray) (n, n): covariance matrix of X """ m = X.shape[0] return (X.T @ X) / m
128d9bfe12169cb344c150bf9f8f05565b5a8831
3,602,566
import operator def filter(array, *args, foos_filtering=[operator.gt, operator.lt], **kwargs): """general filter function for escape arrays. checking for 1D arrays, applies arbitrary number of filter functions that take one argument as input and""" if not np.prod(np.asarray(array.shape)) == array.shap...
825290fa49ae66455e6b8c5edd840c3d6d51d996
3,602,567
def sigmoid_deriv(x): """ Calculates the sigmoid derivative for the given value. :param x: Values whose derivatives should be calculated :return: Derivatives for given values """ return x * (1. - x)
8a7a1005fafb1b34c17c6ce4a8a04f80334e396a
3,602,568
from typing import Mapping def UpdateDict( target, override ): """Apply the updates in |override| to the dict |target|. This is like dict.update, but recursive. i.e. if the existing element is a dict, then override elements of the sub-dict rather than wholesale replacing. e.g. UpdateDict( { 'outer...
a07a3d7989e227ff1759271248777e167b7e5467
3,602,569
def calculate_propensity(kinetic_rates, lattice_state): """ Calculate the propensity for each event type Parameters ---------- kinetic_rates : list kinetic rates as defined in sim_parameters.py lattice : numpy.ndarray current lattice state Returns ------ event_propensit...
d689a5cd09930eaa881ce11d37c3ec006a20b37d
3,602,570
def fib(n): """calculate fibonanchi""" if mem[n] != 0: return mem[n] if (n <= 1): return n mem[n] = (fib(n - 1) + fib(n - 2)) return mem[n]
c9b5976411143f4e5be93cf3849c651b521ba6d9
3,602,572
def calc_sharp_v_scan(t, v, res_points=10): """Calculate the discontinuous rate of change of v with respect to t Args: t (np.array): the data of the independent variable, typically time v (np.array): the data of the dependent variable res_points (int): the resolution in data points, i.e...
cac85ac0a6a1ad9fcd13e83569b21dcfb01370d0
3,602,574
def traer_mayor_24_doge(): """ This function returns the highest price of the last 24 hours """ newxd = MySQLdb.connect(host=MY_H, user=MY_U, passwd=MY_P, db=MY_D) consulta = newxd.cursor() consulta.execute("SELECT price FROM history_coin WHERE name='DOGE' ORDER BY price DESC LIMIT 1;") resultado =...
ae093cf25290aee5eedaf14bdb18431b57910efb
3,602,575
def run_adaptive_grid(gdf, rtree, G, params, types, topk_regions, start_time, updates): """Executes the AdaptiveGrid algorithm. Employs a top-tier grid to identify promising cells and then applies ExpandBest over seeds that may be chosen using Bayesian optimization within those cells. Args: gdf: A...
ccf7d65302f9b59d14ef1dd65c896092c3a25b2c
3,602,578
from pathlib import Path import uuid def get_filename(filename): """CKEditor - Filename Generator""" extension = Path(filename).suffix return '{0}{1}'.format(uuid.uuid4(), extension)
50988191c0145e686b38306a6f1bfd686d4dff25
3,602,579
def NewtonRaphson(funcion, tolerancia, maxIteraciones, semilla): """ La tolerancia y numero de iteraciones tienen que ser positivos. La semilla debe de estar cerca del intervalo, caso contrario no va a converger. """ historia = np.zeros((maxIteraciones, 3)) if tolerancia < 0 or maxIteraciones < ...
1bb85b2663d732cb094e90645ed27252fb53fdcb
3,602,580
def IntToStr(input_bvv): """ Returns the string representation of the integer expressed in the BitVector :param input_bvv: the integer expressed as a BitVector we want to convert as a string :return: the string representation of the integer """ return StringV(str(input_bvv.value))
e92961fa876fd5047dc0715db40de13e2d5f89c5
3,602,581
def tee(cmd, cwd=None): """ executes a command, echoing output and buffering it for later use by the program. returns (exit_code, output) """ pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd, shell=True) output = [] while True: if pipe.poll() i...
8be56162728cda2711803251e441f35c8a993e6d
3,602,582
def dss_target(request): """ This is a parameterized fixture. Its value will be set with the different DSS target (DSS7, DSS8 ...) that are specified in the configuration file. It returns the value of the considered DSS target for the test. Here it is only used by other fixtures, but one could use it a...
0aa9f85160280032dfdea872b7c9a147a5717523
3,602,583
from typing import Tuple def get_contours_iou(contour1, contour2, image_size: Tuple = None, plot=False): """ 计算两个轮廓(多边形)交并比(Intersection-over-Union,IoU) :param contour1: 多边形1 (num_points,2),由num_points个点构成的封闭多边形 :param contour2: 多边形2 (num_points,2),由num_points个点构成的封闭多边形 :param image_size: (W,H) im...
11b307f984b467eaacfe11042b4e5056d1eca0cc
3,602,584
from typing import Dict import uuid def cancel_run( config: Dict, celery_app: Celery, run_id: str, *args, **kwargs ) -> Dict: """Cancels running workflow.""" collection_runs = get_conf(config, 'database', 'collections', 'runs') document = collection_runs.find_one( filter={'run_...
bb112b763c47328c247102a9485d20b4982b76c6
3,602,586
import re def _clean_name(name): """ This function sets the name of a recipe to the standard naming convention specified """ name = re.sub(r'\s', "_", name) return name.lower()
940792220aa6eabfcf067c6450f30bca66d1b214
3,602,587
def get_base_dict(): """Get basic dictionary containing special tokens.""" return { TOKEN_PAD: 0, TOKEN_UNK: 1, TOKEN_CLS: 2, TOKEN_SEP: 3, TOKEN_MASK: 4, }
166f420317455c14045911d84acf18cbac3d9070
3,602,588
def label_data(dictionary, images): """ Labels the data depending on patient's diagnosis Parameters ---------- dictionary: Dict with patient information images: Names of images to label Returns ------- Labeled data """ data = [] last_patient = '' aux = [] for img...
01eb965d4cff7a8d4242eeb57e43fe3d72ee74f9
3,602,589
from pathlib import Path import csv def save_csv(csvpath, data, header): """Save data & header as a csv output file in the path provided. Args: csvpath (Path): The csv file-path where the output data will be saved data (list of list): list of list with the same number of elements that can be ...
d9e592842a7c428f1165e290e51b17d959a76bd9
3,602,590
def gym_size(gym): """Returns the size of the gym.""" return len(gym)
b31a46a7b56e973da8dfa0cac9950fad14b48622
3,602,591
def is_houdini_paste_event(uievent: KeyboardEvent) -> bool: """Check whether or not the event is an item paste event. :param uievent: The occurring keyboard event. :return: Whether or not the event is a paste event (h.paste). """ return setKeyPrompt(uievent.editor, uievent.key, "h.paste", uievent....
84c2c60369b790546755f2d31a39950ad6f68ac0
3,602,592
import json def get_outputs(file_name, pretty_quotes=False): """Read outputs from notebook.""" with open(file_name) as file: saved_cell_outputs = defaultdict(lambda: None) nb_cells = json.load(file)["cells"] for cell_index, cell in enumerate(nb_cells): if "outputs" not in cell: continue ...
69c116b1f63890f476a835a2d0682ac65af71735
3,602,593
def dump(obj, file=None, file_format=None, **kwargs): """Dump data to json/yaml/pickle strings or files. This method provides a unified api for dumping data as strings or to files, and also supports custom arguments for each file format. Args: obj (any): The python object to be dumped. ...
16068381f3f1fa1a80b2f8c8b31702dbdbfcb08a
3,602,595
def is_call_id_in_video_state(log, ad, call_id, video_state): """Return is the call_id is in expected video_state Args: log: logger object ad: android_device object call_id: call id video_state: valid VIDEO_STATE Returns: True is call_id in expected video_state; Fal...
d0da323a21a23d461fc2aec06ac5d0bebac7cbef
3,602,596
def call_torch(func, arg, *args, dtype=None, device=None, batch_size=64): """Call a torch function with numpy arguments and numpy results.""" args = (arg, *args) index, values = flatten_with_index(args) result_batches = [] for start in it.count(0, batch_size): end = start + batch_size ...
75f3b6d62b374e3c3fff1e3f5db1d60faf05b7d5
3,602,597
import time def gstat_elapsed(metric): """ decorator that logs the elapsed time spent in the decorated method """ def wrap(f): def wrapped_f(*args, **kwargs): start_time = time.time() ret = f(*args, **kwargs) gstat(metric, time.time() - start_time) ...
b1ad90f1004f66d5f3a6694104d2b62eb6550eb8
3,602,598
def interpolate_points( line: "shapely.geometry.linestring.LineString", num_pts=5) -> list: """ Create a list of multipoints for the interpolated points along each linestring Arguments: ----------- line: "shapely.geometry.linestring.LineString" shapely.geometry.linestring.Lin...
4f5142d325b228602654806ed8aef8f54ffd15a6
3,602,599
def pressure_to_eta(del_p, wavenumber, device_d, water_d): """Convert the non-hydrostatic pressure to height above device_d=0.""" return del_p / _coefficient(wavenumber, device_d, water_d)
26718e66164d236ae8d8f7b5bd1618b4a36ccefd
3,602,600
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[],init_weight=True): """Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights Parameters: net (network) -- the network to be initialized init_type (str) -- the name of an...
b8d5e6185b247cc96b2774479aa065c7a5211b70
3,602,601
def confirm_pw(username, pw, pw_hash): """Verify a password for a given user.""" salt = pw_hash.split(',')[0] return make_pw_hash(username, pw, salt) == pw_hash
a479b45499701ccdd82d596eef99cb6f0c063bc2
3,602,602
def run_bandit(params, means, variances, experiment): """ Performs the bandit->environment->attacker interaction for a number of trials. Arguments: params (Python dict): holds parameter values of interest (see main.py) means (np.ndarray (n_arms,)): mean of the reward distribution assoc...
293dae01227319f7924b21bd837bd10708cff85b
3,602,604
def predicted_effects_for_variant( variant, transcript_id_whitelist=None, only_coding_transcripts=False, only_coding_effects=False, require_mutant_protein_sequence=False): """ For a given variant, return its set of predicted effects. Optionally filter to transcripts w...
69ea8e1b078d0e0bac9759d744f64b823009f26a
3,602,605
from typing import Tuple def __coord_on_finish( piece_number: int, player_number: int, piece_progress=0 ) -> Tuple[int, int]: """Piece number is irrelevant >>> __coord_on_finish(1, 0, 57) (9, 3) >>> __coord_on_finish(1, 0, 61) (9, 7) >>> __coord_on_finish(1, 1, 57) (3, 9) >>> _...
41dac0a68d63fe738726c2a97bddaa236a536766
3,602,606
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci): """ Extract spots detected outside foci, in a specific cell. Parameters ---------- cell_cyt_mask : np.ndarray, bool Binary mask of the cell with shape (y, x). spots_out_foci : np.ndarray, np.int64 Coordinate of the ...
d4e06d9ad14ced3b8984b71c32d9d3b1e0cebaae
3,602,607
def augment(im, augment_str): """Augments image (used for training).""" if augment_str: im = Image.fromarray((im * 255).astype(np.uint8)) im = make_augment(augment_str)(im) im = np.asarray(im).astype(np.float32) / 255 return im
c35d72fc97a56ac11f31862fc7bb16bebb3a9b9e
3,602,608
def aoc_string(data): """Read AOC string.""" length = unpack('<h', data) return data.read(length)
a765759b94cb5cf693956d95abc07c70c839e077
3,602,609
import dateutil def parse_date(date_string): """Parse a timestamp If it doesn't have a timezone, assume utc Returned datetime object will always be timezone-aware """ dt = dateutil.parser.parse(date_string) if not dt.tzinfo: # assume naive timestamps are UTC dt = dt.replace(t...
fe858fef9e454afa3352849733e9282e14be18b6
3,602,611
from re import T def nzseel2(): """ RESTful CRUD controller """ tablename = "%s_%s" % (module, resourcename) table = db[tablename] # Pre-populate Inspector ID table.person_id.default = s3_logged_in_person() # Subheadings in forms: s3db.configure(tablename, deletable...
e67223a2216d47b28f3175339a9ec160cf836e80
3,602,612
def End_Net(input_x, phase_depth, keep_prob): """ Define Aggregation Network """ weights, summaries = End_Net_weights_init() layer8 = conv2d_batchnorm_init(input_x, weights[0], name="conv_9", phase= phase_depth, stride=[1,2,2,1]) layer9 = conv2d_batchnorm_init(layer8, weights[1], name="conv_1...
06036b2d05a841e43a9970be7033ee1537671606
3,602,613
import base64 def decrypt(cipher_text, working_key): """ Method decrypt cc-avenue response. :param cipher_text: encrypted data :param working_key: working data :return: list """ cipher_text = base64.b64decode(cipher_text) iv = cipher_text[:AES.block_size] cipher = AES.new(bytes(wo...
8786af7539378c069690513fc665bb5d84b830ef
3,602,614
from datetime import datetime def get_start(): """ Helper function to retrieve the start of the time period from which to gather stock data """ weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] day = weekdays[datetime.today().weekday()] now = datetime.today() if day in...
d79886240011a0e7c56cf9c11c93fb8569ef57a1
3,602,615
import io def get_custom_stopwords(stop_words_file): """ 创建停用词list, :param stop_words_file: 停用词文件 :return: """ with io.open(stop_words_file, encoding='utf-8')as f: stopwords = f.read() stopwords_list = stopwords.split('\n') custom_stopwords_list = [i for i in stopwords_list] ...
d2e25e44815b6769688493a96852cc537d1127bf
3,602,616
from typing import Union def _hex(v: Union[LayerFieldsContainer, LayerField]) -> int: """parse the layer field as a hex string""" # split v into octets and reverse the order assert not isinstance(v, LayerFieldsContainer) or len(v.fields) == 1 return int(v.get_default_value(), 16)
00e1dd102085866a44ed092fadf59e03d10eb0ba
3,602,617
def read_bytes(vw, va): """ read up to MAX_BYTES_FEATURE_SIZE from the given address. raises: envi.SegmentationViolation: if the given address is not valid. """ segm = vw.getSegment(va) if not segm: raise envi.SegmentationViolation() segm_end = segm[0] + segm[1] try: ...
e2a94adff54cd97c7d36f661a3cd14bd18182ccb
3,602,618
def extract_image_number(filename: str, from_file: bool) -> int: """ finds the number of the image from the original images of LITIV 2014 dataset. :param filename: name of the image file. :param from_file: filename is read from a ground-truth file or not. :return: number. """ number = filena...
e55431beffb02959907106a01596310812ba7363
3,602,619
def subarraySum(nums, k): """ Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. """ count = 0 s = 0 for i in range(len(nums)): s += nums[i] if s % k == 0: count += 1 return count
6bbad5ec5511f8563fc951aa916f76a6297946ba
3,602,620
def traffic_sign_detection_noisy(img_in): """Finds all traffic signs in a synthetic noisy image. The image may contain at least one of the following: - traffic_light - no_entry - stop - warning - yield - construction Use these names for your output. See the instructions docume...
50a5430fbe793a6bc863c92378c44522822ce7a3
3,602,621
def get_planet_variables(mc, theta, verbose=False): """ Derived parameters from the Common Models are listed :param mc: :return: """ try: n_samplings, n_pams = np.shape(theta) except: n_samplings = 1 stellar_values = get_stellar_parameters(mc, theta) planet_variabl...
573a84f22734508d22d9887155fc28604fe2079a
3,602,623
def get_container_by_container_id(container_id): """ lookup task id based on matching container id :param container_id: str. container_id is a unique string generated by the docker daemon for each instance of a container :return: str. task id """ if len(container_id) <= 12: query = '...
8e53a998e917ed6929bcee7116ebdc0f3297bddd
3,602,625
def calculate_arc_length(x1, x2, origin): """ Calculate the arc length between points x1 and x2. :param x1, x2: points coordinates. :return: arc length """ r1 = vector.addVectors([x1, origin], [1, -1]) r2 = vector.addVectors([x2, origin], [1, -1]) radius = vector.magnitude(r1) angle ...
cef209b2b1556700416131e56230bd37196ac956
3,602,626
def find(data,fwhm=4,thresh=4000) : """ Star finding using DAOStarfinder """ daofind = DAOStarFinder(fwhm=fwhm,threshold=thresh) sources=daofind(data) sources.rename_column['xcentroid','x'] sources.rename_column['ycentroid','y'] return sources
befde70505c3567e86d1b33cdb22bacfab19129b
3,602,627
import functools from datetime import datetime def cache(ttl=CACHE_DEFAULT_TTL): """ TTL Cache Decorator Parameters ---------- ttl: datetime.timedelta Time-To-Live Returns ------- function Wrapped Function """ def wrap(func): cached = {} @functool...
f2fbbeb4368ee629b4be4383d7ad80a49c03577f
3,602,628
def make_ro_state(f): """ Build a read-only State instance and pass to `f` as the `state` kwarg if the `state` kwarg is None. Function `f` should have have at least two kwargs, `user` and `state`. """ @wraps(f) def state_check(self, *args, **kwargs): state = kwargs.pop('state', None) ...
4df20a8c81eed81b47fd10c92379ec8d58d0ec8a
3,602,629
def get_changes_by_project(changes): """ Break changes into a dict of dicts keyed by project """ changes_by_project = defaultdict(dict) for change in changes: changes_by_project[change.project][change.long_id] = change return changes_by_project
76923ce721df8d68fc96ff63cf49a9aac3b0dce4
3,602,630
from typing import Any from typing import Callable from io import StringIO def yaml_dumps(value: Any, get_yaml_obj: Callable[[], YAML] = get_yaml) -> str: """Converts the object to yaml. :param value: the object to convert. :param get_yaml_obj: A function such as :func:`get_yaml` that will be called ...
b12390989fc4c64722c38c8931f90906c8261991
3,602,631
def aaa_check_compute_auth_token(cookie, in_token, in_user): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("AaaCheckComputeAuthToken") method.cookie = cookie method.in_token = in_token method.in_user = in_user xml_request = method.to_xml(option=WriteXmlOption.DIRTY) re...
8e837e873ef4ca76f53f91e7ce92de79be568b3f
3,602,632
def page_size(request, page_size): """ Changes page size in user preferences""" try: u, created = User.objects.get_or_create(user=request.user.id) u.pagesize = page_size u.save() return HttpResponse('saved pagesize %s' % page_size) except Exception, inst: return H...
0e5bf12142d678481829ea3136d20a559db7c366
3,602,633
def fail_on_npm_install(): """ Used to simulate an error when executing "npm install" """ return 1
ea0b2b14487acf8b9833e84374de469a1b22b61a
3,602,634
def calculateNetIncome(gross, state): """ Calculate the net income after federal and state tax :param gross: Gross Income :param state: State Name :return: Net Income """ state_tax = {'LA': 10, 'SA': 0, 'NY': 9} # Calculate net income after federal tax net = gross - (gross * .10) ...
915528d8bfd15c18003eaeb8f6b3f1e8ad5565a0
3,602,635
def calc_se3_torch_batch(poses_src, poses_tgt): """Bx3x4.""" # B = poses_src.shape[0] se3_src2tgt_batch = se3_mul_torch_batch(poses_tgt, se3_inverse_torch_batch(poses_src)) return se3_src2tgt_batch
d5f2ce006ac08e8c92c463c3631a76e7574fd4c0
3,602,636
from typing import Union def _rescale_proba(p: Union[float, pd.Series], min: float, max: float) -> Union[float, pd.Series]: """Performs min-max-scaling on a probability value""" return np.abs((p - min) / (max - min))
caacf603c5a02af15fd6bd640c79f3d3379d46b0
3,602,637
def build_tree(train: list, max_depth: int, min_size: int) -> dict: """ Build a decision tree :param train: dataset used to build the tree :param max_depth: of the desired tree :param min_size: of the terminal nodes :return: """ class_values = list(set(row[-1] for row in dataset)) ro...
0a6170795677d41e0080aaff80c5758049789341
3,602,638
def field_size(field_label): """ Helper function to determine the size of a binary table field Parameters ---------- field_label : PVLModule The field label Returns ------- int : The size of the one entry in bytes """ data_sizes = { 'Intege...
afaff70bc18d4d9d023fb7c89d45560f1a691bcf
3,602,639
def definite_range(): """Create test fixture for Definite Range.""" return DefiniteRange(min=22, max=33)
0296dd02adc5e890a0d6a020b1772ad0df91c76f
3,602,640
def WaitForOperation(resources, service, operation, collection, resource_ref, message): """Waits for the operation to finish. Args: resources: The resource parser. service: apitools.base.py.base_api.BaseApiService, the service representing the target of the operation. operati...
90de3bc3c6d49be10aee94af6eb55fcb6cc738aa
3,602,642
def ListInstancesDNS(region, instances=None, node_types=[], states=[], names=[]): """Return a list of DNS names for instances matching the arguments. If instance IDs are specified and one or more is not found, an EC2ResponseError exception is thrown. """ return [i.public_dns_name for i in ListInstances(region, ...
20337bcbb97ca1a3602ec34276b1fb96b2e07747
3,602,644
def _calc_trans_distor(X: np.ndarray, labels: np.ndarray, Y: float) -> float: """ Calculate transformed distortion function for the jump method """ _, means, _ = calc_stat_per_batch(X, labels) distor = (((X - means.T[labels,:]) ** 2).sum() / X.shape[0] / X.shape[1]) trans_distor = distor ** (-Y) re...
bcbc697833eb65c48abf9ba2e324c493a323c17a
3,602,645
def bencode(thing): """ bencodes the given object, returning a bytes object containing the bencoded data. Allowed object types are: - list (list) - dictionary (dict) - integer (int) - string (str) - bytes object (bytes) Note that all strings will be converted to byte objects du...
e1c08941a37ce19873e50c33c682ecefbd24073c
3,602,648
def slowSort(array): """Sort an array the slow (but certain) way""" cpy = np.copy(array) ind = np.arange(0, len(array)) for i in xrange(len(cpy)): for j in xrange(len(cpy)): if cpy[i] > cpy[j] and i < j: # Swap the copy array values tmp = cpy[i] ...
b110f6aa797c5ab64309a1e982de561445377f33
3,602,649
def GetBankElementSummary(bank_element): """ Summarizes the bank element params: bank_element = value of the object of type bank_element_t returns: String with summary of the type. """ format_str = "{0: <#020x} {1: <16s} {2: <16d} {3: <16d}" if bank_element.be_type == 0: out_strin...
b14b9a9cb7744bc02958573bc22009fe075e893e
3,602,650
def test_input(ctx): """ To get custom user input! input: Yes/No If yes it stores value in user_input of context """ if ctx.get("user_input"): print("We got: ", ctx.get("user_input")) return val = input("Say yes: ") if val == "yes": ctx["user_input"] = val return RepeatStatement()
28250a05ede180b7d8948a50d6ded526270b1b4f
3,602,651
def _reference_before_setitem(self, key, value): # type: (Object, str, Any) -> Tuple[str, Any] """ This hook allows for the use of any arbitrary attribute, as specified in the `patternProperties` for this object in the OpenAPI schema """ if key != "$ref": _add_property(self, key) ret...
38f5ff3bc96cddac89d3dea6008c9df63835d587
3,602,652
from typing import List def _input_fn(file_pattern: List[Text], data_accessor: tfx.components.DataAccessor, tf_transform_output: tft.TFTransformOutput, batch_size: int = 200) -> tf.data.Dataset: """Generates features and label for tuning/training. Args: file_pattern:...
8afcf39ff01f8b9b3c643b4b4adccaf1c3586f4f
3,602,653
def leading_by(agents, player): """Determine difference between player's score and closest opponent.""" scores = [a.score() for a in agents] player_score = scores[player] scores.sort() if player_score == scores[-1]: return player_score - scores[-2] else: return player_score - sco...
e97aa0a1109bb2ba5f276f34030ea1f93022046f
3,602,654
import torch def smiles2graph(mol): """ Converts SMILES string or rdkit's mol object to graph Data object without remove salt :input: SMILES string (str) :return: graph object """ if isinstance(mol, Chem.rdchem.Mol): pass else: mol = Chem.MolFromSmiles(mol) # atoms ...
2547a07ca8f3beec6681b15c87666197fd58181a
3,602,655
def is_valid(t: float): """ Returns a `bool` indicating if the given value for a t parameter is valid. A t parameter is valid if in the [0, 1] range. :param t: `float` t parameter value :return: `bool` is the t value valid? """ return False if t < MIN or t > MAX else True
6e3ee60136ead77a9bc4ff6b84e3986f5b0532b3
3,602,657
def get_bid2sid(offsets, stc_lens): """ :param offsets: list of 1 tensor, offsets by doc :param stc_lens: list of 1 list, stc length :return: bid2sid: dict of int, blank id 2 stc id, both start from 0 """ bid2sid, acc_len = dict(), 0 sid = 0 for bid, offset in enumerate(offsets[0]): ...
a5a96d3ea6c7fcb17a97df706799fe0716ae659b
3,602,658
import random def generate_easy_alphanumeric_string(): """ Generates an "easy" alphanumeric (lower case) string of length 8 without the 0 (zero) character. This is a design decision, because users will have to type in the "easy" string on mobile devices, so we have made this a string that is easy to t...
76c1b5e51344f726dffcd2800b31349427268f22
3,602,659
def create_abbreviations(metagraph): """Creates abbreviations for node and edge kinds.""" kind_to_abbrev = find_abbrevs(metagraph.node_dict.keys()) kind_to_abbrev = {kind: abbrev.upper() for kind, abbrev in kind_to_abbrev.items()} edge_set_to_keys = dict() for edge in list(metagraph.edge_dict.keys(...
98eb8c0e158b592990a4850263a93be08d41f3a4
3,602,660
def mk_seealso( function_name: str, role: str = "func", prefix: str = "\n\n", module_location: str = ".", ) -> str: """ Returns a sphinx `seealso` pointing to a function. Intended to be used for building custom fitting model docstrings. .. admonition:: Usage example for a custom fittin...
0165599829e8edd3f75adcda9402069066a0381a
3,602,662
import torch def get_accuracy(prototypes, embeddings, targets): """Compute the accuracy of the prototypical network on the test/query points. Parameters ---------- prototypes : `torch.FloatTensor` instance A tensor containing the prototypes for each class. This tensor has shape `(met...
f196820e28258a24ed84a10b4829f3be6a0d68d8
3,602,663
def take_step(obj, step): """ Takes a step towards a target obj """ temp_obj = getattr_or_get(obj, step) if 'id' in step: # if the step is an ID, we need to get the object represented by that id model_str = step.split('_')[0].lower().capitalize() if model_str != 'User': ...
4366977af518df512c433c057bb3d675a3b8d6c9
3,602,664
def mock_xibo_api(mocker): """Return a mock XiboApi.""" return mocker.MagicMock()
8c2ad1566ad716d9fb4dd680a624e59f89950a0a
3,602,665
def get_corpus_archive_name(cycle: int) -> str: """Returns a corpus archive name given a cycle.""" return 'corpus-archive-%04d.tar.gz' % cycle
3068ce88bd85f2c21819da697a2b1147f547c509
3,602,666
def _fn_tanh_ ( self , b = 1 ) : """ Hyperbolic tangent function: f = tan(ab) >>> f = >>> a = f.tanh ( ) >>> a = f.tanh ( b ) >>> a = tanh ( f ) """ return _fn_make_fun_ ( self , b , Ostap.Mor...
d64cab6625f9a50e2e568a5cb275e7b11d4b6b32
3,602,667
from typing import Iterable def mpp_transformer(origin, origin_mpp, aim_mpp): """transform numbers according to mpp :param origin: original numbers :param origin_mpp: original mpp :param aim_mpp: aim mpp :return: transed numbers """ if isinstance(origin, Iterable): transed = [] ...
64955bbc22821990e1087622b23ba46e90ab86bd
3,602,668
def solve(input_grid): """ Here we have solve function that takes the input grid. Every even steps we move the cells around to swap the digits on the currently processed grid """ _output_grid = to_output_array(input_grid) _, n_cols = get_shape_of_array(input_grid) for i in range(n_cols)...
65867f0a80314aab328180d7d070f4b0c61a3d3c
3,602,669
def rank_equality(y_true, y_pred, groups): """Compute the rank equality error between two rankings. Parameters ---------- y_true : array-like of shape = (n_samples) Ground truth (correct) target values. y_pred : array-like of shape = (n_samples) Estimated target values. groups...
a599e82dd1ea795dce6513b36f0fc24d379f1a8a
3,602,670
def distributionCorrection(df, channel): """ Resample file pairs in a dataframe. df: pd.DataFrame channel: str Column name of the values for resampling. Returns: estimated_true_positives: pd.DataFrame To Do: Make a more generic function, or at least pull...
56488b5d12119c62b6f36e20f7158d57f937fff1
3,602,671
from typing import Optional def get_cluster(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClusterResult: """ Resource Type definition for AWS::MSK::Cluster """ __args__ = dict() __args__['arn'] = arn if opts is None: opts = pulum...
888bac8b40daa72a7b27532bdc94de6f38b156d4
3,602,672
def one_step(site, DOY, herb_class, available_forage, prop_legume, supp_available, supp, intake=None, force_supp=None): """One step of the forage model, with one herbivore type, if available forage does not change.""" row = [] herb_class.calc_distance_walked(site.S, herb_class.stocking_den...
f924f6f2cc2c5bd9175254677c7ef973030edbb1
3,602,673
def array_replace(space, w_arr, args_w): """ Replaces elements from passed arrays into the first array """ for i, w_arr in enumerate(args_w): if w_arr.tp != space.tp_array: space.ec.warn("array_replace_recursive(): Argument #%d " "should be an array" % (i+1)) ...
bab04d17733a12418b248e6f72e9dc053b263ac7
3,602,674
def upsample(inputs, out_shape, data_format): """ Upsamples to `out_shape` using nearest neighbor interpolation. """ if data_format == 'channel_first': inputs = tf.transpose(inputs, [0, 2, 3, 1]) new_height = out_shape[3] new_width = out_shape[2] else: new_height ...
0916d0e1b2033690c4d38a80842795c3d7ca44b8
3,602,675
from typing import Iterable from typing import List def _setup_config_sources(spec: YapconfSpec, cli_vars: Iterable[str]) -> List[str]: """Sets the sources for configuration loading Args: spec: Yapconf specification cli_vars: Command line arguments Returns: List of configuration ...
8f193cc03750707f330b542e3d168399ac75b07d
3,602,677
def get_transform(_split): """Frames train(test) transformation.""" if "test" in _split or "val" in _split: transform_fn = transforms.Compose([ transforms.Resize(cfg.TEST.IM_SIZE, interpolation=BICUBIC), transforms.CenterCrop(cfg.TRAIN.IM_SIZE), transforms.Normalize(...
7433f23a2e6f4cad1be4b89ce61ee7f58e51b508
3,602,678
def _chase_up(start_time, interval): """Utility function to check if there are missed intervals. :param start_time: A time object representing the starting time. :param interval: An integer specifying the time interval in seconds. :returns: Number of seconds to sleep before next round. """ end_...
cf04c16e48ba05a6d7d68841298ef1a8e5976fa6
3,602,679