content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=-1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True): """Incremental Network Quantization Affine Layer During training...
7654d925a13276002419c9d08342e4e7974bdc31
19,623
def is_greater_equal(min_value): """Check if the attribute value is greater than or equal to a minimum value. This validator can handle both lists and single element attributes. If it is a list, it checks if the element with the smallest value is greater than or equal to the specified minimum value. ...
a95cc24afcae6d11689b872f2178f6b38b864ca7
19,624
from typing import List def save_lyrics(list_: List[Text], location: Text) -> None: """Writes 'list_' to 'location' as txt file. Returns None.""" with open(location, "w+") as f: for element in list_: f.write(element) f.write("\n") return None
1fff7cf838fdaea32f6875beab90b172a84f379c
19,625
def translate_provider_for_icon(sync_server, project, site): """ Get provider for 'site' This is used for getting icon, 'studio' should have different icon then local sites, even the provider 'local_drive' is same """ if site == sync_server.DEFAULT_SITE: return sync_server....
58867a6dd44c83582d85fc1baf48121eff714232
19,626
def server_delete_ip(body=None): # noqa: E501 """delete server IP Send by server during shutdown. # noqa: E501 :param body: port of iperf server. Ip and time could be emply :type body: dict | bytes :rtype: List[InlineResponse200] """ if connexion.request.is_json: body = ServerAdd...
92b2f425ae7cca1e3e42c58382f3d21b2e96f016
19,627
import re def extract_key_and_index(field): """Returns the key type, key name and if key is a compound list then returns the index pointed by the field Arguments: field: csv header field """ for key_type, value in KEY_TYPES.items(): regex = re.compile(value["regex"]) match = rege...
aba66922117cd14f2c670df839c3ca522856caa3
19,628
import torch def as_mask(indexes, length): """ Convert indexes into a binary mask. Parameters: indexes (LongTensor): positive indexes length (int): maximal possible value of indexes """ mask = torch.zeros(length, dtype=torch.bool, device=indexes.device) mask[indexes] = 1 r...
0235d66f9ee5bdc7447819122b285d29efd238c9
19,629
def interpolate_array(x, y, smooth_rate=500): """ :param x: :param y: :return: """ interp_obj = interpolate.PchipInterpolator(x, y) new_x = np.linspace(x[0], x[-1], smooth_rate) new_y = interp_obj(new_x) return new_x, new_y
4c6f79c3071496e6314d772651d2e6cc6a449c74
19,630
from typing import Sequence from typing import Counter import copy def calculate_resource_utilization_for_slaves( slaves: Sequence[_SlaveT], tasks: Sequence[MesosTask] ) -> ResourceUtilizationDict: """ Given a list of slaves and a list of tasks, calculate the total available resource available in that lis...
13b4856b3ef0bdf06410a58ecc0fbc29bfda4483
19,631
def check_pass(value): """ This test always passes (it is used for 'checking' things like the workshop address, for which no sensible validation is feasible). """ return True
aa3a5f536b5bc729dc37b7f09c3b997c664b7481
19,632
def state_array_to_int(s): """translates a state s into an integer by interpreting the state as a binary represenation""" return int(state_array_to_string(s), 2)
b0b50dd879b74af27946cde49e1bf805c2d6e504
19,633
import asyncio import traceback def async_task(coro, loop=asyncio.get_event_loop(), error_cb=None): """ Wrapper to always print exceptions for asyncio tasks. """ future = asyncio.ensure_future(coro) def exception_logging_done_cb(future): try: e = future.exception() ex...
5520aafebca17cbe32c79b69e41856f6076179f3
19,634
def is_valid_charts_yaml(content): """ Check if 'content' contains mandatory keys :param content: parsed YAML file as list of dictionary of key values :return: True if dict contains mandatory values, else False """ # Iterate on each list cell for chart_details in content: # If one ...
cc68ba6bc9166f8d2f8c37da756accec667f471a
19,635
def get_trader_fcas_availability_agc_status_condition(params) -> bool: """Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS.""" # Check AGC status if presented with a regulating FCAS offer if params['trade_type'] in ['L5RE', 'R5RE']: # AGC is active='1', AGC is ina...
fa73ae12a0934c76f12c223a05161280a6dc01f1
19,636
import importlib def load_class(full_class_string): """ dynamically load a class from a string """ class_data = full_class_string.split(".") module_path = ".".join(class_data[:-1]) class_str = class_data[-1] module = importlib.import_module(module_path) # Finally, we retrieve the Cla...
95ab0a0b27d508b5bd41468cf6a4e3c008799fdf
19,637
def request_credentials_from_console(): """ Requests the credentials interactive and returns them in form (username, password) """ username = raw_input('Username: ') password = raw_input('Password: ') return username, password
43102d8528502f700ab96714831c94abb6a3b0f8
19,638
def prettify_url(url): """Return a URL without its schema """ if not url: return url split = url.split('//', 1) if len(split) == 2: schema, path = split else: path = url return path.rstrip('/')
0beed0522355e4ea8170cac22e61f92e0c21ccca
19,639
def CDLMORNINGDOJISTAR(data: xr.DataArray, penetration: float = 0.3) -> xr.DataArray: """ Morning Doji Star (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Parameters: penetration: 0.3 Outputs: double series (values are -1, 0 or 1) """ return multi...
be1f4954dda5109d067070fc97c340233085b043
19,640
def panerror_to_dict(obj): """Serializer function for POCS custom exceptions.""" name_match = error_pattern.search(str(obj.__class__)) if name_match: exception_name = name_match.group(1) else: msg = f"Unexpected obj type: {obj}, {obj.__class__}" raise ValueError(msg) return ...
8841d2c4b6f3ba1deae5057a6b85b70830c412a1
19,641
from typing import Optional def build_class_instance(module_path: str, init_params: Optional[dict] = None): """ Create an object instance from absolute module_path string. Parameters ---------- module_path: str Full module_path that is valid for your project or some external package. ...
d50ffdbb8bbeed36b572e6e555376febabecb745
19,642
def maintainers_mapper(maintainers, package): """ Update package maintainers and return package. https://docs.npmjs.com/files/package.json#people-fields-author-contributors npm also sets a top-level "maintainers" field with your npm user info. """ # note this is the same code as contributors_map...
57e76ec2cbc1727778bfe980c5cd6d82798a1800
19,643
def calc_original_pressure(pressure_ratio): """ calculates the original pressure value given the <code>AUDITORY_THRESHOLD</code>. The results are only correct if the pressure ratio is build using the <code>AUDITORY_THRESHOLD</code>. :param pressure_ratio: the pressure ration that shall be converted to ...
1a0680073cb739fef47952887e6dedf4487f2aa0
19,644
def normalize_field_names(fields): """ Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text' """ return set(s.replace('_','').lower() for s in fields)
55bdac50fd1fcf23cfec454408fbcbbae96e507e
19,645
def powspec_disc_n(n, fs, mu, s, kp, km, vr, vt, tr): """Return the n'th Lorentzian and its width""" Td = ifana.LIF().Tdp(mu, s, vr, vt) + tr Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km) kpbar = (kp*(Td-tr)-log(Ppp))/Td return 1./Td * 2*kpbar/(kpbar**2 + (2*pi*(fs - n*1./Td))**2), kpbar
60335e496b734c32116424d857a3c59de7f5b567
19,647
def list_keys(request): """ Tags: keys --- Lists all added keys. READ permission required on key. --- """ auth_context = auth_context_from_request(request) return filter_list_keys(auth_context)
564d03457265c0461e82b55abfb23cb4d45ad0ac
19,648
def rounder(money_dist: list, pot: int, to_coin: int = 2) -> list: """ Rounds the money distribution while preserving total sum stolen from https://stackoverflow.com/a/44740221 """ def custom_round(x): """ Rounds a number to be divisible by to_coin specified """ return int(to_coin *...
f315027def4646252aa7d4ee7c05ca3085625583
19,649
def find_wcscorr_row(wcstab, selections): """ Return an array of indices from the table (NOT HDU) 'wcstab' that matches the selections specified by the user. The row selection criteria must be specified as a dictionary with column name as key and value(s) representing the valid d...
dcd2b4025ec3756319911e6626dd403a6efda1c4
19,650
import urllib def _gftRead(url, step): """ Reads in a gtf file from a specific db given the url. Some gft have a certain number of header lines that are skipped however. Input: url where gtf is fetched from Input: number of lines to skip while reading in the frame ...
ef05d2747188def526612bdd27931e0420e275dd
19,652
def add() -> jsonify: """ Adds a new item in the server and returns the updated list to the front-end """ # Passed Items from Front-End name = request.form['name'] priority = request.form['priority'] price = request.form['price'].replace(",", "") # To prevent string to float conversion ...
e8a32aa47ee057c6f9653554955cddd0b003ef1a
19,653
def calculate(formula, **params): """ Calculate formula and return a dictionary of coin and amounts """ formula = Formula.get(formula) if formula is None: raise InvalidFormula(formula) if not formula.expression: return {} return calculate_expression(formula.expression, formula, **p...
e8a237d2677581296bb1491badecf83264c0d44a
19,655
import torch def pack_batch_tensor(inputs): """default pad_ids = 0 """ input_max_length = max([d.size(0) for d in inputs]) # prepare batch tensor input_ids = torch.LongTensor(len(inputs), input_max_length).zero_() input_mask = torch.LongTensor(len(inputs), input_max_length).zero_() for i, ...
33e59acbc8facaf41064e2dd7031bdd314211878
19,656
def build_network(network_class=None, dataset_dirs_args=None, dataset_dirs_class=None, dataset_dirs=None, dataset_spec_args=None, dataset_spec_class=None, dataset_spec=None, network_spec_args=No...
4fae693408b385629c6ae645c69778276c16b915
19,657
def lookup_service_root(service_root): """Dereference an alias to a service root. A recognized server alias such as "staging" gets turned into the appropriate URI. A URI gets returned as is. Any other string raises a ValueError. """ if service_root == EDGE_SERVICE_ROOT: # This will trig...
8cc5384ba26639438e4c7e18264fb39ee2445fcf
19,659
import warnings def get_initial_configuration(): """ Return (pos, type) pos: (1, 1) - (9, 9) type will be 2-letter strings like CSA format. (e.g. "FU", "HI", etc.) """ warnings.warn( """get_initial_configuration() returns ambiguous cell state. Use get_initial_configuration_...
c96f7f70e258d09090abeffc9815082265245cf2
19,660
def request_pull_to_diff_or_patch( repo, requestid, username=None, namespace=None, diff=False ): """Returns the commits from the specified pull-request as patches. :arg repo: the `pagure.lib.model.Project` object of the current pagure project browsed :type repo: `pagure.lib.model.Project` :...
a7b543294cb66561700b7db7800277d74ed1267c
19,661
def GL(alpha, f_name, domain_start = 0.0, domain_end = 1.0, num_points = 100): """ Computes the GL fractional derivative of a function for an entire array of function values. Parameters ========== alpha : float The order of the differintegral to be computed. ...
226d5d8b49be9a243ac4508a7691c8997503cb4d
19,662
def check_lint(root_dir, ignore, verbose, dry_run, files_at_a_time, max_line_len, continue_on_error): """Check for lint. Unless `continue_on_error` is selected, returns `False` on the first iteration where lint is found, or where the lint checker otherwise returned failure. :return:...
c43b7a05bf47b9108281bb7c0cef4ff1d6e107d3
19,663
def remove_comments(s): """ Examples -------- >>> code = ''' ... # comment 1 ... # comment 2 ... echo foo ... ''' >>> remove_comments(code) 'echo foo' """ return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#"))
1d3e1468c06263d01dd204c5ac89235a17f50972
19,664
def generate_wsl(ws): """ Generates watershed line that correspond to areas of touching objects. """ se = square(3) ero = ws.copy() ero[ero == 0] = ero.max() + 1 ero = erosion(ero, se) ero[ws == 0] = 0 grad = dilation(ws, se) - ero grad[ws == 0] = 0 grad[grad > 0] = 255 ...
6d61b2b366ca6a4b94f8a6513f1a0a5fb1bfd8c9
19,665
def train_lstm_model(x, y, epochs=200, patience=10, lstm_dim=48, batch_size=128, lr=1e-3): """ Train an LSTM to predict purchase (1) or abandon (0) :param x: session sequences :param y: target label...
159ad99e419d659e655bcdd9556a6ae3202071ae
19,666
def nash_sutcliffe_efficiency(predicted, observed): """ implements Nash-Sutcliffe Model Efficiencobserved Coefficient where predicted is modeled and observed is observed""" if np.isnan(np.min(predicted)) or np.isnan(np.min(observed)): return np.asarray([np.nan]) return 1 - np.sum((predicted - observed)**2) / np.su...
b9820cf95472499d6e6c24e47ffb4bbd5574e439
19,667
def tf_Affine_transformer(points, theta): """ Arguments: points: `Matrix` [2, np] of grid points to transform theta: `Matrix` [bs, 2, 3] with a batch of transformations """ with tf.name_scope('Affine_transformer'): num_batch = tf.shape(theta)[0] grid = tf.tile(tf.expand_d...
a024609ac386b7d12173fb3965233ae4c21233d2
19,668
def read_COCO_gt(filename, n_imgs=None, ret_img_sizes=False, ret_classes=False, bbox_gt=False): """ Function for reading COCO ground-truth files and converting them to GroundTruthInstances format. :param filename: filename of the annotation.json file with all COCO ground-truth annotations :param n_imgs:...
dfcfa69ee620ac3546b1f646c9c23f126a9822c3
19,669
def get_metrics_from_file(metric_file): """Gets all metric functions within a file :param str metric_file: The name of the file to look in :return: Tuples containing (function name, function object) :rtype: list """ try: metrics = import_module(metric_file) metrics = get_sorted_...
12e59feb03b6d8571fb7a5ef8f02e81e53605b0b
19,670
def mnist_model(inputs, mode): """Takes the MNIST inputs and mode and outputs a tensor of logits.""" # Input Layer # Reshape X to 4-D tensor: [batch_size, width, height, channels] # MNIST images are 28x28 pixels, and have one color channel inputs = tf.reshape(inputs, [-1, 28, 28, 1]) data_format = 'channels...
7807adce4030d070c79eea5f3a1991ff4c4e1cd6
19,671
import base64 import io def show_local_mp4_video(file_name, width=640, height=480): """Renders a mp4 video on a Jupyter notebook Args: file_name (str): Path to file. width (int): Video width. height (int): Video height. Returns: obj: Video render as HTML object. """ ...
4f2b4660b005edcf865eca1c6632ffa6c0899fe8
19,672
from datetime import datetime def change_status(sid, rev, status, **kwargs): """ [INCOMPLETE] - DISABLE OTHER REVISION OF THE SAME SIGNTURE WHEN DEPLOYING ONE Change the status of a signature Variables: sid => ID of the signature rev => Revision number of the signature ...
dce934db6c7fe34e184ff98a63f2bc5e32efaffe
19,673
from re import X def trilinear_interpolation(a: np.ndarray, factor: float) -> np.ndarray: """Resize an three dimensional array using trilinear interpolation. :param a: The array to resize. The array is expected to have at least three dimensions. :param factor: The amount to resize the array. ...
a3ed2c13f13bdc37cbe47cd7ed6862a67cdebd66
19,674
def load_data(path): """将材料的label与text进行分离,得到两个list""" label_list = [] text_list = [] with open(path, 'r') as f: for line in f.readlines(): data = line.strip().split('\t') data[1] = data[1].strip().split() label = [0 for i in range(8)] total = 0 ...
2274e0e327844c4dedae229b3c03a344653f7342
19,675
def invoke(request): """Where the magic happens...""" with monitor(labels=_labels, name="transform_request"): transformed_request = _transform_request(request) with monitor(labels=_labels, name="invoke"): response = _model.predict(transformed_request) with monitor(labels=_labels, name...
4547de901cfd2cc153ea67632c2a002a17a15d8b
19,676
def munge_pocket_response(resp): """Munge Pocket Article response.""" articles = resp['list'] result = pd.DataFrame([articles[id] for id in articles]) # only munge if actual articles present if len(result) != 0: result['url'] = (result['resolved_url'].combine_first(result['given_url'])) ...
32695526a784cc95aeb428ca2481dcf9053e72ed
19,678
import time def fake_data_PSBL_phot(outdir='', outroot='psbl', raL=259.5, decL=-29.0, t0=57000.0, u0_amp=0.8, tE=500.0, piE_E=0.02, piE_N=0.02, q=0.5, sep=5.0, phi=75.0, b_sff1=0.5, mag_src1=16.0, p...
bde4d98d0936be3b0cd655879bbfdbde2e1a5826
19,680
import pathlib def is_dicom(path: pathlib.Path) -> bool: """Check if the input is a DICOM file. Args: path (pathlib.Path): Path to the file to check. Returns: bool: True if the file is a DICOM file. """ path = pathlib.Path(path) is_dcm = path.suffix.lower() == ".dcm" is_...
1e20ace9c645a41817bf23a667bd4e1ac815f63f
19,681
from typing import Optional def _hessian(model: 'BinaryLogReg', data: Dataset, data_weights: Optional[jnp.ndarray]) -> jnp.ndarray: """Ravelled Hessian matrix of the objective function with respect to the model parameters""" params_flat, unravel = ravel_pytree(model.params) random_params = model.random_pa...
5824fe0d2def5d03e8ac3f773641d19d6aebfa3e
19,682
import re def promax2meta(doc, target): """ Return meta information (Line or Area) of csv Promax geometry file. Arguments: doc -- csv Promax geometry file target -- meta information to get (Line or Area) """ ptarget = r'' + re.escape(target) + r'\s*[=:]\s*\"?([\w-]+)\"?' for line in o...
7dce362112aa7fb6fa24999c4f870107b24c3d40
19,683
def axLabel(value, unit): """ Return axis label for given strings. :param value: Value for axis label :type value: int :param unit: Unit for axis label :type unit: str :return: Axis label as \"<value> (<unit>)\" :rtype: str """ return str(value) + " (" + str(unit) + ")"
cc553cf4334222a06ae4a2bcec5ec5acb9668a8f
19,684
import hashlib import time def save_notebook(filename, timeout=10): """ Force-saves a Jupyter notebook by displaying JavaScript. Args: filename (``str``): path to notebook file being saved timeout (``int`` or ``float``): number of seconds to wait for save before timing-out Returns ...
4d02f1eb48459c412a119fcab7d8df7515c1b465
19,685
def test_gen(): """Create the test system.""" project_name = "test_grid_sinfactory" return PFactoryGrid(project_name=project_name).gens["SM1"]
cd8009b55bfced7fbafc2914b80e0dd2cd2851fc
19,686
def validate_api_key(): """Validates an API key submitted via POST.""" api_key_form = ApiKeyForm() api_key_form.organization.choices = session['orgs_list'] if api_key_form.validate_on_submit(): session['org_id'] = api_key_form.organization.data return jsonify(True) return jsonify(api...
1cf72017600222992cb9d622c6b718b8dc84bae8
19,687
def plot_clickForPlane(): """ Create a Plane at location of one mouse click in the view or onto a clicked object or at a pre-selected point location: Create a Plane perpendicular to the view at location of one mouse click. - Click first on the Button then click once on the View. - Click first on...
62acc0e41ce165047f6dabf99d0df8fd2b1db000
19,688
def is_logged_in(f): """ is logged in decorator """ @wraps(f) def wrap(*args, **kwargs): """ wrap from template """ if 'logged_in' in session: return f(*args, **kwargs) else: flash('Unauthorized, Please login', 'danger') ret...
732bf60bf0901fc341f81c3e6db3516052ecfd12
19,689
def dataframe_from_mult_files(filenames): """@param filenames (List[Str]): list of filenames""" dfs = [] for filename in filenames: dfs.append(dataframe_from_file(filename)) return pd.concat(dfs, axis=0)
76f37d5cef6a8b44946ef25536a135db339beca6
19,690
def batch_euclidean_dist(x, y, min_val): """ euclidean_dist function over batch x and y are batches of matrices x' and y': x' = (x'_1, | x'_2 | ... | x'_m).T y' = (y'_1, | y'_2 | ... | y'_n).T Where x_i and y_j are vectors. We calculate the distances between each pair x_i and y_j. res'[i, j] ...
1eec65330ba8970fd84c7d9c7c57e91cd79e0e6f
19,691
def outgroup_reformat(newick, outgroup): """ Move the location of the outgroup in a newick string to be at the end of the string Inputs: newick --- a newick string to be reformatted outgroup --- the outgroup Output: newick --- the reformatted string """ # Replace the outgroup and co...
a45be59deb95d7bb61ea82a111d4390e49d4b7a8
19,692
def get_source_token(request): """ Perform token validation for the presqt-source-token header. Parameters ---------- request : HTTP request object Returns ------- Returns the token if the validation is successful. Raises a custom AuthorizationException error if the validation fail...
db53bba32f8471a17d44fae2d3f44749d5a83c86
19,693
def read_train_valid(filename): """ 读取训练或者验证文件 :param filename: 训练集/验证集的文件名字 :return: 返回训练集的文本和标签 其中文本是一个list, 标签是一个list(每个元素为int) 返回示例:['我很开心', '你不是真正的快乐', '一切都是假的], [1, 0, 0] """ fp = pd.read_table(filename, sep='\t', error_bad_lines=False) return fp['review'].tolist(), list(...
f6990db50453e4dd88f8ecd13e1eb345ab15fc87
19,694
def weighted_regularization_matrix_from( regularization_weights: np.ndarray, pixel_neighbors: np.ndarray, pixel_neighbors_sizes: np.ndarray, ) -> np.ndarray: """ From the pixel-neighbors, setup the regularization matrix using the weighted regularization scheme. Parameters ---------- reg...
ecc6301e327adc608530c933ae769bd92ffcaf84
19,695
def child_at_time( self, search_time, shallow_search=False, ): """Return the child that overlaps with time search_time. search_time is in the space of self. If shallow_search is false, will recurse into compositions. """ range_map = self.range_of_all_children() # find...
5961a6d20a962b7b698822610bf4cecdf9c33257
19,696
def weight_variable_truncated_normal(input_dim, output_dim, name=""): """Create a weight variable with truncated normal distribution, values that are more than 2 stddev away from the mean are redrawn.""" initial = tf.truncated_normal([input_dim, output_dim], stddev=0.5) return tf.Variable(initial, name...
4c645fc5a914ff99f5b1063f5ecc0b4878481517
19,697
def get_dummy_vm_create_spec(client_factory, name, data_store_name): """Builds the dummy VM create spec.""" config_spec = client_factory.create('ns0:VirtualMachineConfigSpec') config_spec.name = name config_spec.guestId = "otherGuest" vm_file_info = client_factory.create('ns0:VirtualMachineFileInf...
6564197d319b87f0a9dd05ae3053de6ebc11cf5c
19,698
def test_comparison_ops_eq_t(): """Check the equal-to operator for a truthy result.""" return """ fn main() { {dest} = 1 == 1; } """
1d6562c26b1103deaf3a8eed4bc8d341a4a7d3e0
19,699
def binary_accuracy(*, logits, labels): """Accuracy of binary classifier, from logits.""" p = jax.nn.sigmoid(logits) return jnp.mean(labels == (p > 0.5))
f7795c8d7a945e5e5e97475888cf9e5b65aa1415
19,700
def extract_tag(inventory, url): """ extract data from sphinx inventory. The extracted datas come from a C++ project documented using Breathe. The structure of the inventory is a dictionary with the following keys - cpp:class (class names) - cpp:function (functions or class methods)...
dcda1869fb6a44bea3b17f1d427fe279ebdc3a11
19,702
def strip_parens(s): """Strip parentheses around string""" if not s: return s if s[0] == "(" and s[-1] == ")": return strip_parens(s[1:-1]) else: return s
ee4c9ce6ee769a86a2e2e39159aa9eaa5fd422c6
19,703
import ast def custom_eval(node, value_map=None): """ for safely using `eval` """ if isinstance(node, ast.Call): values = [custom_eval(v) for v in node.args] func_name = node.func.id if func_name in {"AVG", "IF"}: return FUNCTIONS_MAP[func_name](*values) eli...
a9ff29455ee90a83f5c54197633153d5b9d0fdbc
19,704
def validate_dict(input,validate): """ This function returns true or false if the dictionaries pass regexp validation. Validate format: { keyname: { substrname: "^\w{5,10}$", subintname: "^[0-9]+$" } } Validates that keyname exists, and that it contains a substrname that is 5-10 word characters, an...
0a221f5586f4464f4279ab4ce3d22019e247659b
19,705
def build_windows_and_pods_from_events(backpressure_events, window_width_in_hours=1) -> (list, list): """ Generate barchart-friendly time windows with counts of backpressuring durations within each window. :param backpressure_events: a list of BackpressureEvents to be broken up into time windows :param...
78adebe54d883a7251c04e250f7c14e47043d40e
19,706
import requests import json def package_search(api_url, org_id=None, params=None, start_index=0, rows=100, logger=None, out=None): """ package_search: run the package_search CKAN API query, filtering by org_id, iterating by 100, starting with 'start_index' perform package_search by owner_org: https://...
642a869931d45fe441a146cb8e931dc530170c37
19,707
def voigt_fit(prefix,x,slice,c,vary): """ This function fits a voigt to a spectral slice. Center value can be set to constant or floated, everything else is floated. Parameters: prefix: prefix for lmfit to distinguish variables during multiple fits x: x values to use in fit slice: slice to be f...
034810cb6a0ac8efb311182df3d65cf0bd6002d9
19,708
from typing import List def turn_coordinates_into_list_of_distances(list_of_coordinates: List[tuple]): """ Function to calculate the distance between coordinates in a list. Using the 'great_circle' for measuring here, since it is much faster (but less precise than 'geodesic'). Parameters ----...
5fdc0198b533604ec3d935224c7b2b634670083e
19,709
import json def getPileupDatasetSizes(datasets, phedexUrl): """ Given a list of datasets, find all their blocks with replicas available, i.e., blocks that have valid files to be processed, and calculate the total dataset size :param datasets: list of dataset names :param phedexUrl: a string wi...
48d77aa47998204ff99df188ef830cae647ac9b9
19,710
def convertpo(inputpofile, outputpotfile, template, reverse=False): """reads in inputpofile, removes the header, writes to outputpotfile.""" inputpo = po.pofile(inputpofile) templatepo = po.pofile(template) if reverse: swapdir(inputpo) templatepo.makeindex() header = inputpo.header() ...
6954354db5ca9c660e326eeae23906853743eb57
19,711
def do_fk5(l, b, jde): """[summary] Parameters ---------- l : float longitude b : float latitude jde : float Julian Day of the ephemeris Returns ------- tuple tuple(l,b) """ T = (jde - JD_J2000) / CENTURY lda = l - deg2rad(1.397)*T - deg2...
2ccc96aab8ddfcbe93d7534a01b0f262c0330053
19,712
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.8 ** (epoch // 1)) for param_group in optimizer.param_groups: param_group['lr'] = lr return lr
ce4b5a3aa70ab07791af3bd41e14758e568fb1cc
19,713
import yaml def get_defaults(module, *args): """ Find an internal defaults data file, load it using YAML, and return the resulting dictionary. Takes the dot-separated module path (e.g. "abscal.wfc3.reduce_grism_extract"), splits off the last item (e.g. ["abscal.wfc3", "reduce_grism_extract"...
a92e37f75c4f967c2b23391a817fb14118b89a8f
19,714
import shlex def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if _tryorder is None: with _lock: if _tryorder is None: register_standard_browsers() if using is not None: alternatives = [using] else: altern...
12c2ca5fdd93964527330a0694d69a8d4e84ee12
19,715
import binascii def _bin_to_long(x): """ Convert a binary string into a long integer This is a clever optimization for fast xor vector math """ return int(binascii.hexlify(x), 16)
54b50ffea715bf127eabd7e82aada36e4717c288
19,716
def update_book(username, book_id, data): """Update book data""" cursor, conn = db_sql.connect('books.db') keys = list(data.keys()) sql = ("UPDATE " + username + " SET " + " = ?, ".join(keys) + " = ? WHERE _id = ?") temp_list = [] for key in keys: temp_list.append(data[key]) ...
2dcc2970cec8f53c90c72f341092f7cb7c7d6232
19,717
def score_retrievals(label, retrievals): """ Evaluating the current retrieval experiment Args: ----- label: string label corresponding to the query retrivals: list list of strings containing the ranked labels corresponding to the retrievals tot_labels: integer number ...
c9a3a24c2c6e5a2986387db88710da43984bd862
19,718
def default_add_one_res_2_all_res(one_res: list, all_res: list) -> list: """ 默认函数1: one_res 增加到all_res :param one_res: :param all_res: :return: """ for i in one_res: for j in i: all_res.append(j) return all_res
9c2e83ffaa7c67759f8b3d7cf30354d7cf7ca030
19,719
from typing import Iterable import re def search_gene(search_string: str, **kwargs) -> Iterable[Gene]: """ Symbols have been separated into search_gene_symbol - this returns Gene objects """ CONSORTIUM_REGEX = { r"(ENSG\d+)": AnnotationConsortium.ENSEMBL, r"Gene:(\d+)": AnnotationConsortium.R...
768c6ac712b6660b78b2bead3be6f0000541696f
19,720
def check_logged(request): """Check if user is logged and have the permission.""" permission = request.GET.get('permission', '') if permission: has_perm = request.user.has_perm(permission) if not has_perm: msg = ( "User does not have permission to exectute this ac...
2cf03f7336b7c8814fd380aae5209b0b8fe6dca9
19,723
def _deprecated_configs(agentConfig): """ Warn about deprecated configs """ deprecated_checks = {} deprecated_configs_enabled = [v for k, v in OLD_STYLE_PARAMETERS if len([l for l in agentConfig if l.startswith(k)]) > 0] for deprecated_config in deprecated_configs_enabled: msg = "Configuring...
e47a47a1a7dd40d04a21927730479500f934a1d1
19,724
def check_number_of_calls(object_with_method, method_name, maximum_calls, minimum_calls=1, stack_depth=2): """ Instruments the given method on the given object to verify the number of calls to the method is less than or equal to the expected maximum_calls and greater than or equal to the expected minimum_ca...
64bdc512753b159128e34aa7c95d60a741745fce
19,725
def _get_span(succ, name, resultidx=0, matchidx=0, silent_fail=False): """ Helper method to return the span for the given result index and name, or None. Args: succ: success instance name: name of the match info, if None, uses the entire span of the result resultidx: index of the re...
1fc6208f1aa7289a53e4e64c041abb71498a2eeb
19,727
import random def gen_k_arr(K, n): """ Arguments: K {int} -- [apa numbers] n {int} -- [trial numbers] """ def random_sel(K, trial=200): count_index = 0 pool = np.arange(K) last = None while count_index < trial: count_index += 1 r...
c66084faa8903455835973226ea6ca570239a1ec
19,728
def tau_data(spc_dct_i, spc_mod_dct_i, run_prefix, save_prefix, saddle=False): """ Read the filesystem to get information for TAU """ # Set up all the filesystem objects using models and levels pf_filesystems = filesys.models.pf_filesys( spc_dct_i, spc_mod_dct_i, run_p...
d27742140929d79dd4bb7a36094b5e5caf7173e2
19,729
def get_atten(log, atten_obj): """Get attenuator current attenuation value. Args: log: log object. atten_obj: attenuator object. Returns: Current attenuation value. """ return atten_obj.get_atten()
22d69d326846105491b1fa90f319eb9e0da69a20
19,730
def lfs_hsm_remove(log, fpath, host=None): """ HSM remove """ command = ("lfs hsm_remove %s" % (fpath)) extra_string = "" if host is None: retval = utils.run(command) else: retval = host.sh_run(log, command) extra_string = ("on host [%s]" % host.sh_hostname) if re...
ddca4a626786dfecfef231737761924527d136d5
19,731
def area_under_curve_score(table,scoring_function): """Takes a run and produces the total area under the curve until the end of the run. mean_area_under_curve_score is probably more informative.""" assert_run(table) scores = get_scores(table,scoring_function) return np.trapz(scores)
f84fd0a2adede09c17aa6254906bee36a2738983
19,732