content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import ssl def generate_ssl_context(server_certificate, server_key, ca_cert): """This function generates an ssl context for Tornado handler""" mySSLContex = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) mySSLContex.load_cert_chain(server_certificate, server_key) mySSLContex.load_verify_locations...
29e8cd2bc49948e6e5b509dab312b049d0cc9aaa
3,602,400
import os def ToolPath(tool, toolchain_info=None): """Return a full qualified path to the specified tool""" # ToolPath looks for the tools in the completely incorrect directory. # This looks in the checked in android_tools. if ARCH == "arm": toolchain_source = "arm-linux-androideabi-4.6" toolchain_pre...
87691d7cec122b82403a6437edae1bf09b673e13
3,602,401
def get_page(rb, cand, el_type): """ Функция принимает RoboBrowser с открытой страницей результатов голосования по какому-то УИКу rb, кол-во кандидатов в выборах cand, а также тип выборов el_type и возвращает список, состоящий из номера УИКа, кол-ва избирателей на УИКе, кол-во проголосовавших на дому и ...
a4fecd2dc60d8438e20870d0e96ce876bb4c1902
3,602,402
from typing import Optional def get_storage_class_v2(cluster_id: Optional[str] = None, name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetStorageClassV2Result: """ Use this data source to retrieve information about a Ranche...
f7b1e774e0950ab73daa534a8ede80629c014db0
3,602,403
import os def populate_and_save_assets_proto( artifacts_dir): """Populate and write a ScannAssets proto listing assets in `artifacts_dir`. Args: artifacts_dir: the directory for which this function finds ScaNN assets. The resulting proto is written in plaintext format to `artifacts_dir/scann_...
30c49203de110f120f8bc638ede8dd3771499032
3,602,404
import socket def parse_hub(hub): """ Parse a hub specification. :param hub: The hub specification. Can be either a bare "hostname" or a "hostname:port". If the hostname is an IPv6 address, it should be enclosed in brackets, i.e. "[::1]:4859". :retur...
ac3978a1646fdd00ddc8ccfcc54bf9e04eae6a1f
3,602,405
import json def get(url): """ Queries the NodePing API via GET and returns its results Accepts a URL to the NodePing API to query and retrieves data provided by NodePing, and then converts the contents to a dictionary :type url: string :param url: The URL that will be used for GET request ...
b9026456ff67b55d8e2bcdc41bc77541e2b2a6a8
3,602,406
def makeindexline(url, startpage, total, numonpage=10, pagesonscreen=5): """ Make a menu line for a given number of inputs, with a certain number per page. Will look something like : :: First Previous 22 23 24 25 26 27 28 29 30 31 32 Next Last Each number or word will be a link to ...
fdae2d9385f02e3c47fff516b2eb4fe1f931cec8
3,602,407
def log_loss( y_hat: np.ndarray, y: np.ndarray ) -> float: """ Log-loss cost function. :param y_hat: Predicted value (scaled [0, 1]) :param y: Label value (i.e., ground-truth) :return: loss value """ is_one = y * np.log(y_hat) is_zero = (1.0 - y) * np.log(1.0 - y_hat...
2c377700dddea65f670db7ce20755d8aa746d847
3,602,408
import pandas def optimize_price_index(initial_price_list: pandas.DataFrame) -> pandas.DataFrame: """ This pricing function has been made very simple as the main purpose is to serve the use case example. In real life this would typically be replaced by a more flexible price optimization engine with severa...
058dedbec73c1fa3dad510a1b6c4a0b56fa94112
3,602,409
from typing import List def generate_all_legal_trades_fast(state: State) -> List[ActionTradeGems]: """Returns the list of all possible actions of trade in a given current_state""" gems_board = state.board.gems_on_board gems_player = state.active_players_hand().gems_possessed #print(state.active_player...
94476f06afe4cb27e2abba364251bf165325e609
3,602,410
def upkey(name): """ Shortcut for creating an uppercase keyword """ return Keyword(name, caseless=True).setParseAction(upcaseTokens)
408465622b39971726f90a00bf83a1cf1118ef5c
3,602,411
def get_db_path(spider_dir, db_id): """ Return path to SQLite database file. Args: spider_dir: path to SPIDER benchmark db_id: database identifier Returns: path to SQLite database file """ return f'{spider_dir}/database/{db_id}/{db_id}.sqlite'
9069b673df1b3c929c249319339a84eaaf398c33
3,602,412
def is_available(): """[filterツールとenhancd.logが存在することを確認する] Returns: [bool]: [実行可能ならTrue] """ b1 = filepath.split_filterlist(x_env["ENHANCD_FILTER"]) is not None b2 = (x_env["ENHANCD_DIR"] / "enhancd.log").exists() return b1 and b2
6dd1fab9e7f4885309b315408d530e9a0b7e1d7c
3,602,413
def test_Mesh_NO2_trace_elements(): """Unittests for the trace elements.""" if rAnk == mAster_rank: print(">>> {test_Mesh_NO2_trace_elements} ...... ", flush=True) mesh = MeshGenerator('crazy')([2, 2, 2], EDM='debug') trace_elements = mesh.trace.elements benchmark = {0: ('0N', 'North'), 1: ...
6fae44a5080db5e02457583674027a9aa5e41fdd
3,602,414
import hashlib import base64 def get_pubkey(key): """Get the pubkey info corresponding to the given public key. The md5 hash of the key is used for the query for quicker lookups. """ session = get_session() md5_hash = hashlib.md5(base64.b64decode(key)).hexdigest() pubkeys = session.query(mode...
f4b2aca9fa93b4cf5a0ad277cb3f52e2b8cce783
3,602,415
import copy def init_ball_with_word2vec(vecFile, wordsenseFile, IncDim = 1, d=50, l0 = 10000, r0 = 30, rmin = 0.1): """ vecFile is a file of pre-trained word embedding. :param vecFile: :param trainFile: :param IndDim: 0, not to increase the dimension, >0, increase d+1th dimension with the value I...
ec447ab078c251e44223c591ec98ed9eecfd002c
3,602,416
def readable_ternary(first_opernad, condition, second_operand): """Same as `first_operand if condition else second_operand`""" return ternary(condition, first_opernad, second_operand)
3520bbcbda0881200d5ad5424e1a35286b7c1800
3,602,417
def execute(qregistry, iterations=1, lines=[], ancilla=None, useSystem=True, optimize=True): """Execute the gates in lines on a qsystem. Gets repeated the specified number of iterations. Returns the result of each iteration. """ sol = [_executeOnce(qregistry, lines, ancilla, useSystem, ...
d41e1594790aeb9b7899418bc66763b5c8445f67
3,602,418
import sys import argparse def parse_cmdline(argv): """ Returns the parsed argument list and return code. `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ if argv is None: argv = sys.argv[1:] # initialize the parser object: parser = argparse.ArgumentParser(descri...
ac3ac3fa19d90d8be1599bd52ef08955faa2b3ac
3,602,419
def frequency_response(data, fs, uprate): """ Parameters ---------- data: ndarray fs: float sampling frequency uprate: int Returns ------- (ndarray, ndarray, ndarray) mag_fre_db, phase_fre_rad, frequnecy """ response = fft(data, len(data) * uprate) mag_d...
d2ba8566924ce9153063498dee30687d1a7b4009
3,602,420
from typing import Optional from typing import Sequence from typing import Mapping from typing import Any def get_encode(batch_inputs: Optional[Sequence[Mapping[str, Any]]] = None, batch_results: Optional[Sequence[Mapping[str, Any]]] = None, encoded_value: Optional[str] = None, ...
411ccd95a23cb299a246792561e044fde95167fc
3,602,421
import re def sanitize_scope_name(name: Text) -> Text: """Sanitizes string which will be used as TensorFlow scope name.""" # Add "." to beginning if first character isn't acceptable name = re.sub("^([^A-Za-z0-9.])", ".\\1", name) # Replace invalid characters with "_" name = re.sub("([^A-Za-z0-9._]...
e83b84bf9135caf0a84e34fc380085100152ad7c
3,602,422
def get_entity_bio(seq, id2label): """Gets entities from sequence. note: BIO Args: seq (list): sequence of labels. Returns: list: list of (chunk_type, chunk_start, chunk_end). Example: seq = ['B-PER', 'I-PER', 'O', 'B-LOC'] get_entity_bio(seq) #output ...
bdaf2da0a7dd819239701af0aa49d69c09ece7f6
3,602,423
def sparse_euclidean_distance(sp_tensor, tensor2): """ Computes the euclidean distance between two tensors. Args: sp_tensor (`Union[Tensor,SparseTensor]`): a tensor or sparse tensor tensor2 (`Tensor`): a dense tensor Returns: distance (`Tensor`): euclidean dista...
719d14c8204b5d2ad595368f34ee8e44b6b8cbbc
3,602,424
def pop_indices(lst, indices): """ pop the lst given a list or tuple of indices. this function modifies lst directly inplace. >>> pop_indices([1,2,3,4,5,6], [0,4,5]) >>> [2, 3, 4] """ for n in sorted(indices, reverse=True): lst.pop(n) return lst
4cfeedfd211ba4578d877004acdec061c7727d78
3,602,425
from typing import Dict from typing import Any def delete_user(current_user: User, target_user: User) -> Dict[str, Any]: """ Delete the user records and remove the user from all user groups. All user id fields with this user id as values are set to null. :param current_user: :param target_user: ...
9d1d34c0c2927fd802ecf23551c55a438acb6afb
3,602,426
def plot(xy: PointUnionList, color='black', label=None, linewidth=None, linestyle=None, plotter=None) -> Artist: """Quick entry to pyplot.plot() for List[Point]""" plotter = plotter or plt artist, = plotter.plot(*zip(*xy), color, label=label, linestyle=linestyle,...
3a1341ab28551cd5f6a1d52bc2f49e194a41be47
3,602,427
import json def login(request): """Log user in. Associate barangay data with authentication data and store in session. Args: request: The URL Request. Returns: Render form with errors. """ data = json.load(request) auth_data: dict = data.get("payload") user_col = firesto...
d2472b2ea9ce271c30f09ffea6bccd4a60131df5
3,602,428
import json def record_locators(request): """ View that generates at least one record locator, generating 'n' if specified through a query parameter. """ num_locators = int(request.GET.get('n', 1)) record_locators = generate_locators(num_locators) data = {'record_locators': record_locators} ...
9eb3836b31435aec8579925d5348cc168c6f5de7
3,602,429
def merge(obj, *sources, **kargs): """Recursively merges own enumerable properties of the source object(s) that don't resolve to undefined into the destination object. Subsequent sources will overwrite property assignments of previous sources. If a callback is provided it will be executed to produce the...
517bfa55419e672f09cc55a5bf0f764c80d9fd61
3,602,430
def wrapper_early_cav_identif(grid, grid_min, grid_shape, selection_protein, selection_coords, size_probe = 1.0, maxdistance = 6.0, radius_cube = 4, min_burial = 8, radius_cube_enc = 3, min_burial_enc = 8, gridspace = 1.0, min_degree = 3, radius = 2, trim_score = 500, min_points = 40, min_burial_q = 10, quantile = 0...
c6a788b548f67e1f943e769310277191ec3e5212
3,602,431
def calculate_distance(aux_structures, start, end): """ Returns the distance between two nodes. start and end are node IDs. """ start_id_to_coordinate = map_node_id_to_coordinates(aux_structures, start) end_id_to_coordinate = map_node_id_to_coordinates(aux_structures, end) dista...
3565f95538eff326661af3228369e30051994690
3,602,432
import sys import os def compress_directory( path: str, compression_format="gzip", destination=None, delete_after_compress=False ) -> str: """compression format accepted rar, tar, zip, bz2, gz, xz""" output = "" if destination: # used for relative paths namespace = sys._getframe(1).f_...
1cca46afa498280fd31461a076831e9998f0fb35
3,602,433
def get_sampling_rate(filename=None): """Get the sampling rate in Hz.""" return _fs
a5d5a9a93224543a98ab92128e113201f2ea72c9
3,602,434
def ls(directory=None): """Return a python list of ROOT object names from the given directory.""" if directory == None: keys = ROOT.gDirectory.GetListOfKeys() else: keys = ROOT.gDirectory.GetDirectory(directory).GetListOfKeys() key = keys[0] names = [] while key: obj = ke...
60239abd729971b944b95e8483f513226e112071
3,602,435
def is_color_management_enabled(): """ Returns whether or not color management is enabled :return: bool """ return maya.cmds.colorManagementPrefs(cmEnabled=True, query=True)
3d89dea2aad26e5c8337db857bc1273d95974e4d
3,602,436
import os import glob import sys def check_dataset_dir(dataset_dir): """ Check the directory that holds the dataset """ if not os.path.exists(dataset_dir): create_dir(dataset_dir) dataset_list = sorted(glob.glob(dataset_dir + "/*")) print("Dataset List: ", dataset_list) if len(d...
a3bd2ca053799116d7a3ace5e949cf68c929b68d
3,602,437
def UNET(input_shape, num_classes, branch_names, BACKBONE, weights, freeze_backbone=False, activation='sigmoid', decoder_type='upsample', decoder_filters=[256, 128, 64, 32, 16], input_tensor=None, name='UNET'): """Build a generic UNET model with a given ``BACKBONE`` class. # Argument...
2ae9e643392fb65bef869d5ea98b3178a1ea1c05
3,602,438
def geo2rect(lon: float, lat: float, h: float, r: float, ecc: float = EARTH_SECOND_ECCENTRICITY_2) -> np.ndarray: """ Geodetic to Rectangular Coordinates conversion in the e-frame. Parameters ---------- lon : float Longitude lat : float Latitude h : float Height abov...
a0b00fdb8e9e6d478ce245e09a1755a0edd1aaf1
3,602,439
from typing import Optional from typing import Set from pathlib import Path from typing import Iterable from typing import List import logging def filter_tidy_lints(only_files: Optional[Set[Path]], git_repo_base: Optional[Path], diags: Iterable[TidyDiagnostic]) -> List[Tidy...
9d3a047b8ea8dd7e4a90bd982dbfdee9abc681d8
3,602,440
def timeseries_table(request, model_uuid): """ View the "Timeseries" page Parameters: model_uuid (uuid): required Returns: HttpResponse Example: http://0.0.0.0:8000/<model_uuid>/timeseries_table/ """ model = Model.by_uuid(model_uuid) can_edit = model.handle_view_access(reques...
410b5bdac6a2bb926d98ddd540e065b9d7d01831
3,602,441
def _initialize_variogram_model(X, y, variogram_model, variogram_model_parameters, variogram_function, nlags, weight, coordinates_type,network=None): """Initializes the variogram model for kriging. If user does not specify parameters, calls automat...
abd50d84eeef20df802e5033db3a79a4cb40e7d7
3,602,442
def is_specific_hemorrhage(df): """If a specific hemorrhage present or suspected, then hemorrhage NOS changed to absent.""" hemorrhages = [ "epidural_hemorrhage", "subarachnoid_hemorrhage", "subdural_hemorrhage", ] present = ["present", "suspected"] specific_hemorrhage ...
404a8162e9225055bf1b3ea493d6529ea5e90767
3,602,443
def polynomial(degree, coeffs): """ >>> fourth = polynomial(4, [3,6,2,1, 100]) >>> fourth(3) # 3*(3**4) + 6*(3**3) + 2*(3**2) + 1*(3**1) + 100 526 >>> third = polynomial(3, [2, 0, 0, 0]) >>> third(4) # 2*(4**3) + 0*(4**2) + 0*(4**1) + 0 128 """ def h(x): result = 0 ...
b7f84aabe99e853e57dd7204aecd7bef03655668
3,602,444
def contentaddress(key, mem, beta): """Content address Parameters ---------- key : `[batch_size, word_size]` mem : `[batch_size, mem_size, word_size]` beta : `[batch_size, 1]` Returns ------- `[batch_size, mem_size]` """ key_ = expand_dims(key, axis=2) norm_mem = norm(m...
5edac65914c9814322cd8a0a454506c0e383c9fc
3,602,445
def hsv2rgb(img): """ Use matplotlib to convert hsv to rgb (TA allowed) """ return (hsv_to_rgb(img.astype(np.float32) / 255.) * 255).astype(np.uint8)
262ec15ab3e5ba21b3514973d93b5889becf534a
3,602,446
def cybereason_driver(): """Generate Cybereason Driver for testing.""" driver = CybereasonDriver() _cr_pre_checks(driver) return driver
1d984d2db26fd8aeb6c48cafab7451435c89d11d
3,602,447
def all_forms_list(*args, **kwargs): """Returns a list/tuple of all possible word form descriptors for the given part-of-speech and other restrictions. This caches the result.""" key = (args, tuple(sorted(kwargs.items()))) if key in all_forms_cache: return all_forms_cache[key] forms = tuple...
f289b301d7f57b21ac9933003317a2d09d1f6986
3,602,448
def patch(url, body=None, **kwargs): """patch performs a HTTP PATCH request.""" return request('PATCH', url=url, body=body, **kwargs)
4049f91bbe1ee5fb15d3a2c6534a44893e60b682
3,602,449
def opportunity_outlook_gain(X, threshold=1): """Calculate opportunity outlook gain Value for existing capabilities is NaN. Args: X (pandas.DataFrame): [locations x activities] threshold (float, optional): Binarisation threshold for location quotient. Returns: pand...
1b5b625aa9f90fc4c75f4450b00024949bba0f1d
3,602,450
def new_format_converter(df, logger): """Returns a dataframe.""" df = df.rename(columns={"Plant Name": "Hour"}) df["Hour"] = df["Hour"].astype(str) df = df.reset_index(drop=True) df = df.set_index("Hour") total_index = df.columns.get_loc("Total (MW)") df = df.iloc[:, total_index:] try:...
d18178046e12a074fdfa05c8ad4dbdbe9993d003
3,602,451
def conv2d_grad_backend(x, dy, padding, stride): """Performs the gradient of a discrete 2d convolution of x with w.""" dilated_dy = np.zeros([dy.shape[0], dy.shape[1], stride[0], dy.shape[2], stride[1], dy.shape[3]]) dilated_dy[:, :, 0, :, 0, :] = dy dy = dilated_dy.reshape([dy.shape[0], dy.shape[1] * s...
59c95f92ba6874923d188066856a968a08962e0d
3,602,452
def TETMajScale(frequency, octaveDivider): """Cross references a traditional major scale with a new TET chromatic scale. Returns an array of 8 frequencies.""" standard = StandardMajScale(frequency) newTET = TETChromaticScale(frequency, octaveDivider) newScale = [] for i in range(len(standard)): ...
e54705e30c0eaccf5bc52f98380786c15698f5a8
3,602,453
import torch def calc_loss(x_pred, x_output, num_output, pri=True): """Focal loss :param x_pred: prediction of primary network (either main or auxiliary) :param x_output: label :param pri: is primary task output? :param num_output: number of classes :return: loss per sample """ if not...
7433df267911d136d0b03ce3d922e7650d1c93d6
3,602,454
def _BackslashEscape(s): """Double up backslashes. Useful for strings about to be globbed and strings about to be IFS escaped. """ return s.replace('\\', '\\\\') # Similar to GlobEscape and splitter.Escape(). escaped = '' for c in s: if c == '\\': escaped += '\\' escaped += c return escap...
4c107203117d699c65fd00158913914ae6530b97
3,602,455
import collections def _collect_traces(raw_traces, trace_factory): """Postprocesses pytype's opcode traces.""" out = collections.defaultdict(list) for op, symbol, data in raw_traces: out[op.line].append(trace_factory(op.name, symbol, data)) return out
6f656073c17c9c5c1d6a33c37dd6a23a5525aa64
3,602,456
def intrange(arg): """ convert a command-line argument to a list of integers """ acceptable_chars = [str(x) for x in range(10)] acceptable_chars.append("-") partial = [] first = None msg = "Could not convert {0} to index range.".format(arg) err = TypeError(msg) for char in arg: ...
8d3bbe9b32207ae2c18080601761b84c9e87ec9f
3,602,457
def inside_or_on_line_2d(p1, p2, reference_point, pt, tol=None): """Tests whether a point is on the same side of a line as a reference point, or on the line itself. Assumes reference_point is not on the line (within tol). Points are represented as (x, y, z) triples. Args: p1: The first point d...
58aa202c5333bedbbb7139128d93f6e057d45ee8
3,602,458
import string def create_row_object_stack(): """Extract every stacking object in a client call""" l_row = environment.get_cursor_row() non_splittable_characters = string.ascii_letters + string.digits + "_" l_col = complete_start() - 1 l_col = environment.previous_non_white_character_in_row(l_row, ...
9c370710cd4a0610c33d41410268d2bf3117ff16
3,602,459
from summit_core import find_closest_date, search_for_attr_value import logging def match_lines_to_runs(lines, runs): """ This takes a list of PaLine and GcRun objects and matched them by date, within a tolerance. When matching objects, it WILL modify their parameters and status if warranted. :param ...
49ad2c4648c68042fcc14a027ace95902ea24efa
3,602,460
def update_dict(new_dict): """ update configs dict """ if new_dict["method"] == "dichotomy": default_dict = DICHOTOMY_DICT.copy() elif new_dict["method"] == "sphere_tracing": default_dict = SPHERE_TRACING_DICT.copy() elif new_dict["method"] == "gradient_descent": default_dict...
79d0f6f676c6ca11b1d40445145d399a78beb893
3,602,461
def protein_binding_hairpin(N, target='none', ligand='theo', pam=None): """ Randomize the region 5' of the hairpin in the hopes of creating a sequence that is partially complementary to the aptamer. Presently, this strategy is intended for protein binding aptamers like MS2 that aren't expected to ...
6391ae7b2926a468c3e4d5789c04079a64af3f26
3,602,462
def rfcavity(fam_name, length, voltage, frequency, phase_lag=0.0): """Create a RF cavity element. Keyword arguments: fam_name -- family name length -- [m] voltage -- [V] frequency -- [Hz] phase_lag -- [rad] """ ele = _trackcpp.rfcavity_wrapper( fam_name, length, frequency, v...
504cd5d017d75f706c391be05b06cc83a746a56e
3,602,463
def add_api_token_to_response(response, user): """Generate API token and add it to the response (both as a `token` key in the response if it was json and by setting a cookie named API_TOKEN_COOKIE. """ token = generate_api_token(user) if hasattr(response, 'data'): response.data['token'] = to...
6f2ced2209246e6c0b3d33b044e28f8e3a98b14b
3,602,464
def coords_from_outcar( filename='OUTCAR' ): """Finds and returns Cartesian coordinates from the OUTCAR file. Args: filename (:obj:'str', optional): the name of the ``OUTCAR`` file to be read. Default is `OUTCAR`. Returns: (np.array): The Cartesian coordinates as found in the ``OUTCA...
2c98bc2bfa895aeefda30eedaf586b92ec01edc5
3,602,465
def model_fn(features, labels, mode): """The model_fn argument for creating an Estimator.""" model = Model() image = features['image'] training = mode == tf.estimator.ModeKeys.TRAIN angle_logits, predicted_throttle = model(image, training=training) predicted_angle = tf.argmax(input=angle_logits,...
6453da36ec0af25d3b347ae1ecc27d6e7b9550b1
3,602,466
def multiPlot(plotArray, title='', xlabel='', ylabel='', xscale='linear', yscale='linear'): """ plotArray is of the form: [[X1, Y1], [X2, Y2]] Where Xi, Yi are arrays of of the values to plot. """ plt.clf() figure = plt figure.title(title) figure.xlabel(xlabel) figure.ylabel(...
bbfd7147f094e6c92a3644128e0788c22ccea9bf
3,602,467
def dUdT_n_dimensional(sto): """ Dimensional entropic change of the negative electrode open-circuit potential [V.K-1] """ return pybamm.FunctionParameter( "Negative electrode OCP entropic change [V.K-1]", sto, c_n_max )
d9a13427e05b221548798231b63e0eb0f74ddb84
3,602,468
def set_problem_availability(pid, disabled): """ Updates a problem's availability. Args: pid: the problem's pid disabled: whether or not the problem should be disabled. Returns: The updated problem object. """ problem = api.problem.get_problem(pid=pid) if len(proble...
139256d3326bda05d93fda082533e79ead3b8c26
3,602,469
import pickle def load_pickle(fname): """ Load an ephemeris pickle file Parameters ---------- fname (str) : path and name of the pickle file Returns ---------- Dictionary of Segments """ f = open(fname, 'rb') data = pickle.load(f) f.close() dc = {}...
cb6d82118b4b92340017adb51bf7277772ae40b8
3,602,470
import copy import numpy def run_backwards_test( three_predictor_matrices, target_array, model_object, model_metadata_dict, cost_function, num_bootstrap_reps=DEFAULT_NUM_BOOTSTRAP_REPS, num_steps=None): """Runs backwards version of permutation test (both single- and multi-pass). E = n...
bef2770a104b38229c4c24a6bad23630da854370
3,602,471
def get_t1(close, timestamps, num_days): """Return horizontal timestamps Note ---- Not include the case to hit the vertical line at the end of close.index Parameters ---------- close: pd.Series timestamps: pd.DatetimeIndex num_days: int The number of forward dates for verti...
c619249649401695d48fb00718b898b181513a2b
3,602,472
def compute_difference_metrics(initial_output, final_output, tmp_results): """ Given NN output before and after removal, all absolute difference metrics are stored. :param initial_output: model.forward(x) :param final_output: model.forward(x_salient_pixels_removed) :param tmp_results: object to sto...
90e80ddd9797288ead39331462ab09c7f9689095
3,602,473
def search_peaks(x_data, y_data, height=0.1, distance=10): """ 从给定的光谱数据中寻找峰值 Look for peaks in the given spectral data :param x_data: 光谱数据x数据,Spectral X-axis data :param y_data:谱数据y数据,Spectral Y-axis data :param height:峰值高度阈值.Peak height threshold :param distance:峰之间的最小水平距离,如果距离小于指定值,会从高...
c3fc9b41beafd8c699bfef633441a2c05a80d8e6
3,602,474
import os import sys def check_lock(lock): """ Check if lock directory exists before calling function """ def __inner(func): def __wrapper(*args, **kwargs): if os.path.isdir(lock): logger.warning('Lock directory detected, function is already running') ...
65d13294fffc766ecfcdf442471b3b819f344dd9
3,602,475
from jinfo.sequence import BaseSeq import re from typing import List def seq_list_from_fasta(file_path: str, seq_obj: ANY_SEQ = BaseSeq) -> List[ANY_SEQ]: """ Parse a multifasta file Returns list of BaseSeq objects """ with open(file_path, "r") as text_file: fasta_str = text_file.read()...
3ae91e7feb022eea9ee58d9a5b46625845c4f52b
3,602,476
import subprocess def s3_addition(bucket_name, region): """ add a new s3 """ output = subprocess.getstatusoutput("aws s3api create-bucket --bucket {0} --region {1} --create-bucket-configuration LocationConstraint={1}".format(bucket_name,region)) return output
ae08985c1b34446fb54d1ef547420c4ca15d6456
3,602,477
def make_projector_info(info): """Make an SSP operator using the measurement info Calls make_projector on good channels. Parameters ---------- info : dict Measurement info Returns ------- proj : array of shape [n_channels, n_channels] The projection operator to apply t...
246cb1677ff33a85c7a287556c8f79ed1e0ae6c1
3,602,478
import re def read_accounts_file(account_file): """ Process each line in the specified account file looking for account definitions. An account definition is a line containing the word 'account' followed by a valid account name, e.g: account Expenses account Expenses:Utili...
f917958201cd66f6b04bd9307611bb282b25f3f6
3,602,479
def _FieldOrExtensionValues(message, field_or_extension): """Retrieves the list of values for the specified field or extension. The target field or extension can be optional, required or repeated, but it must have value(s) set. The assumption is that the target field or extension is set (e.g. _HasFieldOrExtens...
1dd483a71825b04bb76df84ec334674833151c40
3,602,480
def create_encoder(backbone_options: config_pb2.ModelOptions.BackboneOptions, bn_layer: tf.keras.layers.Layer, conv_kernel_weight_decay: float = 0.0) -> tf.keras.Model: """Creates an encoder. Args: backbone_options: A proto config of type config_pb2.ModelOptions.Back...
bf536761ddf2c37240927718e12c38f2c5f1a65c
3,602,481
import os def dst_path(src, output_path, overwrite): """ Resolves the destination path for the wrapping operation :param src: single input file path :param output_path: output sequence path :param overwrite: overwrite output option :return: single output file path """ dst = output_path...
e301e433cfb99b6b4c2896a5850c51afba333c0d
3,602,482
import subprocess def flake8(skip_init, path): """ Run flake8 to analyze your code base. :param skip_init: Skip checking __init__.py files :param path: Test coverage path :return: Subprocess call result """ flake8_flag_exclude = "" if skip_init: flake8_flag_exclude = " --excl...
d2cb84ca802b72b45fa653fd3d72f3d8ad40eaef
3,602,483
def forceresolution( numgridptscuberoot, lengthcuberoot ) : """ returns the force resolution of the PM part in units of the input boxsize args: numgridptscuberoot: lengthcuberoot : return : force resolution (distance) in units usef for the box size """ return lengthcuberoot/numgridptscuberoot
d14760ac863bd1409b9df40fe0ff19ff44b508ca
3,602,484
from typing import Dict def fixture_color_name(theme: Dict[str, str]) -> str: """Return a random color name.""" return choice(list(theme))
a197406acf8c57e0c7c8bc1d321c2a70d133119a
3,602,485
def find_transformation_full(lines): """ Finds alignment transform. Very slow and distortionable :param lines: :return: """ if len(lines) == 0: return bounds = lines[0].chars[0].refined_box for ln in lines: for ch in ln.chars: bounds = [min(bounds[0], ch.refin...
9abe40d45478a06e566f6d2d048280229d9c233b
3,602,486
import requests def fetch(url: str): """ Simply fetch any URL given, and convert from bytes to string """ r = requests.get( url, headers={ "User-Agent": read_json()["user_agent"], "Content-Type": "text/html; charset=UTF-8", } ) text = r.content.decode("utf-8") ...
63c85b952a9e9bb703cc9d16cd4d5259713458f6
3,602,487
def compute_cost(X, y, w): """ Calculates mean square error cost. :param X: design matrix :type X: np.ndarray(shape=(N, d)) :param y: regression targets :type y: np.ndarray(shape=(N, 1)) :param w: weights :type w: np.array(shape=(d,)) :return: cost :rtype: float """ # ...
3614b58712af327ee919a1a0826057943ebfde05
3,602,488
def set_up_folder_name_1M ( model_file , date_run ): """ Produce log_file, plot_folder based on model_file (file name ending with _sd.pt) If model_file is epoch_1_sd.pt, date_run is 0913: plot_folder 'plot_2d_epoch_1', log file 'log_0913_2d_epoch_1' """ # if model_file == '': model_pure = f'ep{ep_in...
d7dd24789476279ea8d5fe0b32627aa049731ef7
3,602,489
def kfl_random_monotonic_initializer(shape, scale, monotonicities, init_min=0.5, init_max=1.5, dtype=tf.float32, ...
7230365e40fe763e891bdb79c7d3fe6f582d6371
3,602,490
def percentage_of_peaks_found(known_peaks, association_matrix, knownhdf5_filename): """ This function takes in a list of classified peaks, and returns a percentage of how many of the material's peaks are found in the unknown spectrum. This can be used as a metric of confidence. Parameters:...
cabb18b1dd2375ff042ee43f9c9910fb87a4c432
3,602,491
import time def wait_for_measurement(): """ helper function to log waiting around for data to be ready - a combination of waiting and polling - this function is called after p1125.acquisition_start(...) :return: success <True/False> """ # pre-waiting here, the acquisition was just kicked off,...
0c09f6d7921cced9e08a088a161daeaa4d640a29
3,602,492
def iterencode(data, ensure_ascii=False, **kwargs): """ Returns a generator that yields each string representation as available. """ if 'indent' not in kwargs: kwargs['separators'] = (',', ':') return JSONEncoder(ensure_ascii=ensure_ascii, **kwargs).iterencode(data)
0f88abef47b79562f64816e768793fc3a69ba4a3
3,602,493
from typing import List import glob def get_all_file_from_directory(directory: str, file_dsc: str) -> List[str]: """ Get paths of all files matching file_dsc in directory """ template = f"{directory}{file_dsc}" file_paths = glob.glob(template) return file_paths
7a3115793a5a59bc8f6ee655315ea87857338c47
3,602,494
import configparser def read_options(config_path): """Чтение конфигурационного файла и установка глобальных переменных из cfg.py :param config_path: путь к конфигурационному файлу :return: True or False """ config = configparser.ConfigParser() if config.read(config_path, encoding='utf-8'): ...
328d63bc72c52684b6e824dccae7a2fa17d49569
3,602,495
def update_slu(client_name: str, model_name: str): """ Update SLU config. """ json_config_data_provider = JSONAPIConfig(config_dict=request.json) config = json_config_data_provider.generate() CLIENT_CONFIGS[model_name] = config MODEL_PREDICT_APIS[model_name] = convert_config_to_predict_wrap...
fc09fd0bf6f08b3f035098f5b5029377704ab526
3,602,496
from . import __version__ from datetime import datetime def appendExportRecord(item, user, metadataProperty, status=None): """ Append information about the current export to an item's exported record. Return the most recent export record. :param item: the Girder item to add export history to :par...
b21cbfc80ff29352b4aafb5458a402fbe8ef133f
3,602,497
def naked(val): """ Given a string strip off all white space & quotes """ return val.strip(' "\'\t')
1875b38f05fa0c8b540ece0265354293f275b3ea
3,602,498
def get_hex_slug(length=16, case_convertor=None): """ gets a slug from a uuid as hex string. :param int length: length of generated slug. defaults to `16` if not provided. the maximum length is `32`. :param function case_convertor: a callable to be used as...
c39a46d9035508aaf5f444acae776d4962f0740d
3,602,499