content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def rms_model(nu, nu_rms, rms): """ """ return (1/3)*rms[crrls.best_match_indx(nu, nu_rms)]
b48d38625eb985ce69f37cdd4cf8903be5749815
3,601,000
import os def to_abs_path(relative_path): """Returns a canonical path for the specified path relative to the script directory. """ script_dir = os.path.dirname(os.path.realpath(__file__)) return os.path.realpath(os.path.join(script_dir, relative_path))
c333c999fce96ba9a05975d4df690c7c86ac0426
3,601,001
def remove(predicate, coll): """ Return those items of collection for which predicate(item) is true. >>> from functoolz import remove >>> def even(x): ... return x % 2 == 0 >>> list(remove(even, [1, 2, 3, 4])) [1, 3] """ return filter(lambda x: not predicate(x), coll)
388960b59dd996a9dcac2470ac3c63a8d904853c
3,601,002
def channel_shuffle2(x, groups): """ Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,' https://arxiv.org/abs/1707.01083. The alternative version. Parameters: ---------- x : Tensor Input tensor. ...
7fd5d4e9438ec0e294e839231ebe103cdd74eac1
3,601,003
def blackmanharris7(N, sym): """ 7 Term Cosine, 180.468 dB, NBW 2.63025 bins, 11.33355 dB gain""" a = [2.712203605850388e-001, -4.334446123274422e-001, 2.180041228929303e-001, -6.578534329560609e-002, 1.076186730534183e-002, -7.700127105808265e-004, 1.36...
4f81e08f72d1cf2f361812a53fb43810111dcc21
3,601,004
import os import importlib def read_version(): """This function reads the version from diffusion_maps/version.py without importing parts of the package (which would require some of the dependencies already installed).""" # code parts were taken from here https://stackoverflow.com/a/67692 path2set...
4e3db219499600de0459ec88d73083c19aea9884
3,601,005
import types def register(fnname, nargs): """ Register a function with excel """ if type(fnname) == types.FunctionType: fnname=fnname.func_name r=RegisterFnXLL(str(getXLLDLL()), "ExPyDispatch", "P"+"P"*nargs+"#", fnname) fnreg...
e2409eb95d414d564cdc066ab15516e1a210e43d
3,601,006
def compute_accuracy(y_pred, y_test): """Compute accuracy of prediction. Parameters ---------- y_pred : array, shape (N_test) Predicted labels. y_test : array, shape (N_test) True labels. """ true_counter = 0 for i in range(len(y_pred)): if y_pred[i] == y_test[i]...
a06b4d91f1878288ab4746d1f729040c95b91a91
3,601,007
def verify_device_tracking_policy_configuration(device, policy_name, security_level='guard', trusted_port=None, device_role=None, data_glean=None, prefix_glean=None, neighbor_d...
f6aa0753acda069f6c51e8410a6fb0b265dfaaf1
3,601,008
import itertools def findEpitopes(responses, sharedRule, **kwargs): """Given a list of responses find the minimum set of epitopes that "explain" all responses.""" """Start with all possible sets of responses (i.e. combinations)""" sharedSets = [] for N in range(1, len(responses) + 1): for...
4dab98a31b3581ef1310d7a09a4525ad23576cfa
3,601,009
def closest_approach(points, direction): """ Compute the point of closest approach between lines. Parameters ---------- points : ndarray An n x 3 array of points on each line direction : ndarray An n x 3 array of vectors that defines the direction of each line ...
99bbf31659dc7140cc816767a12c46f7d8fa3634
3,601,010
def read_random_int(nbits: int) -> int: """Reads a random integer of approximately nbits bits.""" randomdata = read_random_bits(nbits) value = transform.bytes2int(randomdata) value |= 1 << (nbits - 1) return value
691042f40206b5a4f12b0023797eec22483690ee
3,601,011
def init_centroids(k, edges): """Returns k centroids by randomly sampling data points out of a given set of edges, as a matrix of shape (k, n). :param k: an integer value denoting the number of means/clusters. :param edges: a matrix of edges to sample the initial means from :returns: a matrix of k ...
7193d44b312ffd1910cf22c01ccbe501ee524e87
3,601,012
def get_request_url(url, *args, **kwargs): """Returns url parameter that request will use""" return url
fde43b531d53e0f3cf80655b0da9895b7a001e13
3,601,013
import glob import re import os from datetime import datetime def folder_mtime(folder): """Determine the time at which the experiment was performed. In order to do this reliably, ``folder_mtime`` tries the following approaches, and returns the result of the first successful approach: #. Parse the nam...
dc974c6cb472b5b0ef35cca74c99d044509bdb7f
3,601,014
import sys def _load(target, **vars): """ Fetch something from a module. The exact behaviour depends on the the target string: If the target is a valid python import path (e.g. `package.module`), the rightmost part is returned as a module object. If the target contains a colon (e....
44446d742765ff96f4bbc38546157c5abc3dffa8
3,601,015
from typing import Set def get_genes_in_graph(graph: pybel.BELGraph) -> Set[str]: """Get BEL graph gene set for a pathway. :param graph: BEL Graph :return: BEL graph gene set """ return { node for node in graph if isinstance(node, CentralDogma) and node.namespace.lower() =...
83446ff7f38f935ed5d26423b57ea1eecdb59ba3
3,601,016
import typing import scipy def get_pcs(mat: np.ndarray, num_pcs: int) -> typing.Tuple[np.ndarray, np.ndarray]: """Gets the top num_pcs principal component vectors and associated values from the specified matrix. Args: mat (np.ndarray[samples, features]): The matrix to reduce num_pcs (int)...
b5de6199f88d513d438efb2e770d3a98cca3412d
3,601,017
def square_table_while(n): """ Returns: list of squares less than (or equal to) N This function creates a list of integer squares 1*1, 2*2, ... It only adds those squares that are less than or equal to N. Parameter n: the bound on the squares Precondition: n >= 0 is a number """ ...
8eb94d9690f4138fb6759cf73d5a602659571b34
3,601,018
import sys import argparse def template_arg_parser(*, desc, default_prefix, argv=None, macros=None, supported_async_libs=None): """ Construct a template arg parser for starting up an IOC Parameters ---------- description : string Human-friendly description of what ...
5cfdd820bcf8f9d0b4eb5e589ca493d154d5ddcd
3,601,019
import json async def home_card(request : VueRequest): """ 获取首页卡片上数据的接口 :param: :return str response: 需要返回的数据 """ try: response = {'code': '', 'message': '', 'data': ''} request = rsa_crypto.decrypt(request.data) request = json.loads(request) token = req...
2ec13c58f038cb3de3109739edfd655c72b76474
3,601,020
import os def val_dir(string: str) -> str: """Check that provided string is a directory.""" if os.path.isdir(string): return string else: raise NotADirectoryError
092689cc81c40a29c71aa8475f231423f2bc2e3b
3,601,021
from functools import reduce def subtract(ctx, *operands): """Negate one number or subtract many.""" if len(operands) == 1: return -operands[0] else: return reduce(float, lambda x, y: x - y, *operands)
c131a6975297deccc31e06634935df328e4306f6
3,601,022
def get_gsom_node_array_with_new_feature_vectors(gsom_nodemap, gsom_list, labels, input_database, centroids, global_centroid): """ Advanced Version of the get_gsom_node_array(gsom_list, labels) :param gsom_list: gsom neuron weights returned by the kmeans clustering :param labels: This is regar...
033f3454d152bb1ad5fd965aba3ff5b68932b3b9
3,601,023
def gtk_get_light_theme(): """Return the GTK Light theme specified in the yin-yang config""" return config["gtkLightTheme"]
e3c0e2155f8ad147535e43fb2db42e9aa2436bfa
3,601,024
def populate_words(words, oxford_api, words_api=None, allow_messages=True): """ Iterates the words dictionary, populating the data of each object using the OxfordAPI and with the optional WordsAPI to be used in the case the word is not found in the Oxford dictionary. :param words: The dictionary contain...
6f435b2e8d9947a9e7c6ba558aa43e13fe0dcfd6
3,601,025
def fold(paper, axis, pos): """ Make a fold. """ if axis == 'y': top, bottom = np.array_split(paper, [pos,], axis=0) bottom = bottom[1:] if top.size > bottom.size: bottom = np.pad(bottom, ((0, len(top)-len(bottom)), (0, 0)), 'constant') else: top =...
8620d612a0bde3a58f80432722bd1fa9824c5e62
3,601,026
def LoadSignedJson(txt, key): """Verify that a given message was signed with the given key, and load it. @param txt: json-encoded hmac-signed message @param key: the shared hmac key or a callable taking one argument (the key selector), which returns the hmac key belonging to the key selector. Typical usa...
73a4f21f0c587b4f357c48ddc1f6068c14ed0344
3,601,027
import json import logging def create_iam_role_for_lambda(iam_role_name): """Create an IAM role to enable a Lambda function to call AWS services :param iam_role_name: Name of IAM role :return: ARN of IAM role. If error, returns None. """ # Lambda trusted relationship policy document lambda_a...
f876543b2c9ccb3cb53aae8fa03cfb8d0ee97bef
3,601,028
def multilabel_dilation(img, radius=1, kernel=sitk.BinaryDilateImageFilter.Ball): """ This function... :param img: :param radius: :param kernel: :return: """ distImg = sitk.SignedMaurerDistanceMap( img != 0, insideIsPositive=False, squaredDistance=False, useImageSpacing=False ...
6dc3b795d87eb40e5d7589a049c1d9ab5f7e503a
3,601,029
def _neighbors_sparse_fixed_radius(csrmat, radius): """ Returns the list of neighbor column indices within the fixed radius Parameter --------- csrmat : scipy.sparse.csr_matrix radius : int Return ------ list of lists of ints Example ------- >>> M = np.array([[-1,0,1,4],[1,-1,0,2],[0,10,-1,3],[0,0,2...
1948ced30f98a20692e7ed9b97e212ff332001e0
3,601,030
import re import os def labels_from_mni_coords(seeds, extent=30., subject='fsaverage', surface='white', mask=None, subjects_dir=None, parc=None): """Create a parcellation from seed coordinates in MNI space Parameters ---------- seeds : dict ...
15f1f647132de5376847b1d2e34e260bd14ce921
3,601,031
def set_subMenus(id, menus): """ :param id: 父id :param subMenu:子菜单列表 :return: 没有子菜单返回None 有子菜单返回子菜单列表 """ try: _subMenus = [] for menu in menus: if menu.pid == id: _subMenus.append(model_to_dict(menu)) for sub in _subMenus: menu2 =...
8ff3e506f837ed3bc9f110bbf99d40505ebf4f6b
3,601,032
import argparse def read_cmd(): """Reading command line options.""" desc = "Program for relinking Khan Content Bakalari NEXT e-learning module." parser = argparse.ArgumentParser(description=desc) parser.add_argument('-s','--subject', dest='subject', default='root', help='Relink content for a given domain/...
7015f4d4917fcabf9ee5e9437ac813138db1b874
3,601,033
def media_artist(self): """Artist of current playing media, music track only.""" return self._media_artist
12e0538850bfb04ae52fe6840b7445423e393687
3,601,034
def baseline_predict_scenev2(LR, QM, interpolation=cv2.INTER_CUBIC): """ baseline version 2 : average image with the maximum number of clearance pixel of one imageset """ # load clearance map n = len(QM) clearance = np.zeros( (n,) ) #for cl in QM: for i in prange(n)...
ca8701adf17e1e76177441d09cb5ce63923fbb57
3,601,035
import ast def NullIncDec(p, w, bp): """ ++x or ++x[1] """ right = p.ParseUntil(bp) child = tdop.ToLValue(right) if child is None: p_die("This value can't be assigned to", word=w) return ast.UnaryAssign(word.ArithId(w), child)
823944c0d75ed2aadc3a208e4a7ec15fa9b97f8f
3,601,036
def flattenEmailAddresses(addresses): """ Turn a list of email addresses into a comma-delimited string of properly formatted, non MIME-encoded email addresses, suitable for use as an RFC 822 header @param addresses: sequence of L{EmailAddress} instances """ return ', '.join(addr.pseudoForma...
91c235451006747e419cfd1e01eb7151eec952ed
3,601,037
def predict(): """ Prediction endpoint that loads data given the file path and calls the prediction function in diagnostics.py Returns: json: model predictions """ filepath = request.get_json()['filepath'] df = pd.read_csv(filepath) df = df.drop(['corporation', 'exited'], axis=...
35f7c311ec6ba3427336ab358c9a170bb3803057
3,601,038
def split(text): """ sometext|split """ return text.split()
5067bad72a36827f221bde6fcd86c3c124f0b12b
3,601,039
def compute_lda(corpus, id2word, k=10, alpha='auto'): """ Performs the LDA and returns the computer model. Input: Corpus, dictionary and hyperparameters to optimize Output: the fitted/computed LDA model """ lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, ...
67b903ee41bb51fa117a7b70b6fb2270b90b44e9
3,601,040
def load_image(image): """ Preprocess an image. """ # if self.bgr: # temp = image.swapaxes(0, 2) # temp = temp[::-1] # image = temp.swapaxes(0, 2) scale_shape = np.array([224, 224], np.int32) crop_shape = np.array([224, 224], np.int32) mean = np.array([104.00698793, 116.66876...
3f4c36fbd381b8c24bda64218a1eabc3e0ccd194
3,601,041
import logging def _is_LoginForm_in_this_frames(driver, frames): """ 判断指定的 frames 中是否有 登录表单 """ for frame in frames: if _is_LoginForm_in_this_frame(driver, frame): logging.debug('Founded! We Found LoginFrom in this frame{}'.format(frame)) return True else: l...
0a2fd7b817c7a9cecd778dbfff87443d5169a5d7
3,601,042
def not_found(e): """ Controller for not found scenarios [404]. :param e: Exception raised due to the not found error. :return: JSON response. """ log.error(f'Endpoint not found: [{e}]') return response.make(error=True, message='Not found.', code=404)
67482d1c278d3f3171f8589b885edc8f03df279a
3,601,043
from typing import Union import logging from pathlib import Path def parse(**kwargs) -> Union[str, None]: """ Parses data, alternative to running on command line. Keyword Arguments: url (str): url to parse sort (str, optional): Sorting of results. Default ``True`` cache (str, opti...
9c85f4f8517605f78954a28a63852c248b460335
3,601,044
def structural_parameters(keys, columns): """ Gets the structural parameters in a specific order (if catalog is generated by the method in tbridge.binning) """ mags = columns[keys.index("MAGS")] r50s = columns[keys.index("R50S")] ns = columns[keys.index("NS")] ellips = columns[keys.index("EL...
3e6fd7c231f31f4fdcb47cd76359411d194f5539
3,601,045
def infer_batch(model, batch): """recognize text in image provided by file path""" recognized_lines = [infer_line(model, lst) for lst in batch.imgs] return recognized_lines
66b477fc39bc1fe4d59de6c8584a085646ef3d8a
3,601,046
def new_unet( input_size, num_channels=1, num_classes=1, activation="relu", use_batch_norm=True, upsample_mode="deconv", # 'deconv' or 'simple' dropout=0.3, dropout_change_per_layer=0.0, dropout_type="spatial", use_dropout_on_upsampling=False, use_attention=False, filter...
6a6f483b777abb24c9579bb7c8c9e990475a451e
3,601,047
from typing import Optional def get_lambda_function_association(function_arn: Optional[str] = None, instance_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLambdaFunctionAssociationResult: """ Provid...
b776af4cf7ad1e2b98d676fa4690fe5aa1fd822a
3,601,048
def poly(a, x, y, order=4): """Polynomial evaluation. pol = a[i,j] * x**(i-j) * y**j summed over i and j, where i runs from 0 to order. Then for each value of i, j runs from 0 to i. For many of the polynomial operations the coefficients A[i,j] are contained in an array of dimension (order+1, order+...
e5575d4df2ae4cc5f7f1eea467d9b04ebbb97942
3,601,049
def random_in_unit_sphere(): """ Uniformly sample a point from the sphere surface. Returns: coords """ p = 2.0 * ti.Vector([ti.random(), ti.random(), ti.random()]) - ti.Vector([1.0, 1.0, 1.0]) while p.norm() > 1.0: p = 2.0 * ti.Vector([ti.random(), ti.random(), ti.random()]) - ti...
942c5d16760e5e5c7c0e4ada8d6730e32dd3456b
3,601,050
def sharded_and_sliced_predict(params, predict, X, aggregate=max_votes): """Given a sharded and sliced dataset and params, defines the prediction function.""" return aggregate(get_votes(params, predict, X))
f9fba0e246bfb0d15007b340d6093f36286b3ed1
3,601,051
import os import signal import time import logging def stop(): """ Stops the kolibri server :raises: NotRunning """ pid, __, __, status = _read_pid_file(PID_FILE) if not pid: return status with open(PROCESS_CONTROL_FLAG, "w") as f: f.write(STOP) if not wait_for_status...
1b6ad9aad92159adc7300ff115595a57fcaaf970
3,601,052
def unique_vals_counts(df: DataFrame) -> DataFrame: """Count unique values in dataframe. The count is perfromed on all columns in the dataframe. Parameters ---------- df : DataFrame Dataframe to check for unique values per column. Returns ------- DataFrame """ ...
37de2b2aa08e88449e78cff2e259460e88cfdc6b
3,601,053
def groups2csv(grouplist, filename, x='energy', y='norm', _larch=None): """save data from a list of groups to a CSV file Arguments --------- grouplist list of groups to save arrays from filname name of output file x name of group member to use for `x` y ...
8368b4f3e1651c3b6ab3582614313c949707fb26
3,601,054
import scipy def discount(x, gamma): """ Compute discounted sum of future values. Returns a list, NOT a scalar! out[i] = in[i] + gamma * in[i+1] + gamma^2 * in[i+2] + ... """ return scipy.signal.lfilter([1],[1,-gamma],x[::-1], axis=0)[::-1]
d4ab307bb0a82a41ab5754e822ccb7aa0d391e6d
3,601,055
def get_center_category(categories): """ 利用word2vec计算类别列表的相似度,与列表中其他类别最相似的类别作为中心类别 :param categories: 类别列表 :return: 中心类别,各个类别的权重列表 """ categoryCout = len(categories) similarityMatrix = np.zeros((categoryCout, categoryCout)) for i in range(categoryCout): for j in range(categoryCou...
4e2ff3f60dfeada0e0a45283039013537e2abfdb
3,601,056
import argparse def parser(args): """Return parsed command line arguments.""" parser = argparse.ArgumentParser( description=( 'Extracts the convergence indicators of a ONETEP BFGS geometry\n' 'optimisation calculation from the output file, and compares\n' 'them to t...
bef30fbd9278a17e06c68bf7af9d04b877883b1c
3,601,057
def get_moved_siphon(new_centerlines, centerlines, p1, p2): """ Extracts new siphon from new centerline and clipping point information. Args: new_centerlines (vtkPolyData): Centerline data. centerlines (vtkPolyData): Initial centerlines. p1 (ndarray): First clipping point. ...
e1410dc54b9bfe47b40eee12cccf8db1f2a66e3d
3,601,058
def load_train(): """Loads training data.""" with open('mnist_train.npz', 'rb') as f: train_set = np.load(f) train_inputs = train_set['train_inputs'] train_targets = train_set['train_targets'] return train_inputs, train_targets
24a8a48f3b78332bdbad5824bdbf090b3519a2c0
3,601,059
def softmax(X, theta=1.0, axis=None): """ https://nolanbconaway.github.io/blog/2017/softmax-numpy Compute the softmax of each element along an axis of X. Parameters ---------- X: ND-Array. Probably should be floats. theta (optional): float parameter, used as a multiplier prior to ex...
6148f0312d9bf03f3d6b1cf0f9a270142d671560
3,601,060
def transform_angular_velocity( arr, into, outof=None, what="reference_frame", dim=None, axis=None, timestamps=None, time_axis=None, cutoff=None, return_timestamps=False, ): """ Transform an array of angular velocities between frames. The array represents the velocity of...
91b3234ec50d625c67505604eda77f752cbcb30d
3,601,061
import torch import random def prepare_model(): """Main training program.""" #print('Generate Samples') # Disable CuDNN. torch.backends.cudnn.enabled = False # Timer. timers = Timers() # Arguments. args = set_args() #print(args) args.mem_length = args.seq_length + args.mem_...
7a9d8bb544c8edcee4cdabcdfbd5535455edc2d9
3,601,062
def _get_autogrid(phase): """ Helper function to assist with memory re-allocation during FFT calculation """ autocorr_grid = _calc_autoc_grid(phase) nzc = np.sum(np.sum(phase != 0)) autocorr_grid = fftshift(real(autocorr_grid)) / nzc return autocorr_grid
55c36e5d48a5343b5e24564a55cf3a1f8d18cfa3
3,601,063
def vecs2angles(vectors): """ theta = asin(-y) -- pitch phi = atan2(-x, -z) -- yaw """ x, y, z = vectors.T pitch = np.arcsin(-y) yaw = np.arctan2(-x, -z) return np.column_stack((yaw, pitch))
6a1efda78716c361419b32d95c5d916e10e272c0
3,601,064
import requests import io def cpi(startdate="1960-01-01", enddate="2021-01-01"): """ Full Name: Consumer Price Index: Total All Items for the United States Description: Percent, Monthly, Quarterly and Annually, Seasonally Adjusted Return: pd.DataFrame """ tmp_url = url["fred_econ"] ua = Us...
72e16316154e92776f614982211b9a78bb5bcf43
3,601,065
import struct def short_to_bytes(short_data): """ For a 16 bit signed short in little endian :param short_data: :return: bytes(); len == 2 """ result = struct.pack('<h', short_data) return result
26eeb2de936fa6b434c724ef80c008d93aec0446
3,601,066
def random_circle_at_origin(*, rng=None): """ Creates a random circle at the origin """ rng = np.random.default_rng(rng) mv_a = random_euc_mv(rng=rng) mv_r = random_euc_mv(rng=rng) r = generate_rotation_rotor(np.pi/2, mv_a, mv_r) mv_b = r*mv_a*~r mv_c = r * mv_b * ~r pp = (up(mv_...
edafd334d8c4329978dfb398f84306c159b7a9b6
3,601,067
import numpy def append_gaintable(gt: GainTable, othergt: GainTable) -> GainTable: """Append othergt to gt :param gt: :param othergt: :return: GainTable gt + othergt """ assert gt.receptor_frame == othergt.receptor_frame gt.data = numpy.hstack((gt.data, othergt.data)) return gt
f9fcfa4a5a8d5ef916bd6cad027fad2c9e82f6f7
3,601,068
def cumprod(pda): """ Return the cumulative product over the array. The product is inclusive, such that the ``i`` th element of the result is the product of elements up to and including ``i``. """ if isinstance(pda, pdarray): repMsg = generic_msg("efunc {} {}".format("cumprod", pda.na...
fd50fe3af900c999409adf5808a29d6168150ec7
3,601,069
from fsspec import AbstractFileSystem, registry import os def test_to_parquet_gcs_new_file(monkeypatch, tmpdir): """Regression test for writing to a not-yet-existent GCS Parquet file.""" registry.target.clear() # remove state df1 = DataFrame( { "int": [1, 3], "float": [2....
5e6811dc3b6bafcc0fd4511634fe37b1c57f969e
3,601,070
def LogDebug(*args, **kwargs): """LogDebug(String msg)""" return _misc_.LogDebug(*args, **kwargs)
6a967993d61bf4c7a3822bbc31fa588acbed8647
3,601,071
def approximateAgeCohorts(df, splits=countyAgeProportions, mode='by county'): """Takes a df of flat cases by county and splits by age proportions""" dfs = [] if mode == 'by county': for key in ageProportions.keys(): dfSub = df.copy(deep...
dac2a9f5b13338751550851a04ed808872008e99
3,601,072
def get_average_color(first, second): """ Combine two colors into one average :param first: <tuple> :param second: <tuple> :return average_color: <tuple> """ log_.debug("Getting the average color.") log_.debug(" from: %s", first) log_.debug(" from: %s", second) stage = [] ...
d038a0acb2ecafcaa85e9508fdd81767bbed25e9
3,601,073
def adjust(new_rows, maxi): """ A function to set all with maxi number of columns for making csv compatible """ rows = [] for each_row in new_rows: if len(each_row) < maxi: for i in range(maxi - len(each_row)): each_row.append("-") rows.append(each_row...
2151362add7a85c4a236ad9ee936dcc08578534b
3,601,074
import os def get_event_detector_df_path(event: int, detector: int, df_dir: str = DF_DIR): """ Given detector and event returns path to corresponding df :param event: event number :param detector: detector number :param df_dir: directory with dataframe files :return: path to pandas dataframe ...
2dfe9a590cb525397a2f519eab7c639aef31ad7b
3,601,075
import struct def icmp_construct(seq=1): """Returns ICMP packet with all required fields. However, identifier is not set and timestamp might also be included. """ icmp_type = 8 # (1B) Echo ping icmp_code = 0 # (1B) icmp_checksum = 0 # (2B) icmp_id = 0 # (2B) icmp_seq = seq # (2B) ...
0676937bc7dc94b6417f1f0cec414ac9301d0d28
3,601,076
def outer_product(u, v): """m_ij = u_i v_j""" return Matrix( u.x*v.x, u.x*v.y, u.x*v.z, u.y*v.x, u.y*v.y, u.y*v.z, u.z*v.x, u.z*v.y, u.z*v.z )
ea0fa00b9c437bbcfec6cd51ac0ede77a32ff995
3,601,077
def DefineFrameNodesAndElementsSteelIShape(n_hor_axis: int, n_vert_axis: int, storey_width, storey_height, list_col: list, list_beam: list, geo_trans_ID: int, N_G = np.array([]), t_dp = np.array([]), L_b_col = np.array([]), L_b_beam = np.array([]), fix_support = True, show_plot = True, panel_zone = True): "...
824242f3512de462197501472e724c17f150de17
3,601,078
def from_triples(triples): """ Decode triples, as from :func:`to_triples`, into a DMRS object. """ top = lnk = surface = identifier = None nids, nd, edges = [], {}, [] for src, rel, tgt in triples: rel = rel.lstrip(':') src, tgt = str(src), str(tgt) # in case penman converts ids...
f1cdcf5dc035e5e2584ac95864ed08814e66e921
3,601,079
import os import shutil def get_sky_cells(visit_input, input_path=None, scale=None, cell_size=None): """Return all sky cells that overlap the exposures in the input. Parameters ----------- visit_input : str or list Input specifying the exposures from a single visit; either a poller ou...
7e72f45510b0606715615d4c2a38f56bee28613f
3,601,080
from typing import Union from typing import Optional def convert_chinese_to_bool(message: Union[Message, str]) -> Optional[bool]: """将中文中表示判断的词语转换为布尔值 参数: message: 消息对象或消息文本 返回: 是表达同意的布尔值, 如果无法确认判断的词语, 则返回 `None` """ text = message.extract_plain_text() if isinstance(message, Mess...
f6299b1335e46c3844b70d39640cb9cfe77b984d
3,601,081
def user_authenticated(user): """ Checks if a user is authenticated. :param user: User to check :return: True, if the useris verified and accepted general terms and conditions as well as the privacy policy; False otherwise. """ if isinstance(user, User): return \ user.is_...
6f32b49c2d6b9fe704bbf59f63e4182911bc96e9
3,601,082
import sys def recompute_derivatives(model: StateDynamics, times, states): """ Re-run the dynamics to access the state derivatives (accelerations). In `simulate` the derivatives are internal, but it can be helpful to know the accelerations at each time step. This is a bit of a kludge, but it's fa...
5889d8fff6950a5ba0b8e57afa74755364f5ff7c
3,601,083
def gen_car1(t,alpha,sig): """ gen_car1 generates red noise time series with uneven time grid. Inputs: - t [1-dim numpy array of floats]: the times of the time series. - alpha [1-dim numpy array of floats]: values of the coefficient of the AR-1 process, as defined in 'A General Theory on Spectral Analysis f...
a4bdf51548d74d3a42737320204274483a896c9c
3,601,084
def unflatten_B(t): """ Unflatten [B*3, ...] tensor to [B, 3, ...] tensor t is flattened tensor from component batch, which is [B, 3, ...] tensor """ shape = t.shape return t.view(shape[0]//3, 3, *shape[1:])
77017ca136a942f975dfd498fe3aa8d3d20f67b9
3,601,085
import csv from datetime import datetime def findTimestampsOfScoresOnHasAndLas(dateLookup, hardcodedLookup): """ Go through all scores in HAS_Calculations and find the corresponding dates return a list of score objects for all scores in HAS_Calculations with a date added Hardcoded Lookup ...
e41ce3905d4ceab9f8afdaac456de6be57372850
3,601,086
def residuals(x1, x2): """ Calculates the residuals between two data sets. Parameters: x1, x2: array The arrays containing the data. They must have the same dimensions. Returns: An array of the same size of x1 containing the residuals. Th...
a7523fb7d3ddd726508bcc50cfc4cdac10382d8b
3,601,087
def unflatten_optimizer_step(step): """ Wrap an optimizer step function that operates on flat 1D arrays with a version that handles trees of nested containers, i.e. (lists/tuples/dicts), with arrays/scalars at the leaves. """ @wraps(step) def _step(value_and_grad, x, itr, state=None, *args,...
8c9fe53af31c741384039503099bdeb193f5c753
3,601,088
import torch def l12_smooth(input_tensor, a=0.05): """Smoothed L1/2 norm""" if type(input_tensor) == list: return sum([l12_smooth(tensor) for tensor in input_tensor]) smooth_abs = torch.where(torch.abs(input_tensor) < a, torch.pow(input_tensor, 4) / (-8 * a ** 3) + to...
f6de684a53605aa3f28cf21f46f90dbb5d325616
3,601,089
import json def english_to_french(englishtext): """ This function translates English text to Frenc text """ frenchtext = language_translator.translate( text=englishtext, model_id='en-fr').get_result() print(json.dumps(frenchtext, indent=2, ensure_ascii=False)) return frenchtext.get("tr...
acdddc18c0b105e1935494da245b305a554a8d36
3,601,090
def docker_image_update(tag): """Update (if needed) the docker image. :param tag: docker tag :type tag: str :return: either the image has been updated or not :rtype: bool """ set_prompt_color("Purple") have_been_updated = True id_image_base = None try: print("Trying to u...
3c37ac89b5942906ecfd9b51d9dd8bc207cc017f
3,601,091
import os def config_open(config_file, config_section='default'): """ Read configuration file :param config_file: :param config_section: :return: """ if not os.path.exists(config_file): new_config(config_file, config_section) cfg = conf.read(config_file) return cfg
a40a27643b0f8816ee221d9a861dc31b7aea1766
3,601,092
def _dedupe_entities(alerts, ents) -> list: """Deduplicate incident and alert entities.""" alrt_ents = [] for alrt in alerts: if alrt["Entities"]: alrt_ents += [ent.__hash__() for ent in alrt["Entities"]] for ent in ents: if ent.__hash__() in alrt_ents: ents.remo...
9fc56c217d5a6f2ad85c100f3ee5f8a049de0d1c
3,601,093
def find_components(value): """ Extract the three values which have been combined to form the given output. """ r1 = value >> 20 # 11 most significant bits r2 = (2**10 - 1) & (value >> 10) # 10 middle bits r3 = (2**10 - 1) & value # 10 least significant bits return...
80a235cafe8ceb37cafb6453f3338e03653bffe1
3,601,094
def linkage_report( df, no_entity_id="Unable to connect Responsibility to Entity" ): """ Creates primary entity linking report for processed RE documents. Args: df: dataframe of post-processed RE docs no_entity_id: text of non-linked entity option Returns: dataframe of ...
f59060fc20d7e5e95ae89797fbb889d51692df0d
3,601,095
def callBranchDepth(jid, motifDict, tomtomDict, depth, fileList): """Call the Branch and cut algorithm to select motifs To run use: ./bc moitfSeqFile To compile using: g++ branch_cut.cc -lglpk -o bc Args: motifDict: dict between motif IDs and seqs it occurs in tomtomDict: dict between motif Ids and a list of m...
8c599f162f4b7c7733177227f0754b0436c4be49
3,601,096
def choose_boundary(): """ Our embarassingly-simple replacement for mimetools.choose_boundary. """ return uuid4().hex
be9c1d7060f8a1d191cf8ac7ec6f370a7e49c86a
3,601,097
def get_tfm_secure_targets(): """ Creates a list of TF-M secure targets from Mbed OS targets.json. :return: List of TF-M secure targets. """ return [str(t) for t in TARGET_NAMES if Target.get_target(t).is_TFM_target]
7306aa5c815fa4e261f0ff495dd36d94959a9f7a
3,601,098
def most_energetic(df): """Grab most energetic particle from mc_tracks dataframe.""" idx = df.groupby(["event_id"])["energy"].transform(max) == df["energy"] return df[idx].reindex()
031e5a92d9e890743323012227ffbd4048d0052a
3,601,099