content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_transceiver_sensor_sub_id(ifindex, sensor): """ Returns sub OID for transceiver sensor. Sub OID is calculated as folows: sub OID = transceiver_oid + XCVR_SENSOR_PART_ID_MAP[sensor] :param ifindex: interface index :param sensor: sensor key :return: sub OID = {{index}} * 1000 + {{lane}} * ...
4c718feb45384ab6bef11e1f3c42ab4cd8d0ae2c
21,500
def patch_twitter_get_following_users(value): """Return a function decorator which patches the TwitterClient.get_following_user_ids method.""" return patch_twitter_client_method("get_following_user_ids", value)
296d20a3dbce3684cb2af2568c64fac25ab345c9
21,501
def conv1x1_1d(inplanes: int, outplanes: int, stride: int = 1) -> nn.Conv1d: """1x1一维卷积,用于短接时降采样""" return nn.Conv1d( inplanes, outplanes, kernel_size=(1,), stride=(stride,), padding=0, bias=False )
481dc7b71b31ae6199bcafd1112bf1541d7a5d25
21,502
import hashlib import os def load_cifar10(channels_last=True, x_shape=None, x_dtype=np.float32, y_dtype=np.int32, normalize_x=False): """ Load the CIFAR-10 dataset as NumPy arrays. Args: channels_last (bool): Whether or not to place the channels axis at the last? ...
d730abf0de556a8990289e92359c5d31df6c0e9c
21,503
import struct def unpack_mmap_block(mm, n): """Decode the nth 4-byte long byte string from mapped memory.""" return struct.unpack("<L", mm[n*DATA_BLOCK_SIZE:(n+1)*DATA_BLOCK_SIZE])[0]
a75ac48e188e03e1ec7d3c289ffdd8e12173bc6f
21,504
def tobs(): """Return a list of temperatures for prior year""" # * Query for the dates and temperature observations from the last year. # * Convert the query results to a Dictionary using `date` as the key and `tobs` as the value. # * Return the json representation of your dictionary. las...
c7411130bb5c8d956d10a2ba3ce535f41ca04474
21,505
def reactToAMQPMessage(message, send_back): """ React to given (AMQP) message. `message` is expected to be :py:func:`collections.namedtuple` structure from :mod:`.structures` filled with all necessary data. Args: message (object): One of the request objects defined in ...
fd34510d58e6b164f37f93c0b17f2b2a1c8d32d2
21,506
def recE(siEnergy, layer): """ Reconstructed energy from sim energy """ return ( (siEnergy/mipSiEnergy) * layerWeights[layer-1] + siEnergy)*\ secondOrderEnergyCorrection
9efde4432f3a81ff06505c6fbb529be7404027d4
21,507
def get_account_id(): """ Retrieve the AWS account ID """ client = boto3.client("sts") account_id = client.get_caller_identity()["Account"] return account_id
579bdc686a0ceb5d71e180bf8ce7a17243cff849
21,508
def process_tag(item, profile, level=0): """ Processes element with <code>tag</code> type @type item: ZenNode @type profile: dict @type level: int """ if not item.name: # looks like it's root element return item attrs = make_attributes_string(item, profile) cursor = profile['place_cursor'] and zen_codin...
7d06160cadb0d828799713d888327a41e7ab0b80
21,509
from typing import Optional import google def read_secret(project_id: str, secret_name: str) -> Optional[str]: """Reads the latest version of a GCP Secret Manager secret. Returns None if the secret doesn't exist.""" secret_manager = secretmanager.SecretManagerServiceClient() secret_path = secret_man...
388fa51983452f0852646d1ed1ab183da706c0ab
21,510
import xml def find_in_xml(data, search_params): """Try to find an element in an xml Take an xml from string or as xml.etree.ElementTree and an iterable of strings (and/or tuples in case of findall) to search. The tuple should contain the string to search for and a true value. """ if isinstan...
1cb4685a042349231cd946116a4894ca5b9d68d5
21,511
def conditional_expect( X, func, reg, method=None, quantile_method=None, n_integration_samples=10, quad_dict=None, random_state=None, include_x=False, include_idx=False, vector_func=False, ): """Calculates the conditional expectation, i.e. E[func(Y)|X=x_eval], where Y...
fb89adedeada5e100f2483d927d945ffe2d99034
21,512
def getSumOfSquaresPixel16_Image16(Image): """getSumOfSquaresPixel16_Image16(Image) -> unsigned __int16""" return _ImageFunctions.getSumOfSquaresPixel16_Image16(Image)
9ba21171e26fc32d938a3f377684830df5f03b8f
21,513
def parse_statement(parsed, output): """Parses a tokenized sql_parse token and returns an encoded table.""" # Get the name of the table being created table_name = next(token.value for token in parsed.tokens if isinstance(token, Identifier)) # Add the table metadata to the cached tables to access later. ...
a81791deac59e496145993bba0547294d5d5a7fa
21,514
def create_hue_success_response(entity_number, attr, value): """Create a success response for an attribute set on a light.""" success_key = f"/lights/{entity_number}/state/{attr}" return {"success": {success_key: value}}
c8570ca95ada89bd26d93f659261c91032c915c7
21,515
import warnings def get_deaths(): """***DEPRECATED - Use get_data_jhu instead.*** Get most recent fatality counts from JHU.""" # Deprecated warning url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/" warnings.warn("This function is...
c747d27b10d0845520f4dbbfbb5efcf23c655b7e
21,516
def transform_sentence(text, model): """ Mean embedding vector """ def preprocess_text(raw_text, model=model): """ Excluding unknown words and get corresponding token """ raw_text = raw_text.split() return list(filter(lambda x: x in model.vocab, raw_text)) ...
57f9002e4f7fccefa824f1691324b4593b11fbe0
21,517
from typing import Sequence from typing import List import inspect def model_primary_key_columns_and_names(Model: DeclarativeMeta) -> (Sequence[Column], List[str]): """ Get the list of primary columns and their names as two separate tuples Example: pk_columns, pk_names = model_primary_key_columns_an...
9466524452a77459042081e7becf968302b3dd3b
21,518
def biweekly_test_data(): """ Provides test data for the full system test when using "biweekly" time_scale.""" time_scale = "biweekly" time_per_task = { "Free" : 480 * 9 * 2, "Work" : 480 * 5 * 2, "Sleep" : 480 * 7 * 2 } min_task_time = 60 preferences = { "Free" :...
b5f354a17819133c3c29e7652f6b1132599e89b6
21,519
def plot_bar_whiskers_jitter_significance(data, comparison_columns, significant_comparison_columns, heights, ylabel, xlabels=None, ax_handle=None, ...
dfdaf95034d3d53fac7c79eb4c7b387f9ac18f5b
21,520
def _is_trans_valid(seed, mutate_sample): """ Check a mutated sample is valid. If the number of changed pixels in a seed is less than pixels_change_rate*size(seed), this mutate is valid. Else check the infinite norm of seed changes, if the value of the infinite norm less than pixel_value_change_rate...
118dc0e566fc4f5c481d21f8c8aec7fe4f1ece29
21,521
def split_axis(x, indices_or_sections, axis): """Splits given variables along an axis. Args: x (tuple of Variables): Variables to be split. indices_or_sections (int or 1-D array): If this argument is an integer, N, the array will be divided into N equal arrays along axis. ...
245841aaef14ea130b20254775152a9199d63c41
21,522
def status(**kwargs): """Execute \"git status\" on the repository.""" status = check_output(["git", "status"]).decode("utf-8") repo_clean = True for keyword in ["ahead", "modified", "untracked"]: if keyword in status: repo_clean = False return {"clean": repo_clean, "status": st...
8e81264579628407e8560a6d89be884179636ea9
21,523
import os import tqdm def preprocessing_raw_csv(PATH=".//tcdata//hy_round2_train_20200225//", local_file_name="train.pkl"): """Loading and processing all train csv data.""" if PATH is None: raise ValueError("Invalid PATH !") file_names = sorted(os.listdir(PATH), key=lambd...
774e3865bac16458439fe597d4a5a5a745957a9c
21,524
from typing import Counter def find_listener_frequent_words(df, num): """ Given a conversation dataframe from a certain subreddit, find the top frequent words spoken by listeners. Args: df: A specified dataframe from a subreddit. num: A ranking number used for finding the top frequent wor...
80bc4b95e5713429751ff1725afce4ac02f0bddd
21,525
def is_rescue_entry(boot_entry): """ Determines whether the given boot entry is rescue. :param BootEntry boot_entry: Boot entry to assess :return: True is the entry is rescue :rtype: bool """ return 'rescue' in boot_entry.kernel_image.lower()
ba456c2724c3ad4e35bef110ed8c4cc08147b42c
21,526
import base64 def estimate_cost(features, ssd): """Generate a TensorFlow subgraph to estimate the cost of an architecture. Args: features: A 1D float tensor containing features for a single network architecture. ssd: The name of the search space definition to use for the cost model. Returns: ...
2c85cc5d320cd214dae260793a1c779d8019177c
21,527
def short_bubble(l, debug=True): """ what if the whole list is already in ascending order, the bubble would then still go through the entire outer loops actually, if there is no swap happens in a certain iteration ( the inner loop), the next loop should stop :param l: :param debug: :return: ...
d79ec7311e8a08267ddcbe82d08a85b35b9d4a6f
21,528
import yaml def IsResourceLike(item): """Return True if item is a dict like object or list of dict like objects.""" return yaml.dict_like(item) or (yaml.list_like(item) and all(yaml.dict_like(x) for x in item))
bc6ae6c4d84949511c679116454343731e8d8bd2
21,529
import math def rad_to_gon(angle: float) -> float: """Converts from radiant to gon (grad). Args: angle: Angle in rad. Returns: Converted angle in gon. """ return angle * 200 / math.pi
cbf7070a9c3a9796dfe4bffe39fdf2421f7279ed
21,530
def check_interface_status(conn_obj, interface, state, device="dut"): """ API to check the interface state Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param conn_obj: :param interface: :param state: :param device: :return: """ interface_state = get_interface_sta...
484c1a8dcf96a3160791a63979d47096e5e51fbc
21,531
def hungarian_match(self, y_true, y_pred): """Matches predicted labels to original using hungarian algorithm.""" y_true = self.adjust_range(y_true) y_pred = self.adjust_range(y_pred) D = max(y_pred.max(), y_true.max()) + 1 w = np.zeros((D, D), dtype=np.int64) # Confusion matrix. fo...
29a9976edcfa4a935d451f6471641b3836343d83
21,532
import torch def orthantree(scaled, capacity=8): """Constructs a :ref:`tree <presolve>` for the given :func:`~pybbfmm.scale`'d problem. This is a bit of a mess of a function, but long story short it starts with all the sources allocated to the root and repeatedly subdivides overfull boxes, constructing t...
9813697be3b19a2d7e3b71f28b1212c91a590fd3
21,533
def make_sparse( docs_to_fit, min_df=50, stop_words=None, docs_to_transform=None, ngram_range=None, ): """ Take a pre-tokenized document and turn into a sparse matrix. :param docs_to_fit: A list of lists of tokenized words to build the vocabulary from. :param min_df: Number of records th...
467d04f465ed4c19b4e20aa69c05508f6faafdc6
21,534
import random def weightedPriorityReliabilityScore(service_instances, last_records): """ Algorithm to find highest priority of the service based on reliability score achieved in past discovery results """ priority_list = [] for i in range(0, len(service_instances)): sin...
e215ae3e4009de7e8e6e8a8a0b66a66238e30f16
21,535
def calculate_output(param_dict, select_device, input_example): """Calculate the output of the imported graph given the input. Load the graph def from graph file on selected device, then get the tensors based on the input and output name from the graph, then feed the input_example to the graph and retrieve...
e98bf63743d7f940170ca7ab4dcd97b751be178f
21,536
def is_instance_failed_alarm(alarms, instance, guest_hb=False): """ Check if an instance failed alarm has been raised """ expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_FAILED, 'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL} return _instance_alarm_raised(alarms...
5c886bea0b72d52392ed38217af20b7ebc87bd91
21,537
from modules.plumedwrapper import io as plumedio import os def load_metad_fes(fes_dir_path): """Load all the PLUMED free energy profiles saved by sumhills.""" # Read the FES in time. fes_file_prefix_path = os.path.join(fes_dir_path, 'fes_') fes_time = plumedio.read_table(fes_file_prefix_path + 'time....
29e341193670e1ff82e33d1ab818f7df8a4d9042
21,538
def detected(numbers, mode): """ Returns a Boolean result indicating whether the last member in a numeric array is the max or min, depending on the setting. Arguments - numbers: an array of numbers - mode: 'max' or 'min' """ call_dict = {'min': min, 'max': max} if mode not in ca...
b0a5b19e7d97db99769f28c4b8ce998dbe318c5b
21,539
import math def calculate_compass_bearing(point_a, point_b): """ Calculates the bearing between two points. The formulae used is the following: θ = atan2(sin(Δlong).cos(lat2), cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong)) :Parameters: - `pointA: The tuple repres...
535fc0cfc086974b1e329df297bdbea4aab1f127
21,540
import re def parse_instructions(instruction_list): """ Parses the instruction strings into a dictionary """ instruction_dict = [] for instruction in instruction_list: regex_match = re.match(r"(?P<direction>\w)(?P<value>\d*)",instruction) if regex_match: instruction_dic...
67b773bae0cb2cc0509503f2ea27f3312ce9d41c
21,541
def calc_elapsed_sleep(in_num, hyp_file, fpath, savedir, export=True): """ Calculate minutes of elapsed sleep from a hypnogram file & concatenate stage 2 sleep files Parameters ---------- in_num: str patient identifier hyp_file: str (format: *.txt) file with hypnogram at 30-sec...
61390b205c7dcbd65884e8f073f1b1395f1d1ca2
21,542
def valid_pairs(pairs, chain): """ Determine if the chain contains any invalid pairs (e.g. ETH_XMR) """ for primary, secondary in zip(chain[:-1], chain[1:]): if not (primary, secondary) in pairs and \ not (secondary, primary) in pairs: return False return True
c9e36d0490893e1b1a6cd8c3fb0b14b382d69515
21,543
import os import json def setup(sub_args, ifiles, repo_path, output_path): """Setup the pipeline for execution and creates config file from templates @param sub_args <parser.parse_args() object>: Parsed arguments for run sub-command @param repo_path <str>: Path to installation or source co...
30a45285d09ba2d7e919c918fa2e67f67c3b57e6
21,544
from typing import Any def fqname_for(obj: Any) -> str: """ Returns the fully qualified name of ``obj``. Parameters ---------- obj The class we are interested in. Returns ------- str The fully qualified name of ``obj``. """ if "<locals>" in obj.__qualname__: ...
6d4e5db255715c999d1bb40533f3dbe03b948b07
21,545
import time import io import zipfile import os def analyzer_zipfile(platform, monitor): """Creates the Zip file that is sent to the Guest.""" t = time.time() zip_data = io.BytesIO() zip_file = zipfile.ZipFile(zip_data, "w", zipfile.ZIP_STORED) # Select the proper analyzer's folder according to t...
4c302ce81f1a3a18bfda9681e1761e246a6de42a
21,546
def symbol_size(values): """ Rescale given values to reasonable symbol sizes in the plot. """ max_size = 50.0 min_size = 5.0 # Rescale max. slope = (max_size - min_size)/(values.max() - values.min()) return slope*(values - values.max()) + max_size
a33f77ee8eeff8d0e63035c5c408a0788b661886
21,547
from datetime import datetime def delete(id): """Soft delete a patient.""" check_patient_permission(id) patient = Patient.query.get(id) patient.deleted = datetime.datetime.now() patient.deleted_by = current_user db.session.commit() return redirect(url_for('screener.index'))
0e9c984bb8bf8429c662f1af14945089789b8bc8
21,548
import os import tempfile def system_temp_dir(): """ Return the global temp directory for the current user. """ temp_dir = os.getenv('SCANCODE_TMP') if not temp_dir: sc = text.python_safe_name('scancode_' + system.username) temp_dir = os.path.join(tempfile.gettempdir(), sc) cre...
14c82a59d049068042d10845f63c61f53879259b
21,549
from typing import List from typing import Callable from typing import Union import os import click def _pipeline_network_multiple_database(database: List[str], kernel_method: Callable, filter_network_omic: Union[List, str]) -> Union[Matrix, str]: """Process network for a m...
60f454aee74f5d2779d3a54fdcfb119637c73919
21,550
import torch import tensorflow as tf def _to_tensor(args, data): """Change data to tensor.""" if vega.is_torch_backend(): data = torch.tensor(data) if args.device == "GPU": return data.cuda() else: return data elif vega.is_tf_backend(): data = tf.con...
77d87982c81232bac4581eb5269629c268a7fe16
21,551
def materialize_jupyter_deployment( config: ClusterConfig, uuid: str, definition: DeploymentDefinition) -> JupyterDeploymentImpl: # noqa """Materializes the Jupyter deployment definition. :param config: Cluster to materialize the Jupyter deployment with. :param uuid: Unique...
d4a12efd7d4f55d5261734cf3eb0dd3b230c363d
21,552
def _CreateLSTMPruneVariables(lstm_obj, input_depth, h_depth): """Function to create additional variables for pruning.""" mask = lstm_obj.add_variable( name="mask", shape=[input_depth + h_depth, 4 * h_depth], initializer=tf.ones_initializer(), trainable=False, dtype=lstm_obj.dtype) ...
398dd89a9b8251f11aef3ba19523e26861ff5874
21,553
def get_index_fredkin_gate(N, padding = 0): """Get paramaters for log2(N) Fredkin gates Args: - N (int): dimensional of states - padding (int, optional): Defaults to 0. Returns: - list of int: params for the second and third Frekin gates """ indices = [] for i in range(...
d7ab1f4bc414ad741533d5fabfb0f7c8b4fe0959
21,554
def import_by_name(name): """ 动态导入 """ tmp = name.split(".") module_name = ".".join(tmp[0:-1]) obj_name = tmp[-1] module = __import__(module_name, globals(), locals(), [obj_name]) return getattr(module, obj_name)
714ca90704d99a8eafc8db08a5f3df8e17bc6da4
21,555
def f1_score(y_true, y_pred): """F-measure.""" p = precision(y_true, y_pred) r = true_positive_rate(y_true, y_pred) return 2 * (p * r) / (p + r)
e5f79def2db902bb0aa1efd9ea1ccef52b62072a
21,556
def hexColorToInt(rgb): """Convert rgb color string to STK integer color code.""" r = int(rgb[0:2],16) g = int(rgb[2:4],16) b = int(rgb[4:6],16) color = format(b, '02X') + format(g, '02X') + format(r, '02X') return int(color,16)
59b8815d647b9ca3e90092bb6ee7a0ca19dd46c2
21,557
import torch def test(model, X, model_type, test_type, counter=False): """Test functions.""" if model_type == 'notear-mlp': X = np.vstack(X) y = model(torch.from_numpy(X)) y = y.cpu().detach().numpy() mse = mean_squared_loss(y.shape[0], y[:, 0], X[:, 0]) elif model_type == 'notear-castle': ...
cb98e2096052270e786bbb81fafc328076b1aa40
21,558
def scale(): """ Returns class instance of `Scale`. For more details, please have a look at the implementations inside `Scale`. Returns ------- Scale : Class instance implementing all 'scale' processes. """ return Scale()
f5fb9daf9baaf86674be110aae78b1bf91f09371
21,559
def imread_rgb(filename): """Read image file from filename and return rgb numpy array""" bgr = cv2.imread(filename) rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) return rgb
6fcef3f9f5d8b02c28c596f706f3e1fcf685dd24
21,560
def insert_at_index(rootllist, newllist, index): """ Insert newllist in the llist following rootllist such that newllist is at the provided index in the resulting llist""" # At start if index == 0: newllist.child = rootllist return newllist # Walk through the list curllist = rootllist for i in ran...
767cde29fbc711373c37dd3674655fb1bdf3fedf
21,561
def kpi_value(request, body): """kpi值接口 根据 indicator 传入参数不同请求不同的 handler""" params = { "indicator": body.indicator } handler = KpiFactory().create_handler(params["indicator"]) result = handler(params=params) return DashboardResult(content=result)
5f242028d7f95b1ffa81690c3ed1b1d7006cf97c
21,562
def safeReplaceOrder( references ): """ When inlining a variable, if multiple instances occur on the line, then the last reference must be replaced first. Otherwise the remaining intra-line references will be incorrect. """ def safeReplaceOrderCmp(self, other): return -cmp(self.colno, o...
dae29bf1c8da84c77c64210c4d897ac4a9d0c098
21,563
from typing import Union from typing import Iterable import time from typing import List from typing import Any import requests def broken_link_finder(urls: Union[str, list, tuple, set], print_to_console: bool = False, file_out = None, viewer = DEFA...
2cbbe3c40d2d78e68144c03dcb93f2f2ac6feb83
21,564
def clean_value(value: str) -> t.Union[int, float, str]: """Return the given value as an int or float if possible, otherwise as the original string.""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: pass return value
52c09e2aaf77cb22e62f47e11226350112390eb2
21,565
import types def sumstat(*L): """ Sums a list or a tuple L Modified from pg 80 of Web Programming in Python """ if len(L) == 1 and \ ( isinstance(L[0],types.ListType) or \ isinstance (L[0], types.TupleType) ) : L = L[0] s = 0.0 for k in L: s = s + k ...
c37aa0aa0b7dbf6adbe77d82b27b25e469891795
21,566
def halref_to_data_url(halref: str) -> str: """ Given a HAL or HAL-data document URIRef, returns the corresponding HAL-data URL halref: str HAL document URL (Most important!) https://hal.archives-ouvertes.fr/hal-02371715v2 -> https://data.archives-ouvertes.fr/document/hal-02371715v...
48ef6629fc3198af2c8004a3dbcbbde6e700cb12
21,567
def find_best_rate(): """ Input: Annual salary, semi-annual raise, cost of home Assumes: a time frame of three years (36 months), a down payment of 25% of the total cost, current savings starting from 0 and annual return of 4% Returns the best savings rate within (plus/minus) $100 of the downpayme...
451fc72c006182b63233376a701b4cbb855ad39a
21,568
def q_inv(a): """Return the inverse of a quaternion.""" return [a[0], -a[1], -a[2], -a[3]]
e8d06e7db6d5b23efab10c07f4b9c6088190fa07
21,569
def divide_hex_grid_flower(points, hex_radius=None): """Partitions a hexagonal grid into a flower pattern (this is what I used for the final product. Returns a list of partition indices for each point.""" if hex_radius is None: # copied from build_mirror_array() mini_hex_radius = (10 * 2.5 / 2) + 1 ...
9f77e85d4bbfd00ea5eff6905209aad84e3a9191
21,570
def fis_gauss2mf(x:float, s1:float, c1:float, s2:float, c2:float): """Split Gaussian Member Function""" t1 = 1.0 t2 = 1.0 if x < c1: t1 = fis_gaussmf(x, s1, c1) if x > c2: t2 = fis_gaussmf(x, s2, c2) return (t1 * t2)
443e02dff7ab3827ac0006443964f45a6f9f4ce2
21,571
def _is_trigonal_prism(vectors, dev_cutoff=15): """ Triangular prisms are defined by 3 vertices in a triangular pattern on two aligned planes. Unfortunately, the angles are dependent on the length and width of the prism. Need more examples to come up with a better way of detecting this shape. For now, this...
2b3ffb318b3201923828eea8f4769a6ce854dd58
21,572
import os def get_sza(times, rad, mask=None): """ Fetch sza at all range cell in radar FoV rad: Radar code mask: mask metrix """ fname = "data/sim/{rad}.geolocate.data.nc.gz".format(rad=rad) os.system("gzip -d " + fname) fname = fname.replace(".gz","") data = Dataset(fname) lat...
2b3ecd5c07ba00cbaae3274ade46925a5ad377dc
21,573
def load_results(path): """ return a dictionary of columns can't use genfromtex because of weird format for arrays that I used :param path: :return: """ data = defaultdict(list) column_casts = { "epoch": float, "env_name": str, "game_counter": int, "game...
a4015d37d41353d41c5044d84249ad2e0700d7dc
21,574
def priority(n=0): """ Sets the priority of the plugin. Higher values indicate a higher priority. This should be used as a decorator. Returns a decorator function. :param n: priority (higher values = higher priority) :type n: int :rtype: function """ def wrapper(cls): cls...
58ab19fd88e9e293676943857a0fa04bf16f0e93
21,575
import math def vecangle(u,v): """ Calculate as accurately as possible the angle between two 3-component vectors u and v. This formula comes from W. Kahan's advice in his paper "How Futile are Mindless Assessments of Roundoff in Floating-Point Computation?" (https://www.cs.berkeley.edu/~wkahan/Mindles...
dde6ebed830130f122b0582d4c19963a061a3d31
21,576
def sanitize_option(option): """ Format the given string by stripping the trailing parentheses eg. Auckland City (123) -> Auckland City :param option: String to be formatted :return: Substring without the trailing parentheses """ return ' '.join(option.split(' ')[:-1]).strip()
ece0a78599e428ae8826b82d7d00ffc39495d27f
21,577
def node_values_for_tests(): """Creates a list of possible node values for parameters Returns: List[Any]: possible node values """ return [1, 3, 5, 7, "hello"]
b919efc5e59a5827b3b27e4f0a4cd070ceb9a5a4
21,578
import torch def computeGramMatrix(A, B): """ Constructs a linear kernel matrix between A and B. We assume that each row in A and B represents a d-dimensional feature vector. Parameters: A: a (n_batch, n, d) Tensor. B: a (n_batch, m, d) Tensor. Returns: a (n_batch, n, m) Tensor....
c9b221b3d6a8c7a16337178a1f148873b27ec04a
21,579
def parse_config(config): """Backwards compatible parsing. :param config: ConfigParser object initilized with nvp.ini. :returns: A tuple consisting of a control cluster object and a plugin_config variable. raises: In general, system exceptions are not caught but are propagated up to the...
74689d11c1d610a9211dc5895ff42a8b8e2389ae
21,580
def deletable_proxy_user(request, onefs_client): """Get the name of an existing proxy user that it is ok to delete.""" return _deletable_proxy_user(request, onefs_client)
c7440099fe4435cf9b5b557253f7fb9563dc600c
21,581
import six def get_from_module(identifier, module_params, module_name, instantiate=False, kwargs=None): """The function is stolen from keras.utils.generic_utils. """ if isinstance(identifier, six.string_types): res = module_params.get(identifier) if not res: ...
406a1da5843feb8556bbd1802426b57e7a33b20d
21,582
def color_lerp(c1, c2, a): """Return the linear interpolation between two colors. ``a`` is the interpolation value, with 0 returing ``c1``, 1 returning ``c2``, and 0.5 returing a color halfway between both. Args: c1 (Union[Tuple[int, int, int], Sequence[int]]): The first color. At...
96c950c447994a729c9eb4c18bdcc60976dbb675
21,583
def get_equations(points): """ Calculate affine equations of inputted points Input : 1 points : list of list ex : [[[x1, y1], [x2, y2]], [[xx1, yy1], [xx2, yy2]]] for 2 identified elements Contains coordinates of separation lines i.e. [[[start poin...
4eea43aee8b5f9c63793daae0b28e3c8b4ce0929
21,584
def Temple_Loc(player, num): """temple location function""" player.coins -= num player.score += num player.donation += num # player = temple_bonus_check(player) for acheivements return (player)
dced7b9f23f63c0c51787291ab12701bd7021152
21,585
def indexGenomeFile(input, output): """Index STAR genome index file `input`: Input probes fasta file `output`: SAindex file to check the completion of STAR genome index """ #print input #print output base = splitext(input)[0] base = base + ".gtf" #print base gtfFile = base o...
2ebd981ebad97f68adb1043e9c06fd01dc270c10
21,586
import math def performance(origin_labels, predict_labels, deci_value, bi_or_multi=False, res=False): """evaluations used to evaluate the performance of the model. :param deci_value: decision values used for ROC and AUC. :param bi_or_multi: binary or multiple classification :param origin_labels: true ...
aac87e0bdc02b61ccb5136e04e1ac8b09e01ce65
21,587
def rotkehlchen_instance( uninitialized_rotkehlchen, database, blockchain, accountant, start_with_logged_in_user, start_with_valid_premium, function_scope_messages_aggregator, db_password, rotki_premium_credentials, accounting_data_dir, ...
144585d62c04f97aa7bcb7a355bd90f8ff001022
21,588
def store_inspection_outputs_df(backend, annotation_iterators, code_reference, return_value, operator_context): """ Stores the inspection annotations for the rows in the dataframe and the inspection annotations for the DAG operators in a map """ dag_node_identifier = DagNodeIdentifier(operator_conte...
228a24a4d59162382b5a3ae7d8204e396b8c76dd
21,589
def switched (decorator): """decorator transform for switched decorations. adds start_fun and stop_fun methods to class to control fun""" @simple_decorator def new_decorator (fun): event = new_event() def inner_fun (self, *args): if args: event.wait() if threads_alive(): retu...
1996274fcaba2095b43f7d0da134abb59b2f7a56
21,590
def logistic_embedding0(k=1, dataset='epinions'): """using random embedding to train logistic Keyword Arguments: k {int} -- [folder] (default: {1}) dataset {str} -- [dataset] (default: {'epinions'}) Returns: [type] -- [pos_ratio, accuracy, f1_score0, f1_score1, f1_score2, auc_score...
69b198c6a5f8a44681ccfee67b532b3d38d2ee44
21,591
def process_plus_glosses(word): """ Find all glosses with a plus inside. They correspond to one-phoneme affix sequences that are expressed by the same letter due to orthographic requirements. Replace the glosses and the morphemes. """ return rxPartsGloss.sub(process_plus_glosses_ana, word)
0678efc61d1af0ec75b8d0566866b305b6312448
21,592
from datetime import datetime def check_in_the_past(value: datetime) -> datetime: """ Validate that a timestamp is in the past. """ assert value.tzinfo == timezone.utc, "date must be an explicit UTC timestamp" assert value < datetime.now(timezone.utc), "date must be in the past" return value
a439295190bfa2b6d2d6de79c7dc074df562e9ed
21,593
import os def fixture(filename): """ Get the handle / path to the test data folder. """ return os.path.join(fixtures_dir, filename)
7a14e173993b3f226ca71ea335ee153512e3df7d
21,594
from typing import Dict def character_count_helper(results: Dict) -> int: """ Helper Function that computes character count for ocr results on a single image Parameters ---------- results: Dict (OCR results from a clapperboard instance) Returns ------- Int Number...
b5bcba9d39b7b09a1a123fec034ab1f27b31d1eb
21,595
import pickle def from_pickle(input_path): """Read from pickle file.""" with open(input_path, 'rb') as f: unpickler = pickle.Unpickler(f) return unpickler.load()
4e537fcde38e612e22004007122130c545246afb
21,596
def PromptForRegion(available_regions=constants.SUPPORTED_REGION): """Prompt for region from list of available regions. This method is referenced by the declaritive iam commands as a fallthrough for getting the region. Args: available_regions: list of the available regions to choose from Returns: T...
2298fde743219f59b5a36844d85e14929d1e2a1e
21,597
def update(x, new_x): """Update the value of `x` to `new_x`. # Arguments x: A `Variable`. new_x: A tensor of same shape as `x`. # Returns The variable `x` updated. """ return tf.assign(x, new_x)
363cd3232a57d4c2c946813874a5a3c613f9a8c9
21,598
def r1r2_to_bp(r1,r2,pl=0.01, pu=0.25): """ Convert uniform samling of r1 and r2 to impact parameter b and and radius ratio p following Espinoza 2018, https://iopscience.iop.org/article/10.3847/2515-5172/aaef38/meta Paramters: ----------- r1, r2: float; uniform parameters in from u(...
0c7f69f3f7960792e8d0ecd75fde028eda9feefa
21,599