content
stringlengths
22
815k
id
int64
0
4.91M
def build_keras_network(model_file: str) -> Network: """ Wrapper for the more low-level KerasNetwork classes. Figures out the backend and returns an istance of the appropriate class. Parameters ---------- model_file Path to the .h5 model file. Returns ------- """ curren...
67,000
def get_parser(identifier): """ :param identifier: :return: """ ret_parser = None for parser in BINSON_VALUES: if identifier in parser.identifiers(): ret_parser = parser.from_bytes break if not ret_parser: error_msg = 'Value 0x%02x' % identifier ...
67,001
def approximate_quantum_error(error, *, operator_string=None, operator_dict=None, operator_list=None): """ Return an approximate QuantumError bases on the Hilbert-Schmidt metric. Currently this is only implemented for...
67,002
def change_image_brightness(image_path, new_image_path, a=0.5, g=10): """ 用来改变图片的亮度,并保存到新的文件地址 :param image_path: 输入的图片路径 :param new_image_path: 需要保存的文件位置 :param a: 亮度控制,0-1,默认为 0.5 :param g: 默认为 10 :return: """ image = cv2.imread(image_path) h, w, ch = image.shape ...
67,003
def cat_scsi_test(): """ Check for drive labeled "solid state" """ print('confirming an SSD in this machine with "cat /proc/scsi/scsi"') call(["cat", "/proc/scsi/scsi"]) scsi = str(os.popen("cat /proc/scsi/scsi").read()).lower() if "ssd" not in scsi: print(it("red", "***WARN*** no dr...
67,004
def fetch_repos(args, testing=False): """ Fetch the repositories and write the raw links into an output txt file """ g = GitHub(args.token, password=None, timeout=args.timeout, per_page=args.per_page) base = "https://raw.githubusercontent.com" all_repos = set() nb_search = args.nb_search ...
67,005
def demo(sess, net, im_file, icdar_dir, oriented=False, ltrb=False): """Detect object classes in an image using pre-computed object proposals.""" # Load the demo image im = helper.read_rgb_img(im_file) # Detect all object classes and regress object bounds timer = Timer() timer.tic() scores...
67,006
def load_cam_ext(file): """ read camera txt file """ cam = np.empty((3, 4)) data = file.read().split() for i in range(3): for j in range(4): cam[i, j] = data[4 * i + j + 1] return cam
67,007
def onFile(): """ Run the detailed correctness tests with summary on the selected scene. Returns a list of the directories in which results can be found. """ pass
67,008
def test_Unsample_scale_factor(): """ api: paddle.Upsample op version: 9, 10, 11, 12 """ op = Net(scale_factor=[2, 3]) op.eval() # net, name, ver_list, delta=1e-6, rtol=1e-5 obj = APIOnnx(op, 'nn_Unsample', [9, 10, 11, 12]) obj.set_input_data( "input_data", paddle.to...
67,009
def approximants(l, X=Symbol('x'), simplify=False): """ Return a generator for consecutive Pade approximants for a series. It can also be used for computing the rational generating function of a series when possible, since the last approximant returned by the generator will be the generating functio...
67,010
def error_propagation( func: sp.Function, syms: tp.List[sp.Symbol], vals: np.ndarray, covar: np.ndarray = None, stds: np.ndarray = None) -> tp.Tuple[sp.Expr, sp.Expr]: """Error propagation for an arbitrary function""" if (covar is None) == (stds is None): raise Va...
67,011
def get_db_config(): """ 获取服务器链接 :return: host, user, password, database, port, charset """ db_config = get_config() if "mysql" in db_config: host = db_config['mysql']['host'] user = db_config['mysql']['user'] password = db_config['mysql']['password'] database = ...
67,012
def phase_dates(base_sunday: datetime.date) -> List[datetime.datetime]: """ Test dates and times for the entire week of base_sunday. These are the times we will use as our message times for updating bell prices. """ sunday = relative_message_time(sunday=base_sunday, weekday=6) monday_am = relat...
67,013
def rejection_sampling(X, e, bn, N): """Estimar a distribuição de probabilidade da variável X dada Evidência e em BayesNet bn, usando N amostras. [Figura 14.14] Gera um ZeroDivisionError se todas as N amostras são rejeitadas, I.e., inconsistente com e.""" counts = {x: 0 for x in bn.variable_values(X...
67,014
def get_valid_pbc(inputpbc): """ Return a list of three booleans for the periodic boundary conditions, in a valid format from a generic input. :raise ValueError: if the format is not valid. """ if isinstance(inputpbc, bool): the_pbc = (inputpbc, inputpbc, inputpbc) elif (hasattr(inp...
67,015
def test_negate_of_neg(): """Check functionality of unary neg operator.""" return """ fn main() { var a := -1; {dest} = -a; } """
67,016
def get_user_for_token(token, scope, max_age=None): """ Given a selfcontained token and a scope try to parse and unsign it. If max_age is specified it checks token expiration. If token passes a validation, returns a user instance corresponding with user_id stored in the incoming token. ...
67,017
def _generate_bytes(size_bytes: int, times: int = 1): """ Generates a list of <times> random bytes objects, each the size of <size_bytes>. """ return [os.urandom(size_bytes) for _ in range(times)]
67,018
def redirect(url: str) -> typing.Callable: """ This function returns a decorator that redirects the request to the given url. """ html = f""" <!DOCTYPE html> <html> <p>Redirecting...</p> <p><a href="{url}">Click here if you are not redirected</a></p> <...
67,019
def open(): """A function that opens cans."""
67,020
def test_get_details2(doc: Doc) -> None: """Returns span details.""" doc[0]._.spaczz_details = 1 doc[1]._.spaczz_counts = (0, 0, 0) assert doc[:2]._.spaczz_details is None
67,021
def bi_tempered_binary_logistic_loss(activations, labels, t1, t2, label_smoothing = 0.0, num_iters=5, reduction='mean'): """Bi-Tempered binary logistic loss. Args: activations: A tensor containing activations for class 1. labels: A tensor with shape a...
67,022
def test_grades(client): """Test the grade_book page to see if page loades""" assert client.get('/course/180/session/2/grades').status_code == 302 rv = login( client, 'student@stevenscollege.edu', 'asdfgh') assert b'Logged in' in rv.data with client: client.get('/courses/180/grades...
67,023
def write_README_for_current_parameters_directory(readme_path, **problem_parameters): """ Writes the readme file (README.md) for the directory of the given set of problem parameters. Parameters ---------- readme_path : pathlib.Path object the path where the readme file will be located ...
67,024
def test_set_fees_with_stewards(helpers): """ Setting fees fails with stewards. """ fees = {NYM_FEES_ALIAS: 1} fees_request = helpers.request.set_fees(fees) sigs = [(k, v) for k, v in fees_request.signatures.items()] sigs.sort() sigs.pop(0) fees_request.signatures = {k: v for k, v in...
67,025
def get_paths(param, targetdir=None, smbconf=None): """Get paths to important provision objects (smb.conf, ldb files, ...) :param param: Param object :param targetdir: Directory where the provision is (or will be) stored :param smbconf: Path to the smb.conf file :return: A list with the path of imp...
67,026
def bucketize(tensor, bucket_boundaries): """Equivalent to numpy.digitize Notes ----- Torch does not have a built in equivalent yet. I found this snippet here: https://github.com/pytorch/pytorch/issues/7284 """ result = torch.zeros_like(tensor, dtype=torch.int32) for boundary in bucket_...
67,027
def get_landmark_distance( adata: ad.AnnData, landmark_position_key: str = "curated_landmarks", landmark_distance_key: str = "landmark_distances", reference: Optional[Union[m.Reference, np.ndarray]] = None, **kwargs, ) -> None: """compute landmark distances :param adata: AnnData object wher...
67,028
def _get_task_path(wrapped, instance) -> str: """Get the synthetic URL path for a task, based on the `wrapt` parameters.""" funcname = wrapped.__name__ if funcname.startswith("_") and not funcname.endswith("_"): funcname = re.sub(r"^_+", repl="", string=funcname, count=1) if instance is None: ...
67,029
def location_from_dictionary(d): """ Builds a *Location* object out of a data dictionary. Only certain properties of the dictionary are used: if these properties are not found or cannot be read, an error is issued. :param d: a data dictionary :type d: dict :returns: a *Location* instance ...
67,030
def assert_args_correct_typing( params: Mapping[str, inspect.Parameter], args: Tuple[Any], kwargs: Mapping[str, Any], join: bool = True, context: str = "", ) -> None: """ Applies :func:`output_if_args_incorrect_typing` with assertion error as output. :param params: the parameter ...
67,031
def about(): """Render About page. Only when is run independent from ComPath""" metadata = [ ('Python Version', sys.version), ('Deployed', time_instantiated), ('KEGG Version', current_app.pathme_manager.get_pathway_by_id('hsa00010', 'kegg').created), ('Reactome Version', current_...
67,032
def get_task(username, m_wf_id, wf_id, task_id): """ Returns task identified by m_wf_id, wf_id, task_id. :query boolean pretty-print: Return formatted JSON response :statuscode 200: OK :statuscode 401: Authentication failure :statuscode 403: Authorization failure :statuscode 404: Not found...
67,033
def check_all(doc_root): """ check_all iteratively checks docs link. return True on error occurs, broken links will be outputed to stderr """ has_error = False for root, dirs, files in os.walk(doc_root): for name in files: if name.endswith(".md"): path = os.path.join(...
67,034
def test_explicit_nested_folds(): """Tests explicit nested folds experiment.""" X, y = load_boston(return_X_y=True) _experiment([[X[:10], y[:10], X[10:20], y[10:20]], [X[10:20], y[10:20], X[20:30], y[20:30]], [X[20:30], y[20:30], X[30:40], y[30:40]]], [[X[:1...
67,035
def requires_internet(func): """ Decorator for functions that require internet Parameters ---------- func: func Function that requires an active internet connection Returns ------- """ def inner(*args, **kwargs): if internet(): return func(*args, **kwargs) ...
67,036
def replace_colons(text: str, strip: bool = False) -> str: """Parses a string with colon encoded emoji and renders found emoji. Unknown emoji are left as is unless `strip` is set to `True` :param text: String of text to parse and replace :param strip: Whether to strip unknown codes or to leave them as ...
67,037
def check_feature_names(num_features, feature_names, active_features): """Check feature names for consistency and supply defaults if necessary. :param num_features: positive integer; number of features :param feature_names: list of strings or None; if not None, must have num_features elements :par...
67,038
def autoslugWithFieldAndUUID(fieldname): """[Generates auto slug integrating model's field value and UUID] Args: fieldname ([str]): [Model field name to use to generate slug] """ def decorator(model): # some sanity checks first assert hasattr(model, fieldname), f"Model has no f...
67,039
def create_sequence_diagram_x(eye_x, eye_valid, height, width, offset=0, step=0.5, should_skip=True): """ A Function that returns a 2D numpy array representing the sequence diagram on it :param eye_x: an indexable datastructure with the x eye coordinates :param eye_valid: an indexable d...
67,040
def compute_hashes(paths, path_only=lambda p: False): """Computes strong hashes of the contents of all the files paths, and returns them as a list. :param path_only: Optional lambda function which takes in a path, and returns true if that path should be hashed using only its pathname, rather than its binary con...
67,041
def status(channel_id): """From Hub fetch Status""" channel = Channel.query.get_or_404(channel_id) response = channel.refresh() return jsonify(response)
67,042
def memcmp_unsized(_core, _, plt_path): """ memcmp-like unsized (e.g., strlen) function summary :param _core: core taint engine :param _: not used :param plt_path: path to the plt (i.e., call_site.step()) :return: None """ p = _core.p dst_reg = arg_reg_name(p, 0) src_reg = ar...
67,043
def collect_dmripreproc_output(dmriprep_dir, subject_id, session_id = None): """ Collect the dmripreproc output files for a specific subject and session. """ import os dmri_output = dict() dmri_files = os.listdir(dmriprep_dir) # Get path for this subject subject_name = "sub-" + subject_i...
67,044
def run(): """prepare txt data""" args = parse_args() # load npy data data = np.load(os.path.join(args.data_dir, args.data_file.format(args.mode))) income = np.load(os.path.join(args.data_dir, args.income_file.format(args.mode))) married = np.load(os.path.join(args.data_dir, args.married_file.fo...
67,045
def test_empty(): """No nodes.""" g = SimpleGraph() groups = g.get_groups() assert groups == []
67,046
def init_app(): """Construct core Flask application with possible Dash app.""" fapp = Flask(__name__, instance_relative_config=False) fapp.config.from_object('config.Config') with fapp.app_context(): # Import parts of our core Flask app from . import routes # # Import Dash appl...
67,047
def test_find_newest_timestamp(): """Test it finds the newest data.""" database = TinyDB("tests/fixtures/dbs/dates-data.json") assert find_newest_timestamp(database) == 1609459200 assert find_newest_timestamp(None) is None
67,048
def ensure_rgwa_entities(vf): """Given a vf, ensure that its RGWA BUCKET are created. """ formated_vf = VFModelSerializerForSignal(vf).data engagement_stage = formated_vf['engagement']['engagement_stage'] bucket_name = vf.engagement.engagement_manual_id + "_" + vf.name.lower() if engagement_...
67,049
def get_lidar_image_message(lidar_image): """Convert an opencv image (image) to an imgmsg.""" try: return bridge.cv2_to_imgmsg(lidar_image, encoding="mono8") except CvBridgeError: rospy.loginfo("Error converting lidar image to imgmsg") raise
67,050
def get_argument_parser(): """ List of arguments supported by the script """ parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", type=str, help="Path to the folder containing the 'jpg', 'imagelabels.mat' and 'setid.mat' files", ) parser.ad...
67,051
def make_email(slug): """Get the email address for the given slug""" return '{}@djangogirls.org'.format(slug)
67,052
def list_files_of_extensions(folder, extensions): """ List files in the specified folder which have the specified extensions. Do not traverse subfolders. folder: string path to folder containing files extensions: only files with these extensions will be returned Return a list of paths to the f...
67,053
def count_related(model, field): """ Returns a `Subquery` suitable for annotating a child object count. """ subquery = Subquery( model.objects.filter(**{field: OuterRef("pk")}) .order_by() .values(field) .annotate(c=Count("*")) .values("c") ) return Coales...
67,054
def test_space_after_comma(): """ Test allowing space after comma for attribute type. """ with pytest.raises(errors.InvalidDN): _ = LDAPDN("c n=user,dc=test,dc=local") with pytest.raises(errors.InvalidDN): _ = LDAPDN("cn=user,dc =test,dc=local") dn = LDAPDN("cn=user, dc=test, dc=local") ...
67,055
def get_not_registered_tests(conf_json_tests: list, content_item_id: str, file_type: str, test_playbooks: list) -> list: """ Return all test playbooks that are not configured in conf.json file Args: conf_json_tests: the 'tests' value of 'conf.json file content_item_id: A content item ID, cou...
67,056
def _dataarray_unstack(da, sources, targets, roi_tot, fill_value, order, rm_missing): """Unstack a 1d to 2d DataArray.""" import pandas as pd da['roi'] = pd.MultiIndex.from_arrays( [sources + targets, targets + sources], names=['sources', 'targets']) da = da.unstack(fill_...
67,057
def check_defined_env_val(): """Confirm existence of environment variables.""" try: if os.getenv('POCKET_CONSUMER_KEY') is None or \ os.getenv('POCKET_ACCESS_TOKEN') is None or \ os.getenv('SLACK_POST_URL') is None: raise NoEnvValExcepion( 'this script n...
67,058
def check_dir_structure(): """ Sets up the directory structure """ vec_path = config['vec_path'] mongo_dump_path = os.path.join( config['root_dir'], 'mongo_dump' ) emote_model_path = os.path.join( ...
67,059
def to_internal_dt(date_time): """ Convert input datetime to internal timezone and removes microsecond component. """ return date_time.astimezone(zoneinfo.ZoneInfo(settings.internal_tz)).replace(microsecond=0)
67,060
def test_invalid_assignment(): """Invalid assignments to `process` or `spec` throw a TypeError.""" with pytest.raises(TypeError): MaterialRun(name=12) with pytest.raises(TypeError): MaterialRun("name", spec=ProcessRun("a process")) with pytest.raises(TypeError): MaterialRun("name...
67,061
def construct_csv(cursor): """ transforms the db cursor rows into a csv file string """ header, data = construct_list(cursor) # python 2 and 3 handle writing files differently if sys.version_info[0] <= 2: output = io.BytesIO() else: output = io.StringIO() writer = csv.wr...
67,062
def _get_queue_properties(): """Function used to return a list of queue properties.""" properties = [] properties.append(QueuePropHeader( queue_property=QueueProperties.OFPQT_MIN_RATE, length=12)) return properties
67,063
def _dump_privatekey(key, filetype=FILETYPE_PEM): """Dumps obj private key object to string.""" return crypto.dump_privatekey(filetype, key)
67,064
def pool3d(layer, ksize, strides, padding, pooling_type): """Convenience function to perform pooling in 3D Parameters ---------- layer : tf.Tensor Input tensor. ksize : list of int Size of pooling kernel in each dimension: [size_batch, size_x, size_y, size_z, size_channe...
67,065
def initialize_reservoir_state(self, grid: Grid, config: Benedict, parameters: Parameters) -> None: """Initializes the reservoir state. Args: grid (Grid): the model grid config (Config): the model configuration parameters (Parameters): the model parameters """ # reservoir stora...
67,066
def generateUniformMesh(domain: Domain, offset=0): """ [i][]: i source index [][k]: k = 0,1, where 0 is X data and 1 is t data """ if domain.spatial_dimension == 1: grid = np.meshgrid( np.linspace(domain.Xbounds[0][0], domain.Xbounds[1][0], domain.nX[0]), ...
67,067
async def azip(*aiters): """ async version of zip This function takes a list of async iterators and returns a single async iterator that yields tuples of elements. This iterator advances as slow its slowest component (obviously). example: async for a, b, c in azip(aiter1, aiter2, aiter...
67,068
def flipTurn(piece): """手番反転 Returns ------- str piece """ if piece == PC_X_LABEL: return PC_O_LABEL elif piece == PC_O_LABEL: return PC_X_LABEL return piece
67,069
async def startPrediction(sid, data): """ data: dict of - champion id - lane """ log(sid, "startPrediction", data) runeproposers[sid] = RuneProposer(models, preprocessing); if not "champion_id" in data or not "lane" in data: return False, "Missing champion or ...
67,070
def IMG_isCUR(src): """Tests whether a file object contains a CUR (Windows cursor) image. Args: src (:obj:`SDL_RWops`): The file object to check. Returns: int: 1 if BMPs are supported and file is a valid CUR, otherwise 0. """ return _ctypes["IMG_isCUR"](src)
67,071
def compute_kid_from_feature(fake_features, real_features, num_subsets=100, max_subset_size=1000): """Computes Kernel Inception Distance (KID) based on the extracted features. KID metric is introduced in https://arxiv.org/pd...
67,072
def blockmodel(g, k, iterations=20, corrected=True, indices=[]): """ Takes a graph and a number of clusters, returns group assignments. g is the graph, a 2- or 3-d binary (NOT boolean) numpy array Right now, treats the network as 1-mode, so there's only 1 k. """ # The indices of the people whose n...
67,073
def test_1_7_aromatic_heteroatom_enumeration(): """1,7 aromatic heteroatom H shift""" assert enumerate_tautomers_smiles('c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1') == {'c1ccc2[nH]c(-c3nc4ccccc4[nH]3)nc2c1', 'c1ccc2c(c1)=NC(c1nc3ccccc3[nH]1)N=2', 'c1ccc2c(c1)NC(=C1N=c3ccccc3=N1)N2'}
67,074
def test_different_sub_same(): """ arg=None """ _info = setup_conv() conv = _info['conv'] # Need 2 IdToken one with public and one pairwise sub atr = { "access_token": "ZDZjNWFmNzgtN2IxMi00YTY1LTk2NTEtODIyZjg5Ym", "expires_in": 7200, "id_token": { ...
67,075
def _get_otsu_threshold(gray_img) -> int: """大津の二値化によるしきい値を返します。 Arguments: gray_img {numpy.ndarray} -- グレー画像(1ch) Returns: int -- しきい値 """ opt_threshold = 0 max_sb2 = 0 # w0 * w1 * (M0 - M1) ^2 が最大になるような t が最適なしきい値 for threshold in range(1, 256): sb2 = _get_sb...
67,076
def create_dropout_layer(dropout, num_gpus, default_gpu_id, random_seed): """create dropout layer""" dropout_layer = Dropout(rate=dropout, num_gpus=num_gpus, default_gpu_id=default_gpu_id, random_seed=random_seed) return dropout_laye...
67,077
def main() -> None: """ Function to be used by a script as the main CLI entrypoint. """ try: run() except errors.BaseError as e: sys.stderr.write(f'{str(e)}\n') sys.exit(e.code)
67,078
def r2_op(predictions, targets, inputs): """ r2_op. An op that calculates the standard error. Examples: ```python input_data = placeholder(shape=[None, 784]) y_pred = my_network(input_data) # Apply some ops y_true = placeholder(shape=[None, 10]) # Labels stderr_op =...
67,079
def baremetal_detach_volume(server, volume_id, openstack_client, attachment_uuid=None): """ Baremetal detach volume :param openstack_client: openstack client :param server: the server object get by server id :param volume: volume id :return: attachments """ guest_id = server.metadata.get...
67,080
def create_arg_parser(parent): """Create command subparsers. Parameters ---------- parent : `argparse.ArgumentParser` Command parser. """ arg1 = parent.add_subparsers(dest='command') arg2 = arg1.add_parser('create') arg2.add_argument('-P', '--progress', a...
67,081
def insert_initial_data(conn): """ Finish this function to insert the initial data to the database. The course and student data has been provided above. Assume that all students are registered for all courses. Sample comments on how to proceed have been provided. """ # create a Cursor objec...
67,082
def dday_to_datetime64(dday: np.ndarray, yearbase: int) -> tp.Tuple[NDArray, NDArray]: """Convert time recorded time to pandas time (np.datetime64[s]). Replace time coordinates with datetime64 in strftime='%Y-%m-%d %H:%M:%S' Add `time_string` variables to dataset (strftime='%Y-%m-%d %H:%M:%S') Paramet...
67,083
def test_boundless_mask_special(): """Confirm resolution of special case in issue #1471""" with rasterio.open("tests/data/green.tif") as src: mask = src.read_masks(2, boundless=True, window=Window(-1, -1, 66, 66)) assert not mask[:, 0].any() assert not mask[:, -1].any() assert not mask[0, :]...
67,084
def quant(bins, bins_density, interval=0.95): """ Get the indexes defining range of equal tail density (for one interval) given binned density values. :param bin_density: :return: indexLower, indexUpper: the indexes corresponding to the edge of the interval :type list of one tuple...
67,085
def evaluate_field_nodeset_mean(field: Field, nodeset: Nodeset): """ :return: Mean of field over nodeset. """ fieldmodule = nodeset.getFieldmodule() components_count = field.getNumberOfComponents() with ChangeManager(fieldmodule): mean_field = fieldmodule.createFieldNodesetMean(field, no...
67,086
def open_generic_product(inpath): """Open a satellite product. Open a satellite product based on satpy functions without specifying a reader. :param inpath: Path to the folder containing the satellite images :type inpath: pathlib.PosixPath :return: Satpy scene containing the opened satellite p...
67,087
def _get_best_sol2(x_0, y_0, x_1, y_1, x_ca, y_ca, x_prev, y_prev, r_a, r_b, sols, i_center=1): """Gets the solution with the the solution with the shortest arclength """ arc_lengths = [] for i, sol in enumerate(sols): # Look for NaNs in tan point and center point if any([math.isna...
67,088
def generate_one_year(year, path_features="./../data/wikipedia_italy/new_data"): """ Generate a dataframe containing the data of only one influenza season. The dataframe contains, for each week, the pageview of a each Wikipedia's page of the dataset. :param year: the year we want to generate the da...
67,089
def s_input(prompt : str = ">", accepted_inputs : list = ["break"], case_sensitive : bool = False, fail_message : str = "") -> str: """Keeps asking for user input until the answer is acceptable. Args: prompt (str, optional): User is prompted with this each time. Defaults to ">". accept...
67,090
def set_vmem_rt(args, run_dir, conf, run_hours, nslots=1, pool_jobs=False, test_run=False, request_vmem=True): """Set vmem and runtime per time step based on settings in config file.""" skip = False resource_search_paths = [args["run_path"], *conf.resource_search_paths] # get runtime ...
67,091
def comparison(uncalibrated_zs,calibrated_zs,ys,pop_type,pop_order): """ Compare probabilities of a population type before and after calibration and plot binned probabilities histogram """ # pop_type (int between 0 and len(pop_order) for which population the comparison needs to be fig, (ax1,...
67,092
def hadamard(normalized=False, dtype=jnp.float32): """We need the numpy to use it as initializer""" def init(key, shape, dtype=dtype): n = shape[0] # Input validation if n < 1: lg2 = 0 else: lg2 = np.log2(n) assert 2 ** lg2 == n, "shape must be a ...
67,093
def _gen_ntluf_capture_chain_fo(nt_names, ii): """ Given a list of OP_NAME_NT_NAME strings(nt_names), generate a function object (function_object_t) that calls corresponding xed3 NT capturing functions. Each such function captures everything that xed2 decode graph would capture for a given patt...
67,094
def silhouette_loss(input_img, prob, z, vh=128, vw=128, num_kp=10): """ Args: prob, z: Output of keypoint network for a single image (batch_size, 128, 128, 10) """ mask = input_img[..., 3] mask = tf.cast(tf.greater(mask, tf.zeros_like(mask)), dtype=tf.float32) prob = ge...
67,095
def get_ctrl_vec(exs, history, control_settings): """ Given a batch of examples with given history, return the bucketed CT control values. This is used both when training and evaluating CT systems. Inputs: exs: list length batch_size of message dictionaries. Each dictionary contains a 'te...
67,096
def get_ports(db_name): """Extract all local_port that are being used. Args: db_name: Database name used to read. Return: ports: local_port from all users. """ # CHECK IF DB EXISTS OR NOT if os.path.isfile(db_name): try: # CONNECT TO DB conn = sql...
67,097
def modify_query_with_nested_views(self, grant_target_name, user_name, node=None): """Grant MODIFY QUERY on view and SELECT on the tables and views in the modified query and check the user is able to modify the view query if and only if they have SELECT privilege on all of them. """ view0_name = f"view0...
67,098
def ASSERT_NOT_REACHED(msg: str) -> None: """Raises an AssertionError with the given message :^)""" assert False, msg
67,099