content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def localize_gaspari_cohn(dist,c): """ Gaspari-Cohn correlation function Arguments: - z: Points to be evaluated - c: Cutoff value """ # Initialize localization array localization=np.zeros(dist.shape) # Mask for mid-distance points mid_mask=(dist<=2*c) # c for mid-dist...
a817962324e53beb411c4f05cd263a6970dda873
3,634,943
def download_spectra(table, data_dir, save_raw=True, raw_dir=None): """ Downloads SDSS spectra Parameters ---------- table : AstroPy.Table Table with coordinates data_dir : str Specifies directory where the data is saved save_raw : bool Specifies whether the raw spec...
ef4cfc10f84fc3489ed5e129fa7e642bfd52e779
3,634,944
def serialize_gs_channel(gs_channel, exclude_fields=None): """JSON serializer Serializes the given groundstation channel. :param gs_channel: The Ground Station channel object to be serialized :param exclude_fields: List of fields to be excluded from the object :return: JSON serialization """ ...
a57dc6b67939e23b853f60e847ed9a4aac27338d
3,634,945
def get_is_valid_node_name(name): """get_is_valid_node_name(std::string name) -> bool""" return _RMF.get_is_valid_node_name(name)
0dda27e75692c876888b3c72135664d82dccbbdf
3,634,946
def split_multi_expr_clause(s): """ Transforms "abc, (123 + 1) * 2, f(a,b)" into ["abc", "(123 + 1) * 2", "f(a,b)"] """ sin = list(s) sep = [-1] rb = 0 # () cb = 0 # {} sb = 0 # [] for i in range(len(sin)): c = sin[i] if c == "(": rb = rb + 1 ...
d0adb1334715afa63f7ad453492ab2ef524046c0
3,634,947
def setRCmatrix(m, p): """Random generate matrix ids to set zeros. Parameters ---------- m : integer Number of rows/columns of square matrix p : float (0. < p < 1.0) percent of entries in matrix that set to zero. Returns ------- rowsZeros, columnsZeros : Tuple Rows and columns id of matrix that w...
aa56003f7b916cd9fcffb3db71c0bcc4cf6f8f55
3,634,949
def sections(parsed): """Calculates number of every type of section""" num_small_sections = 0 num_medium_sections = 0 num_big_sections = 0 for fence in parsed.fences: if not fence.isRemoval: num_big_sections += (fence.length/12) // 8 if (fence.length/12) % 8 < 6 and (...
67bf9328af627234d7dd2fc4bf6dfb11911f9985
3,634,950
def idn(sp): """ Identity channel sp -> sp on space sp; it does nothing """ return Channel(np.eye(_prod(sp.shape)), sp, sp)
d74c6a413e89604dae70244d746018c0ebf749c8
3,634,951
def permutation_test(x1, x2, times=1000, sides=2, metrics="mean", seed=None): """ Permutation test: whether group x1 has equal [mean|median] as group x2 Parameters ---------- x1: array or list of int/float samples for variable x1 x2: array or list of int/float samples for variab...
2faada99276d65bbf92beabd7ef54fa475731efd
3,634,952
from pathlib import Path def build_tourism(image_set, args): """ image_set: whether to return train, val or test dataset """ all_imagepaths = sorted(Path(args.image_folder).glob("*.jpg")) all_poses = np.load(args.c2w_path) all_kinvs = np.load(args.kinv_path) all_bounds = np.load(args.bound...
186568140fb52ddc39d428f0abb748e87470b5af
3,634,953
def find_package(app_name, version, revision): """Check for a specific package version""" # NOTE: Originally this method also used 'pkg_type' (the 'builder' # column in the 'packages' table) to filter; this may need to be # re-added at some point. pkg_def = find_package_definition(app_name) i...
1d0865aa055640d541a4ce6cdcb78fa66a30785f
3,634,954
from typing import List def _group_by_internal_name(ports: List[WrapperPort]): """Group ports by their 'internal_name' attribute return a list of (internal_name, group) where group is a list of ports """ ports.sort(key=lambda x: x.internal_name) instances = [(name, list(group)) for name, group ...
112929ccaac00d6b6fdb6ae912c3ad37ed2d8470
3,634,955
def homography_warp(patch, dst_H_src, dsize, points=None, padding_mode='zeros'): """ .. note:: Functional API for :class:`torgeometry.HomographyWarper` Warps patches by homographies. Args: patch (Tensor): The image or tensor to warp. Should be from source. dst_homo_...
2a984b0900ecba6e0754312d59e371e4dafc3b67
3,634,956
def html2text(value): """ Uses html2text to convert HTML to text... """ return _html2text.html2text(value)
94d630eafc5433c702805e4dcdf189b6cbe8e318
3,634,957
from datetime import datetime import pytz def generate_setup(): """Used to initially populate the database with sample data""" user1 = User(username="user", password=pbkdf2_sha256.hash("pass")) user2 = User(username="user2", password=pbkdf2_sha256.hash("pass")) user3 = User(username="user3", password=...
5b8e5b405fde7c00e14a9f39a028b9cf59bdb036
3,634,959
def GPS_VO_Merge_plot(T_v_dict, utm_dict): """ Plot the VO and GPS trajectories. The GPS trajectory is rotated and translated to the origin in order to obtain a visual comparison between both trajectories.""" k = T_v_dict.keys() + utm_dict.keys() k = [i for i in unique_everseen([i for i in k...
5ee5425745219255d76c01aeb4a09384ac001642
3,634,960
import json def serialize_payload(payload): """Serialize a payload to a JSON string.""" return json.dumps(payload, default=_pack)
8b9392259532cb2e18bec201d9f4258a08ee26e7
3,634,961
def is_power(num, return_decomposition=False): """ Check if num is a perfect power in O(n^3) time, n=ceil(logN) """ b = 2 while (2 ** b) <= num: a = 1 c = num while (c - a) >= 2: m = int((a + c) / 2) if (m ** b) < (num + 1): p = int(m ...
f12a3d5559e68eb72d8a920ee1e3fdfb9c813d3f
3,634,963
import ray from ray import tune from datetime import datetime import pytz def train_rllib(submodule, flags): """Train policies using the PPO algorithm in RLlib.""" class Args: def __init__(self): self.horizon = 400 self.algo = 'PPO' self.randomize_vehicles = Tr...
7fce6f77d2a31b372be64c576f48dd9fb5e3430a
3,634,964
import re def validate_bucket_name(bucket_name): """ Validate bucket name Bucket name must be compatible with DNS name (RFC 1123): - Less than 63 characters - Valid character set [a-z0-9-] - Can not begin and end with "-" Returns Trues if valid, False otherwise """ if len(...
1d759408d097143b93b0af172bf8e73fe02e283a
3,634,965
def format_gro_box(box): """ Print a line corresponding to the box vector in accordance with .gro file format @param[in] box Box NamedTuple """ if box.alpha == 90.0 and box.beta == 90.0 and box.gamma == 90.0: return ' '.join(["% 13.9f" % (i/10) for i in [box.a, box.b, box.c]]) else: ...
61fd32e7bc9eb9a81b8276afd3e35eb1b32150a5
3,634,966
def bot_has_permissions(**perms: bool) -> AC: """Similar to :func:`.has_permissions` except checks if the bot itself has the permissions listed. This check raises a special exception, :exc:`.ApplicationBotMissingPermissions` that is inherited from :exc:`.ApplicationCheckFailure`. If this check is ...
8cc393bc5599f6234ea2cad3d316f09b1f725cb9
3,634,967
def get_ilsvrc_xception_trainner(config_file_path='./config/ilsvrc_2012_xception.yaml'): """ :param config_file_path: :return: """ cfg = config_utils.get_config(config_file_path=config_file_path) return base_trainner.BaseClsTrainner(cfg=cfg)
f12e83c5bf8e9a82d126ab01c0c4a15f95d6f295
3,634,968
def get_bpag(model: pd.DataFrame) -> tuple: """Calculate test statistics for heteroscedasticity Parameters ---------- model : OLS Model Model containing residual values. Returns ------- Test results from the Breusch-Pagan Test """ lm_stat, p_value, f_stat, fp_value = het_b...
c371d663365e9b18b383e86bd4502a81a063438b
3,634,969
def name2link(name: str): """Used for hyperlink anchors""" if not isinstance(name, str): name = str(name) return "-".join([s.lower() for s in name.split(" ")])
357496a291dcb16a86f830551350ff77ca9de81c
3,634,970
def window_rolling(origin_data, window_size): """Rolling data over 0-dim. :param origin_data: ndarray of [n_records, ...] :param window_size: window_size :return: [n_records - window_size + 1, window_size, ...] """ n_records = len(origin_data) if n_records < window_size: return None ...
e5a8e30272098ea01ce939d21b245e7fc4a21018
3,634,971
def get_neighbors(grid, structure_num, proximity): """ Given a grid of structures, returns the closest proximity neighbors to the given structure params: - Grid: 2D numpy array - structure_num: int - proximity: int :returns - A list of neighboring structures to the ...
4f62fb8f01beaeea32b8ae0b496e4e972e4cc74b
3,634,972
import re def vgg19_bn(pretrained=False, **kwargs): """VGG 19-layer model (configuration 'E') with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['E'], batc...
17427df13b43f456bfb7cce1d4e2be94c2673b85
3,634,973
def init_ss_model() -> SentenceTransformer: """Load RoBERTa-base model.""" return SentenceTransformer( "usc-isi/sbert-roberta-large-anli-mnli-snli", cache_folder=str(PRETRAINED_MODEL_DIR) )
1cbc11b0def3a81edbd06d8297964f9360713243
3,634,974
def flatten_dic(dic): """ Flatten dictionnary with nested keys into a single level : usable in a dataframe Args: dic -- a dictionnary Returns: out -- the flatenned dictionnary (df(out) is a Series) """ out = {} def flatten(x, name=""): """ Rec...
60f7caa27a2cf909ad426336bda06fcd2da127f6
3,634,975
def policy_eval(policy, env, discount_factor=1.0, epsilon=0.00001): """ Evaluate a policy given an environment and a full description of the environment's dynamics. Args: policy: [S, A] shaped matrix representing the policy. env: OpenAI env. env.P represents the transition probabilities...
ce36895abdb0e176f8f3af9b3a72501479cbec3a
3,634,976
def split_data_target(element, device, logger=None): """Split elements in dataloader according to pre-defined rules.""" if not (isinstance(element, list) or isinstance(element, tuple)): msg = ( "Invalid dataloader, please check if the input dataloder is valid." ) if logger: ...
2aa0a5c4d80aae2dc237ba9f87c11a7fc7e206fd
3,634,977
from typing import List def get_dataset_access_list(dataset: str, access_type: str) -> List[str]: """Get the comma-separated list of members of a dataset's {access_type} group.""" deploy_config = get_deploy_config() membership_key = f"{dataset}-{access_type}-members-cache" group_membership = deploy_co...
3081952eedff20393dca3e56290cbb65cdd8230a
3,634,978
from typing import List def deploy_whitelist_to_constraints( deploy_whitelist: DeployWhitelist, ) -> List[Constraint]: """Converts a whitelist of locations into marathon appropriate constraints https://mesosphere.github.io/marathon/docs/constraints.html#like-operator :param deploy_whitelist: List of...
f20bd167b938ada0e4cee0c613c07f3d59c72063
3,634,979
def coerce_types(T1, T2): """Coerce types T1 and T2 to a common type. Coercion is performed according to this table, where "N/A" means that a TypeError exception is raised. +----------+-----------+-----------+-----------+----------+ | | int | Fraction | Decimal | float | +...
7d412df0182ca6e1f43bfc6ce8e7c6ce1a738bed
3,634,980
def read_vecstim_protocol(protocol_name, protocol_definition, recordings, syn_locs): """Read Vecstim protocol from definitions. Args: protocol_name (str): name of the protocol protocol_definition (dict): dict containing the protocol data recordings (bluepyopt.ephys.recordings.CompRecord...
05f23ac1e3c903796799cb088f83b9f0194d30ed
3,634,981
from typing import Tuple def get_pair_elements(pair: str) -> Tuple[str, str, str]: """ Get a currency pair's base, quote, and trade base pair. Eg. If the global trade base is 'USDT' and the pair is 'BTC-ETH', returns ('BTC', 'ETH', 'USDT-BTC'). Arguments: pair: The currency pair eg. 'BTC-E...
abc838c50aaadd93d56b5bd3717aafaca4158ef2
3,634,982
from . import extensions from . import modules def create_app(**kwargs): """ Entry point to the Flask RESTful Server application. """ # Initialize the Flas-App app: Flask = Flask(__name__, **kwargs) # Load the config file app.config.from_object('config.DevelopmentConfig') # Initiali...
790c82eed799ebe8347e4cb6d9732604a22cd817
3,634,983
def dy4(vector, g, m1, m2, L1, L2): """ Abbreviations M = m0 + m1 S = sin(y1 - y2) C = cos(y1 - y2) s1 = sin(y1) s2 = sin(y2) Equation y4' = g*M*[s2 - s1*C] - S*[M * L1 * y3^2 + C * m2 * L2 * y4^2] ------------------------------------------------------------- ...
680b253ced9c1faafb357eef83450d262391c885
3,634,985
from typing import OrderedDict def sort_dict(od, d): """Sort parameters (same order as xsd:sequence)""" if isinstance(od, dict): ret = OrderedDict() for k in od.keys(): v = d.get(k) # don't append null tags! if v is not None: if isinstance(v,...
6211a98d30e29ac9b5d0dcaeeec3ef76e9c95713
3,634,986
def port_number(worker_id): """A fixture that returns a different port for each parallel worker.""" i = 0 if worker_id != "master": i = int("".join([c for c in worker_id if c.isdigit()])) return PORTS[i]
8bf4e5936d5e2f83a0ca2bf973dfd24d0af1f950
3,634,988
def get_loss_f(**kwargs_parse): """Return the loss function given the argparse arguments.""" return Loss(lamlSum=kwargs_parse["lamlSum"], lamhSum=kwargs_parse["lamhSum"], lamL2norm=kwargs_parse["lamL2norm"], lamCMF=kwargs_parse["lamCMF"], lamConv=k...
03db5b8934ae9263bf3f0668f97d77c124bf58fb
3,634,989
def assert_greater_equal_v2(x, y, message=None, summarize=None, name=None): """Assert the condition `x >= y` holds element-wise. This Op checks that `x[i] >= y[i]` holds for every pair of (possibly broadcast) elements of `x` and `y`. If both `x` and `y` are empty, this is trivially satisfied. If `x` is not ...
bc0ef67602cd0be4e6868971f821eacd48f5fb72
3,634,990
import itertools def pad_ends( sequence, pad_left=True, left_pad_symbol="<s>", right_pad_symbol="</s>" ): """ Pad sentence ends with start- and end-of-sentence tokens In speech recognition, it is important to predict the end of sentence and use the start of sentence to condition predictions. Typi...
e4a341d1e777adab36ec0c0e7996e23203c53478
3,634,991
def client(): """ Create a client with authentication settings. """ cfg = get_config() url = f"ldap://{cfg['SERVER']['hostname']}:{cfg['SERVER']['port']}" client = LDAPClient(url) client.set_credentials( "SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"] ) ...
911f56339f1b995d9addf0466f01dd6f6bf6ff4e
3,634,992
def _check_and_fire_deploy(job): """ Validates pre-conditions for deploy (hook status returned successfully) and triggers deploy for enabled deployers. :param job: Dictionary containing job parameters :return: job or AsyncResult """ # Check and fires deploy job_id = job['meta-info']['jo...
cc38e88c8e2e43878eb9ce4bfe722c0018931320
3,634,993
def mark_errors_flipping(events): """ Marks error fractions """ single_errors = np.zeros(len(events) - 1) double_errors = np.zeros(len(events) - 2) for i in range(len(events) - 1): # A single error is associated with a qubit error if events[i] == events[i + 1]: singl...
14e71e1e6947bca4382fd22c0ae714e359174476
3,634,994
import numpy def split_with_minimum_rt_distance(rts, min_rt_delta=0, random_state=None): """ Sample from a set ot retention times, so that the sampled rts have a minimum rt differences. :param rts: :param min_rt_delta: :param random_state: :return: """ # if min_rt_delta == 0: ...
026adc9b8dc7f3be513a93275fb0ef0d4b7de615
3,634,995
from django.apps import apps def create_proxy_model(name, model_mixins, base_model, attrs=None, module=None): """ Create a Django Proxy Model on the fly, to be used by any Cascade Plugin. """ class Meta: proxy = True app_label = 'cmsplugin_cascade' name = str(name + 'Model') ...
ff0b8216ff83ced0cd46da1adc237614fc9e6d85
3,634,996
from django.apps import apps def get_embed_video_model(): """ Get the embed video model from the ``WAGTAILEMBEDVIDEOS_EMBEDVIDEO_MODEL`` setting. Useful for developers making Wagtail plugins that need the embed video model. Defaults to the standard :class:`~wagtail_embed_videos.models.EmbedVideo` mode...
d691a0d14f209297338c2eb3e9542c5d5c5a9d61
3,634,997
def get_filetypes(key='type'): """Gets the list of possible filetypes from the filetype table Parameters ---------- key : {'type', 'filetype_id'}, optional Defaults to "type". Determines the format of the returned dict. Returns ------- dict If `key` is "type", dict is of th...
0915680135b9460be44bbf3d127ca248637ff96b
3,634,998
def make_dataloader(folder_names, data_path, batch_size, task, isTrain = False): """This function takes in a list of folders with images in them, the root directory of these images, and a batchsize and turns them into a dataloader""" # added flag isTrain - only augment/transform training set, not validation...
1e73d30481aeca43f81a656799377fe5852e9e67
3,634,999
def calc_overlap(row): """ Calculates the overlap between prediction and ground truth and overlap percentages used for determining true positives. """ set_pred = set(row.predictionstring_pred.split(' ')) set_gt = set(row.predictionstring_gt.split(' ')) # Length of each and intersection ...
98e65250f82ab13b23de049fd80a59dea30ccce2
3,635,000
def delete_all(): """ Clear the config list """ def check_path(folder=None): """ Check if the folder exist and return boolean """ return isdir(folder._fullpath) # Clear the config list: kill_list = [elem for elem in config['Elements'] if elem._hide == 0 or check_path(elem) == 0] if...
a4c1359ee272a3f5fd7edd58913baf90ad15bd84
3,635,001
def get_range(l_list,l_position): """ Obtaining range of points in list (optionally at position inside of list)""" l_range = 0 l_abs_range = 0 l_max = 0 l_min = 0 ll_list = [] counter = 0 if l_position == None: ll_list = l_list else: while counter < len(l_list)...
a98b1d12cd37545b5cb1932cfe273222d9c5e4c0
3,635,002
def equalise_paragraphs(a_para, b_para, sentence_ratio=DEFAULT_SENTENCE_RATIO, lowercase_glued=DEFAULT_LOWERCASE_GLUED, stop_chars=DEFAULT_STOP_CHARS): """ Glues together two collections of sentences so that they're of similar word-length. Discards sentences it cannot make parallel. ...
c77a0c066dc0e7a6fad978563d2eb7caad15825a
3,635,003
def build_summary_rendering_context(schema_json, answer_store, metadata): """ Build questionnaire summary context containing metadata and content from the answers of the questionnaire :param schema_json: schema of the current questionnaire :param answer_store: all of the answers to the questionnaire ...
b59b6ffb10a7383d7168b127bf8931f16ca7dc5a
3,635,004
def _bucket_from_workspace_name(wname): """Try to assert the bucket name from the workspace name. E.g. it will answer www.bazel.build if the workspace name is build_bazel_www. Args: wname: workspace name Returns: the guessed name of the bucket for this workspace. """ revlist = [...
4cf3f4505a894f63258846abbe41b3b787485d40
3,635,005
def load_results_with_table_definition( result_files, table_definition, table_definition_file, options ): """ Load results from given files with column definitions taken from a table-definition file. @return: a list of RunSetResult objects """ columns = extract_columns_from_table_definition_file...
4bbe743774b74abbe8c9d4d6af6669cd819c9cba
3,635,006
def CIFAR10(flatten=True, split=[1.0, 0.0, 0.0]): """Returns the CIFAR10 dataset. Parameters ---------- flatten : bool, optional Convert the 3 x 32 x 32 pixels to a single vector split : list, optional Description Returns ------- cifar : Dataset Description ...
8af9997f5c530ac2aae9d680235007b3de289d96
3,635,007
def _cut_daytime(visi, tmstp): """Returns visibilities with night time only. Returns an array if a single night is present. Returns a list of arrays if multiple nights are present. """ tstp = tmstp[1] - tmstp[0] # Get time step risings = ch_eph.solar_rising(tmstp[0], tmstp[-1]) settings =...
f6a3164af732949807f5f3f8c810f5072ab19a6d
3,635,008
def decay(epoch): """ This method create the alpha""" # returning a very small constant learning rate return 0.001 / (1 + 1 * 30)
b3311fe38557ee18d0e72ce794a3123b04b92c7a
3,635,009
import functools import time def timer_function(function): """Print time taken to execute a function""" @functools.wraps(function) def inner_function(name): start = time.perf_counter() function(name) end = time.perf_counter() total = end-start print(start, end) ...
82981c28e9401581d38c1eed6b4efab30679cec8
3,635,010
def blob_delete(cache, key, namespace): # type: (Any, str, Optional[str]) -> bool """Delete stored values from memcache""" chunk_keys = blob_get_chunk_keys(cache, key, namespace=namespace) if not chunk_keys: # Keys are not set, no need to remove them. return True keys_to_delete = list(chunk_keys) ...
d2eaa38ead9e89461341c4a5df7062d723f5e62e
3,635,011
def shape_equality_robust_statistic(𝐗, args): """ GLRT test for testing a change in the shape of a deterministic SIRV model. Inputs: * 𝐗 = a (p, N, T) numpy array with: * p = dimension of vectors * N = number of Samples at each date * T ...
c5f9f967e9f9bdbf314dde3d90dbe812b7dad565
3,635,012
def get_attrib_uri(json_dict, attrib): """ Get the URI for an attribute. """ url = None if type(json_dict[attrib]) == str: url = json_dict[attrib] elif type(json_dict[attrib]) == dict: if json_dict[attrib].get('id', False): url = json_dict[attrib]['id'] elif json...
838b698e3475ebdc877b29de6f3fd446d2be1cdf
3,635,013
def set_model_params(module, params_list, start_param_idx=0): """ Set params list into model recursively """ param_idx = start_param_idx for name, param in module._parameters.items(): module._parameters[name] = params_list[param_idx] param_idx += 1 for name, child in module._module...
7ce6edb0c1b83020280cf0b586623d66839b4b0a
3,635,014
def concatIDF(idfObjectList, param): """Create tab separated strings from input yaml parameter objects""" outString = "" for obj in idfObjectList: outString += "\t" + str(noneClean(obj.params[param])) return outString
0cd6fe6dea85b2d7365a1e225d75386629dab98e
3,635,016
import inspect def super_class_property(*args, **kwargs): """ A class decorator that adds the class' name in lowercase as a property of it's superclass with a value constructed using the subclass' constructor with the given arguments. So for example: class A: pass @super_class_property(foo=5) ...
ecfd38ba3d7ea96266278ed6be6cf0ba87263d7d
3,635,017
def get_group_type_by_name(context, name): """Retrieves single group type by name.""" if name is None: msg = _("name cannot be None") raise exception.InvalidGroupType(reason=msg) return db.group_type_get_by_name(context, name)
ceff65a621fece573cec1ff60291b80bdd784bb7
3,635,019
def register_tortoise_exception( app: FastAPI, add_exception_handlers: bool = False, ) -> None: """ rewrite from tortoise.contrib.fastapi import register_tortoise """ if add_exception_handlers: @app.exception_handler(DoesNotExist) async def doesnotexist_exception_handler(requ...
e9c140f61b32475cd2a396fb709aba1b578cf6bf
3,635,021
def user_from_dict(user_dictionary: dict): """ The function converts a dictionary of User to a User object. :param user_dict: A dictionary that contains the keys of a User. :type user_dict: dict :rtype: ibmpairs.query.User :raises Exception: if not a dict....
fb2380d316a3c939afd9b6a7d6399ad198c881c7
3,635,023
def lind_safe_fs_getdents(args): """ Safely wrap the getdents call. See dispatcher.repy for details. Check the handle and count for consistancy, then call the real getdents dispatcher. """ handle = args[0] count = args[1] check_valid_fd_handle(handle) assert isinstance(count, int...
4ec1b3ba52f0d24ebafc03829b4b520a93f460ee
3,635,024
from datetime import datetime def parser(): # parsing the whole circuit into lists of objects """ Start of Parse .nodes """ file = open("{}.nodes".format(fileName)) lines = file.readlines() saved = 0 node_list = [] # List of all nodes for the current circuit #...
98e828248ec02ecd68928165791d549b04962992
3,635,025
def header(columns): """Create html for column headers.""" cells = add_bars(columns) return div(docfilter, div(*cells, cls='noselect'), id='header')
1d54b6f60085e0234aa7055c9ef17d684793b6d4
3,635,026
def set_playbook_config(ctx, **kwargs): """ Set all playbook node instance configuration as runtime properties :param _ctx: Cloudify node instance which is instance of CloudifyContext :param config: Playbook node configurations """ def _get_secure_values(data, sensitive_keys, parent_hide=False):...
241642acdcd3b3b37c4b3736b375a03e5bc4cbec
3,635,027
def get_services_accounting_flow(device, field, output=None): """ Get value of field from show services accounting flow Args: device (`obj`): Device object field (`str`): field name in show output output (`str`): output of show services accounting flow Returns: ...
d2cc47826073d47a163edc9e12079705563baac1
3,635,028
import math def moving_window_stride(array, window, step): """ Returns view of strided array for moving window calculation with given window size and step :param array: numpy.ndarray - input array :param window: int - window size :param step: int - step lenght :return: strided: numpy.ndarray -...
50217f9830864375f801ef5412c99756fb9982ac
3,635,029
def ecef2geodetic(ecef, radians=False): """ Convert ECEF coordinates to geodetic using ferrari's method """ # Save shape and export column ecef = np.atleast_1d(ecef) input_shape = ecef.shape ecef = np.atleast_2d(ecef) x, y, z = ecef[:, 0], ecef[:, 1], ecef[:, 2] ratio = 1.0 if radians else (180.0 / n...
a4ef47c2f7284066e2d97b744dd144d75ccff768
3,635,031
def merge(sorted1, sorted2): """Merge two sorted lists into a single sorted list.""" if sorted1 == (): return sorted2 elif sorted2 == (): return sorted1 else: h1, t1 = sorted1 h2, t2 = sorted2 if h1 <= h2: return (h1, merge(t1, sorted2)) else: ...
7c02b345b3d1e7c67e363e1535c608575a313f75
3,635,032
from dask import delayed, compute from dask.bytes.core import open_files, read_bytes from dask.dataframe import from_delayed import copy def dask_read_avro(urlpath, blocksize=100000000, storage_options=None): """Read set of avro files into dask dataframes Use this only with avro schema that make sense as tab...
a6559fbdc7a90149984f51f6d632663b36b5106e
3,635,035
import csv def msgs_csv(messages, header): """Return messages in .csv format.""" queue = cStringIO.StringIO() writer = csv.writer(queue, dialect=csv.excel, quoting=csv.QUOTE_ALL) if header: writer.writerow(['Date', 'From', 'To', 'Text']) for m in messages: writer.writerow([m['date'...
f7397af4f19cd7b94bd6d56766608c607dbe6950
3,635,036
def alpha_s_plot_parameters( alpha_curve: "list[float]", loading: "list[float]", section: "list[float]", alpha_s_point: float, reference_area: float, molar_mass: float, liquid_density: float, ): """Get the parameters for the linear region of the alpha-s plot.""" slope, intercept, co...
a06a65ec2f7e13535ac96855f2ddb8b985268d26
3,635,037
def _MutualInformationTransformAccumulate(pcol): # pylint: disable=invalid-name """Accumulates information needed for mutual information computation.""" return (pcol | 'VocabCountPerLabelPerTokenAccumulate' >> beam.CombinePerKey( _CountAndWeightsMeansCombineFn()))
e3fb8c16dc025f8cb7ef4f0196d2b9341cbc0855
3,635,038
import torch def GTLRU(input_a, input_b, n_channels: int): """Gated[?] Tanh Leaky ReLU Unit (GTLRU)""" in_act = input_a+input_b t_act = torch.tanh(in_act[:, :n_channels, :]) r_act = torch.nn.functional.leaky_relu(in_act[:, n_channels:, :], negative_slope=0.01, inplace=True) acts = t_act * r_act ...
62f36cda5329e3b1889abcab2f1c97d6d1448ea8
3,635,039
def get_items_by_category(category_id, limit, offset=None): """ Return items from catalog by category with limit and offset :param category_id: :param limit: :param offset: :return object: """ return session.query(Catalog).filter_by( category=category_id).offset(offset).limit(li...
63e82b3f67cf2ff8e5a863dfe05d7a4acb3e5543
3,635,040
def cosine(u, v, w=None): """ Compute the Cosine distance between 1-D arrays. The Cosine distance between `u` and `v`, is defined as .. math:: 1 - \\frac{u \\cdot v} {||u||_2 ||v||_2}. where :math:`u \\cdot v` is the dot product of :math:`u` and :math:`v`. Para...
ad655f35963e64301686f9df440c59886984335b
3,635,041
import json def adjust_site_parameters(site): """Updates extra parameters with applicable datastreams from `arm_reference_sites.json` Parameters ---------- site: dict Returns ------- dict Copy of input with updated extra parameters. """ with open(DEFAULT_SITEFILE) as ...
f58d10f69c95f4f3db5ef71f772e97cb4c08e8a2
3,635,042
def slice_repr(slice_obj): """ Get the best guess of a minimal representation of a slice, as it would be created by indexing. """ slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step] if slice_items[-1] is None: slice_items.pop() if slice_items[-1] is None: if slice...
c894f66478ec830a4968d0cfc5d9e146457012b6
3,635,043
async def isAtLeastInstructor(context: commands.Context) -> bool: """ Returns true if context.author is either an admin or an instructor and False otherwise :param context: :return: """ return await isInstructor(context) or await isAdmin(context)
074d3726e42288ccfc3c6f5674679bd5e3510d2a
3,635,044
def pad_sequences(sequences, pad_symbol, max_length=None, mask_present_symbol=None, padding_mode='both'): """ Pads a collection of sequences. Will work only for two dimensional data. :param sequences: list or np array, which has sequences (lists or np arrays) that ...
6ccdc43b63e04526a8376c878493323075f14808
3,635,046
from typing import Sequence from typing import Tuple def cast_cal_range(cal_range: Sequence[raw_mz_type]) -> Tuple[float, float]: """ :param cal_range: """ min_val, max_val = cal_range return float(min_val), float(max_val)
22bfb7461209e4a31d871aa2237a1add190abaaf
3,635,047
def request_get(url): """ Realisa una solicitud 'GET' en la url proporcinada, si se realiza con exito retorna el contenido y se ocurre algun error retorna 'None' Parametro 'url' direccion del sitio web return: 'requests.get.content' """ try: with closing(get(url, stream=True)) as ...
e13de348651c9254c1b17fa26c49faa420a670f9
3,635,049
def make_tensor(tensor): """ 转换numpy数组到potobuf格式 """ shape = projector_pb2.Tensor.TensorShape(dim=[projector_pb2.Tensor.TensorShape.Dim(size=d) for d in tensor.shape]) return projector_pb2.Tensor(dtype=str(tensor.dtype), tens...
9bfe06f21f5286b1604f3dde13d8740dc1c5a5df
3,635,051
def pad(sequences, max_length, pad_value=0): """Pads a list of sequences. Args: sequences: A list of sequences to be padded. max_length: The length to pad to. pad_value: The value used for padding. Returns: A list of padded sequences. """ out = [] for sequence in ...
68d0a8a19352e3e724ef012a396b51c28005ff02
3,635,052
def dict_blocks_decoder(nB, v, step, lookup: dict, dec_fmt: str): """ Decodes a single block from a NORB pooling design """ ds = Design() dm = ds.matrix decoder = DictBlockDecoder(dm, lookup, format=dec_fmt) res = [] for b in range(nB): p = v.squeeze()[step*b:step*b + step] ...
10297e9b09919cca73962cfca54f4b6de7738f30
3,635,053
def _build_circuit_layers_and_connectivity_nearest_neighbors(n_qubits): """Function to generate circuit layers for processors with nearest-neighbor connectivity Args: n_qubits (int): number of qubits in the qubit array Returns: (zquantum.core.circuit.CircuitConnectivity, zquantum.core.ci...
62e0a9b5f1ca9e6ddb5713ee8389126983d44793
3,635,054
def band_colormap( cmap, nband=10 ): """ -> a colormap with e.g. 10 bands """ cmap = get_cmap( cmap ) h = .5 / nband A = cmap( np.linspace( h, 1 - h, nband )) name = "%s-band-%d" % (cmap.name, nband) return array_cmap( A, name, n=nband )
dca6fa0afcefc25e288f8eb24599554286de7c05
3,635,055
def rolling_optimal_combo_stats(ret1, ret2, window_len, window_step, nsteps=20, period='monthly', rebal_period=3, downside_vol=True): """Find the optimal (volatility-minimizing) combination of two return series over a rolling window. Args: - ret1: a sequence of period return...
4796faf706fc8ce49588e64ffcf98222432ff031
3,635,056
def forward_backward_prop(data, labels, params, dimensions): """ Forward and backward propagation for a two-layer sigmoidal network Compute the forward propagation and for the cross entropy cost, and backward propagation for the gradients for all parameters. Arguments: data -- M x Dx matrix, w...
c3a774117aced21c117f2dea53f1b1891f7562db
3,635,057