content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import ast def run_averecmd(ssh_client, node_ip, password, method, user='admin', args='', timeout=60): """Run averecmd on the vFXT controller connected via ssh_client.""" cmd = "averecmd --raw --no-check-certificate " + \ "--user {0} --password '{1}' --server {2} {3} {4}".format( ...
bc2fa37ed3197d1015bf48c026778486d6d355dd
3,622,439
def create_bout_ds_list( prefix, lengths=(6, 2, 4, 7), nxpe=4, nype=2, nt=1, guards={}, topology="core", syn_data_type="random", squashed=False, bout_v5=False, metric_3D=False, ): """ Mocks up a set of BOUT-like datasets. Structured as though they were produced b...
f24c93eb1e7c3910aeb824694aeea20305eed0a1
3,622,440
def parse_mapping_file(fp): """ """ ensp_to_hgnc = {} with open(fp, "r") as fh: for line in fh: line = line.rstrip() words = line.split() if(len(words) >= 4): ensp_to_hgnc[words[3]] = words[0] return ensp_to_hgnc
e3c47d9a73cf19eddd9efc8b4fb7840f5bda156b
3,622,441
def sort_group(indx, column1, column2): """ Parameters ---------- indx : integer column1 : list data type (contains strings of SOC NAMES / WORK STATES which need to be ordered.) column2 : list data type (contains integers which denote numbers of of certified applications.) Returns ------- sort_group : l...
6bc153d78be6c40a1c3b7324784f45fb9f01fbd4
3,622,442
import logging def rate_limit(auth, limit, period): """Rate limit main function""" if rate_request(auth, limit, timedelta(seconds=period)): raise exception.too_many_rquests() logging.info('✅ Request is allowed') return True
777fdbd8bf2e39e6c546aa52d2e17bb81320519d
3,622,443
def unflag_output_id(output_id: str) -> bool: """Sets the flag property of an IOPointer to false.""" store = Store(_db_uri) return store.set_io_pointer_flag(output_id, False)
9a9e7071335e5fc52e8b0aa51d78691e56f3f49c
3,622,444
def get_indicator_representation(row): """Convert binary indicator to list of assigned labels Parameters: ----------- row : List[{0,1}] binary indicator list whether i-th label is assigned or not Returns ------- np.array[int] list of assigned labels """ return np.w...
07a1fc42f748bc5ca964ed93db57d6a93112b764
3,622,446
def Uniform(*opts): """Uniform distribution over a finite list of options. Implemented as an instance of :obj:`Options` when the set of options is known statically, and an instance of `UniformDistribution` otherwise. """ if any(isinstance(opt, StarredDistribution) for opt in opts): return UniformDistribution(op...
386d2f701254e596f4aa1f50af456b6f31dda6c9
3,622,447
def TWM_p(pfreq, pmag, f0c): """ Two-way mismatch algorithm for f0 detection (by Beauchamp&Maher) [better to use the C version of this function: UF_C.twm] pfreq, pmag: peak frequencies in Hz and magnitudes, f0c: frequencies of f0 candidates returns f0, f0Error: fundamental frequency detected and...
50969163558a53021ea748550bda2fd6c2b167d7
3,622,448
def iter_items(rows): """ """ member_load = {} for row in rows: try: member_load[row[0]].extend(list(row[2:])) except KeyError: member_load[row[0]] = list(row[2:]) return member_load
16ee5bca38a66dd9c2ba8b3428f169d2c624af85
3,622,449
def get_file_name(api_token, data_series_list, initial_date, final_date, api_host=DEFAULT_API_HOST): """Combines region, items, and dates to return a string""" client = GroClient(api_host, api_token) logger = client.get_logger() key_words = [client.lookup('regions', data_series_list[0]...
a08a8f1847f355f425b7c7a77f0b562538f2bec8
3,622,451
def from_transform(msg): """ Convert a `geometry_msgs/Transform` ROS message into a numpy array (4x4 homogeneous transformation). Parameters ---------- msg: geometry_msgs/Transform The ROS message to be converted Returns ------- array: np.array The resulting numpy array...
cbd0c8a8547b2bb2da242fedeedeb9665367d193
3,622,452
def _read_character_at(source, pointer): """Reads a code point or a backslash-u-escaped code point.""" while pointer < len(source) and source[pointer] == " ": pointer += 1 if pointer >= len(source): raise IndexError("pointer %d out of range 0-%d" % (pointer, len(source))) if source[poi...
529c7319f5f90d6df4aba97ba5fc40d526b94dde
3,622,453
def get_list_of_data(filepath, col_name, geoid=None): """Pull a column data from a shape or CSV file. :filepath: The path to where your data is located. :col_name: A list of the columns of data you want to grab. :returns: A list of the data you have specified. """ # Checks if you have inputed ...
b505501f33e2223a5eb983eb59adde2f2314fe34
3,622,454
def waber(lumin, lambdaValue): """ Weber's law nspired by Physhilogy experiment. """ # lambdaValue normally select 0.6 w = lumin**lambdaValue #w = (255*np.clip(w,0,1)).astype('uint8') return(w)
d9c495dd656161a67120f1e15e447021617180ab
3,622,455
def children(nodes): """ Search and list all the nodes childs. :param nodes: a list with tree nodes :return: a list with nodes childs """ child = [] for node in nodes: if node.left: child.append(node.left) if node.right: child.append(node.right) r...
19e60bbdceb60f85ffa9806e5ff61fd00030b368
3,622,457
def process_long_strings(lexicon: lex_or_string) -> lex_or_string: """Process long strings in the main lexicon. Strings marked for concatenation are indicated with a leading pipe. """ if isinstance(lexicon, str): if lexicon.startswith("|"): lexicon = ( # Remove the p...
f3e8f88dec9731c3d192ce54607223759de2bdef
3,622,459
import click def init(): """Admin Cell CLI module""" @click.group( cls=cli.make_commands( __name__ + '.' + context.GLOBAL.get_profile_name() ) ) @click.option( '--cell', required=True, envvar='TREADMILL_CELL', is_eager=True, callback=cli.handle_cont...
de93dc1caaadaa41e912ff0ad10bf45ea47725a3
3,622,461
def tensor_prod(a, b): """ Returns the tensor product using lists """ product = [] # loop through first tensor/vector for a_ in a: row = [] # multiply with each element of second tensor and add to row list for b_ in b: row.append(a_ * b_) # add row lis...
c13ec6e0d3292d1124c567420d2b50b8d3a5501a
3,622,462
from operator import mod def invoke(request): """Where the magic happens...""" transformed_request = _transform_request(request) with monitor(labels=_labels, name="invoke"): data_iter = mx.io.NDArrayIter(transformed_request, None, 1) response = mod.predict(data_iter) return _transform...
fd817fc70e469b1947c6b0f67ab751cd5c088415
3,622,464
def get_location(stmt): """Return the grounded geo-location context associated with a Statement.""" if not has_location(stmt): loc = None else: loc = stmt.context.geo_location.db_refs['GEOID'] return loc
71d53954cc5de55f3eea4844c2bbc8f8d7aacc08
3,622,465
def _convert_version(value): """Extract 3 version numbers from 2 bytes""" # subversion bits 0.3, versin bits 4-7, type bits 8-15 type_ = value // 256 value = value % 256 version = value // 16 subversion = value % 16 return '{}.{}.{}'.format(type_, version, subversion)
2850b4729da445f2ee7007c469aaa91c2370e4dd
3,622,466
def var_gaussian(r, levels=5, modified=False): """ Returns the Parametric Gaussian VaR of a Series or DataFrame If modified is True, then the modified VaR is returned using Cornish-Fisher modifications """ # compute the Z score assuming the distribution is Gaussian z = norm.ppf(levels / 100...
22d7c8e55230beb2a95d031d53b0a49faa5e5b34
3,622,467
import math def taylor_green_vortex(x, y, z): """ Calculates Taylor Green vortex flow velocities. """ A = 0.14 B = A C = -2 * A a = 1 b = 1 c = 1 # Position translated to ensure boundary flow is tangential and continuous. x_p = x + (math.pi / (a * 2)) y_p = y + (math.pi / (a ...
c7810d3c059f0325c9d29ec88fbd4d8a87f1dea5
3,622,468
def breadcrumbs_list(links): """Returns a list of links to render as breadcrumbs inside a <ul> element in a HTML template. ``links`` should be a iterable of tuples (URL, text). """ crumbs = "" li_str = '<li class="breadcrumb-item"><a href="{}">{}</a></li>' li_str_active = '<li class="breadcrumb-...
736f6685cc3f58b50d2e67758c239ab7970cc9f2
3,622,469
def setup(args: Arguments): """ Create configs and perform basic setups. """ cfg = get_cfg() add_config(args, cfg) cfg.merge_from_file(str(args.config_file)) # cfg.merge_from_list(args.opts) cfg.merge_from_list(switch_extract_mode(args.extract_mode)) cfg.merge_from_list(set_min_max_b...
b660209d3bcbf5efc867d4235b4ac581d4ed596d
3,622,470
import glob def get_lists_in_dir(dir_path): """ Function to obtain a list of .jpg files in a directory. Parameters: - dir_path: directory for the training images (from camera output) """ image_list = [] for filename in glob.glob(dir_path + '/*.jpg'): image_list.append(filename...
c59701c5c8327569a5efe68c2751b0568de0498e
3,622,472
from typing import Union def suppress_red_green_blue(error: Union[Red, Green, Blue]) -> bool: """Suppress Red, Green, and Blue exceptions.""" return True
2febf662644c94bea579c3ad12c24429a91b1bb7
3,622,475
def exists(env): """Check if we're okay to load this builder""" return MkdocsCommon.detect(env)
60066ac1da3a0762694505ef89a5eda40ff36871
3,622,476
def walk_links_for_node(node, callback, direction, obj=None): """ Walks the each link from the given node. Raising a StopIteration will terminate the traversal. :type node: treestruct.Node :type callback: (treestruct.Node, treestruct.Node, object) -> () :type direction: int :type obj: Any ...
a92cb831945a537c55ff4c014eedcb17b26ddd96
3,622,477
from openeye import oechem, oedepict from typing import List import copy def _create_openeye_pdf(molecules: List[Molecule], file_name: str, columns: int): """Make the pdf of the molecules using OpenEye.""" itf = oechem.OEInterface() suppress_h = True rows = 10 cols = columns ropts = oedepict...
3ba260ef2899a6ba1b233637be39ec77c807e8f4
3,622,478
def dialog_create_repository(request): """fills the create repository dialog """ # nothing is needed return { 'mode': 'CREATE', 'has_permission': PermissionChecker(request) }
f69590ecff28a6694e07d5ec0bb81bb5f72dcdaf
3,622,480
def external_load_new_pool(request, form_acess, client): """ Method to call shared_load_new_pool when use by external way """ return facade.shared_load_new_pool(request, client, form_acess, external=True)
7d3423bf1f02038cdfc3f7e651ff0cc2658b0640
3,622,481
import configparser def get_config_parser(filepath): """Create parser for config file. :param filepath: Config file path :type filepath: str :return: configparser.ConfigParser instance """ config_parser = configparser.ConfigParser(interpolation=None) # use read_file() instead of read() to...
224f524c60161bc45b1324b26eeb6d4715c43054
3,622,482
def num_concavities(prop, **kwargs): """Return the number of concavities for a cell Args: prop (skimage.measure.regionprops): The property information for a cell returned by regionprops **kwargs: Arbitrary keyword arguments Returns: int: The numb...
f83cc3206b22b0cbfb7dc264cbbb2f051925dd21
3,622,483
def add_street_network_to_city(city_object, name_list, pos_list, edge_list): """ Add street network to city object. Based on street network functions of uesgraphs. Parameters ---------- city_object : object City object of pycity_calc name_list : list List of street node name...
e73723001ccc9709da71efb6191457bbc111e483
3,622,484
def admin_login_req(f): """ 登录装饰器 """ @wraps(f) def decorated_function(*args, **kwargs): if "admin" not in session: return redirect(url_for("admin.login", next=request.url)) return f(*args, **kwargs) return decorated_function
ef25213a2aed99aa0836624cfa426b1898f302cb
3,622,485
def vec2d(x,y): """A vector in 2D vector space""" return jnp.array([x+0.,y])
559ff6a524a05ab74d63508c11e0ae5aab3ebda8
3,622,486
def preview_page_version(request, revision_id): """ Returns GET response for specified page preview. :param request: the request instance. :param reversion_pk: the page revision ID. :rtype: django.http.HttpResponse. """ revision = get_object_or_404(PageRevision, pk=revision_id) if not ...
3d53848c7d7f5d1146f59b0535aa8906d9e116fd
3,622,487
def load_id_map(id_file): """ Load a ids file in to a barcode -> coordinate dictionary. """ id_map = {} with open(id_file, "r") as fh: for line in fh: bc, x, y = line.split("\t") id_map[bc] = (int(x), int(y)) return id_map
cd2c0635496209c3e19597fa45ae4f486779ceac
3,622,488
def map_page(): """ Global strain map shows the locations of all wild isolates within the SQLite database. """ VARS = {'title': "Global Strain Map", 'strain_listing': dump_json(get_strains(known_origin=True))} return render_template('strain/global_strain_map.html', **VARS)
fe7a078c314d78e0c3ac01115482b80a3072fcf6
3,622,489
def database_is_empty_or_contains_kombu_tables(db_url): """ Database is empty or contains 2 tables: kombu_message, kombu_queue. (ref: https://github.com/galaxyproject/galaxy/issues/13689) """ with disposing_engine(db_url) as engine: with engine.connect() as conn: metadata = MetaD...
99c7870aa7e20702fd94fa69edf1458ab1df3740
3,622,490
from datetime import datetime from pathlib import Path import ftplib def download(startend: tuple[datetime, datetime], site: str, odir: Path, host: str = None, wavelen: str = None) -> list[Path]: """ startend: tuple of datetime """ if not host: host = HOST assert len(startend) == 2 s...
ffcb66a704442febfe73803a310e0e8b671723d2
3,622,491
def get_static_mini_dataset() -> Dataset: """Return a collection of 10 documents and their target subjects of 4 different subjects. Returns ------- Dataset the static dataset consisting of 10 documents and 4 subjects """ documents = [ Document(uri="uri://test_document1", title="...
80521e3ceb5a9798ee4abac5b54ae0b6a89f6def
3,622,492
def popular_environment_shared(request, client_api): """ Method to return environment vip list by finality and client Param: finality Param: client """ lists = dict() status_code = None lists['environments'] = '' try: finality = get_param_in_request(request, 'finality') ...
4a8ab75a4565fa05883467385a8234bb2867a25a
3,622,493
def save_name(): """Change a users details, most importantly his name.""" user = request.json store_user(user) return "I'll try to remember your name, {}!".format(user.get("name"))
51c9ab4d37624af49a58413979a6af91014d7738
3,622,494
from typing import Union from typing import Callable from typing import Optional def add_l2_weight_decay(loss_fn: base.LossFn, scale: Union[float, Callable[[hk.Params], hk.Params]], predicate: Optional[PredicateFn] = None) -> base.LossFn: """Adds scale * l2 weight dec...
c8450dad029799d5b8149782001ba5d72a0a36d6
3,622,496
def create_resnet101() -> tf.keras.Model: """Create ResNet101 """ resnet_base = tf.keras.applications.ResNet101( input_shape=(32,32,3), weights='imagenet', pooling='avg', include_top=False) # Downloading data from # https://storage.googleapis.com/tensorflow/keras-app...
e4bebdab84feb2a01c37679e8fd3f0d5daecabd1
3,622,497
def spatial_join_facilities(left, right, lid_property, rid_property, lsimilarity_properties, rsimilarity_properties, similarity_weights=None, ...
d1e9315af0329db22060c3a25b9e1513db121c63
3,622,498
from textwrap import dedent def handle_description(update, context): """Добавление определенного кол-ва товара в корзину""" query = update.callback_query if '/back' == query.data: return start(update, context) purchase_id = str(query.data) purchase_quantity = 1 chat_id = update.eff...
28c9632cf3f6cecf492f97f51b4607f7dc6f5460
3,622,499
from typing import Dict from typing import Any from typing import List def dereference_json_pointer(root: n.SerializableType, ptr: str) -> Dict[str, Any]: """Given a dictionary or list, return the element referred to by the given JSON pointer (RFC-6901).""" cursor = root components = ptr.lstrip("#"...
529f77e5bdfb49d9914a7610e48bc23171e303d0
3,622,500
def port_exponential_moving_average(asset_indicator, close_arr, n): """Calculate the exponential weighted moving average for the given data. :param close_arr: close price of the bar, expect series from cudf :param n: time steps :return: expoential weighted moving average in cu.Series """ EMA = ...
8f4ae8a45312a7bf2c9cd1c5fc394ddf6247c131
3,622,501
import typing import logging def crop_to(arr: np.ndarray, target_shape: typing.Tuple[int]) -> np.ndarray: """ Center-crops an array to a desired shape. If the difference in shapes is not even the offset of the resulting array will be rounded down, i.e. the removed area "in front" will be smaller than the ...
77155fa571517ee59441a0714836076eb5d8f6af
3,622,502
from typing import Set from typing import Mapping from typing import Sequence def expand_related_tasks(tasks: Set[str], expand_map: Mapping[str, Sequence[str]]) -> Set[str]: """The inverse of `collapse_related_tasks`. Args: tasks: a list of tasks to expand. expand_map: map from a...
16abd2160dc972e89ade3e5cb2b40e8451a932a7
3,622,503
import sympy def antal_h_coefficient(index, game_matrix): """ Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2. H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj}) Parameters ---------- index: int game_matrix: sympy.Matrix Ret...
0e05a6a622ef24ff63b18b9c8b80348b860a16c3
3,622,504
import logging def setup_logging( logger_or_name=None, logfile=None, log_to_console=True, level=logging.INFO ): """ Sets up a logger for logging Args: logger_or_name: Either a logging.Logger object or a string used to reference the logger name. If None, root logger is a...
6c2443ca113c6264ce19bd4a9752684053a99cd5
3,622,505
import hashlib def getcertpubhash(certobj): """ Method 1: Hash from public key :param certobj: :return: """ if certobj: pubkey = certobj.get_pubkey().as_der() pubkeyhash = hashlib.sha256(pubkey).hexdigest() return pubkeyhash else: return None
3002a8ddba6522acf7de0c1cfa225e68a1e3f141
3,622,506
def greedy_value_per_weight_unit(I: list, w: list, v: list, K: int) -> tuple: """ Solve knapsack problem with value per weight unit greedness. Takes most beneficial first. Parameters: ----------- - I : items - w : items' weights - v : items' value - K...
fd81de5f066d6918f17effdc0b6c72659fb19391
3,622,507
def _wrap_output_like_matching_units(result, match): """Convert result to be like match with matching units for output wrapper.""" output_xarray = isinstance(match, xr.DataArray) match_units = str(match.metpy.units if output_xarray else getattr(match, 'units', '')) if isinstance(result, xr.DataArray): ...
f902539a216f9c28e42471aacd29fc84d4d45228
3,622,508
import json def get_mnest_results(root_name, parameters): """ Parameters ---------- root_name : str The directory and base name of the MultiNest output. parameters : list or array A list of strings with the parameter names to be displayed. There should be one name for each...
e133b8ad2120fa7940441e89d80fc30c2d7f5e33
3,622,509
from typing import List import random def _get_list_of_test_resources() -> List[Resource]: """The subset of all Resources that can be tested Returns: List[Resource] -- A list of TesTItems """ resources = [ resource for resource in database.RESOURCES if database.resourc...
fe40bbc2f8ccec9a57cbbcee7a327608714b32e5
3,622,510
from typing import Union from typing import List from typing import Optional def convert_units( data: Union[tb.BeliefsSeries, pd.Series, List[Union[int, float]], int, float], from_unit: str, to_unit: str, event_resolution: Optional[timedelta] = None, capacity: Optional[str] = None, ) -> Union[pd.S...
f3a0cb87599c1f86c7995052fb3b42e16c96459b
3,622,512
from datetime import datetime def add_delta_to_time(timestamp, delta): """Utility to add a datetime.timedelta object to a datetime.time one""" return ( datetime.datetime.combine(datetime.date(2012, 1, 1), timestamp) + datetime.timedelta(seconds=delta) ).time()
9971f103afd2c439b36e29db1b167fed80fb66a3
3,622,513
def raDecFromAltAz(alt, az, obs, includeRefraction=True): """ Convert altitude and azimuth to RA and Dec @param [in] alt is the altitude in degrees. Can be a numpy array or a single value. @param [in] az is the azimuth in degrees. Cant be a numpy array or a single value. @param [in] obs is an O...
69567a3ec34f068d56aa48edf0e24e2f5f766acf
3,622,514
def _is_convertible_to_tensor(value): """Returns true if `value` is convertible to a `Tensor`.""" if value is None: return True if isinstance(value, (ops.Tensor, variables.Variable, np.ndarray, int, float, str)): return True elif isinstance(value, (sparse_tensor.SparseTensor,)): retu...
5500eb345cedccffad9c5c58c6499d00f8caa5f2
3,622,515
def add_ball(space, position): """Ajoute une balle dans l'espace à une position donnée""" mass = 1 radius = 14 moment = pymunk.moment_for_circle(mass, 0, radius) body = pymunk.Body(mass, moment) body.position = position shape = pymunk.Circle(body, radius) space.add(body, shape) retur...
cef5333d8a8bcad337fbe0d0a2c03233fa36ced4
3,622,516
def add_to_cart_view(request, **kwargs): """Add a product to the cart""" validator = ValidateCart(data=request.data) validator.is_valid(raise_exception=True) session_id, queryset = validator.save(request) return simple_api_response(build_cart_response(queryset, session_id))
8f79798063df912c300fcf1b9154cb3250baafd3
3,622,517
from typing import List from typing import Dict def _cx_to_dict(list_of_dicts: List[Dict], key_tag: str = "k", value_tag: str = "v") -> Dict: """Convert a CX list of dictionaries to a flat dictionary.""" return {d[key_tag]: d[value_tag] for d in list_of_dicts}
ea80e9a50ea04536c2ed068d19220b56a9bdf3ed
3,622,518
def im_list_to_blob(ims): """Convert a list of images into a network input.""" max_shape = np.array([im.shape for im in ims]).max(axis=0) num_images = len(ims) blob = np.zeros((num_images, max_shape[0], max_shape[1], max_shape[2]), dtype=ims[0].dtype) for i in xrange(num_ima...
705d27e0fe7cde9fda50baf7a4a733fb7c0baa22
3,622,520
def get_bitmasks(enumid): """ Return list of bitmasks used in enum. """ bmasks = [] bid = idc.get_first_bmask(enumid) while bid != idaapi.BADADDR: bmasks.append(bid) bid = idc.get_next_bmask(enumid, bid) return bmasks
dcd9ad692274bf6eced0270830222acb73e025d5
3,622,521
def get_discrete_physical_eigenvalues_and_amplitudes(lamdas, amps, re_lower): """Find and print only physical eigenvalues. Eigenvalue :math:`\lambda` is called nonnegative here if :math:`\Re \lambda >=` -`re_lower` and :math:`\Im \lambda >= 0`. Parameters ---------- lamdas : ndarray Ar...
b0f04f22a2ff6214448ab5a132fa6efdbbd17a5b
3,622,522
from rstoolbox.components import DesignFrame, DesignSeries import operator def label_sequence( df, seqID, label, complete=False ): """Gets the sequence of a ``label``. Depends on label data for the ``seqID``. Adds a new column to the data container: =========================== ====================...
db3cb7fe7e1735b62c7c620368f32c93dde1e33a
3,622,523
import random from datetime import datetime def MSF_config(BIM): """ Rules to identify a HAZUS MSF configuration based on BIM data Parameters ---------- BIM: dictionary Information about the building characteristics. Returns ------- config: str A string that identifie...
6dc3d529bf478091ded0ac9c83f4003b36d18b50
3,622,524
def get_bond(mol, bond_idx): """ Get oebond object Parameters ---------- mol : oemol Molecule to extract bond from bond_idx : tuple of ints tuple of map indices of atoms in bond Returns ------- bond: oebond """ atoms = [mol.GetAtom(oechem.OEHasMapIdx(i)) for...
9f89921ebe14bf8ecf9c183f90393b00ffcf1054
3,622,525
import typing import pathlib import itertools def find_pyfiles() -> typing.Iterator[pathlib.Path]: """Return an iterator of the files to format.""" return itertools.chain( pathlib.Path("../gdbmongo").rglob("*.py"), pathlib.Path("../gdbmongo").rglob("*.pyi"), pathlib.Path("../stubs").rg...
74b0c11771799fba6090569595d24e70ec68899d
3,622,526
def compare_angle(attr_a, attr_b=0, operation=0): """Create math_CompareAngle-node to get boolean of logical comparison between given attrs. Args: attr_a (NcNode or NcAttrs or string): Maya node attribute. attr_b (NcNode or NcAttrs or float): Maya node attribute. operation (NcNode or Nc...
b92777ed952c790af8fd8433d8cd367b1a959cc0
3,622,527
def _power_off(ssh_obj, driver_info): """Power OFF this node. :param ssh_obj: paramiko.SSHClient, an active ssh connection. :param driver_info: information for accessing the node. :returns: one of ironic.common.states POWER_OFF or ERROR. """ current_pstate = _get_power_status(ssh_obj, driver_i...
02f12753c43bdba2849dc7199e98f0e59419a2e1
3,622,528
def train_valid_test_generator(): """Loading mnist dataset from tensorflow.keras and scaling the pixels between 0 to 1 Args: NA Returns: nd array: Train, Test and Validation datasets """ mnist = tf.keras.datasets.mnist (x_train_full, y_train_full), (x_test,y_test)= mnist.load_dat...
8bb1f7c12d35d06a10d4a6dccdc0a0ec50a0df77
3,622,529
def merge_args(args, cloud_args): """merge_args""" args_dict = vars(args) if isinstance(cloud_args, dict): for key in cloud_args.keys(): val = cloud_args[key] if key in args_dict and val: arg_type = type(args_dict[key]) if arg_type is not type(...
06f84376e23535e9d291eb9bc9514fa27582faa2
3,622,531
def has_permission(obj, actor, codename, roles=None): """Checks whether the passed actor has passed permission for passed object. **Parameters:** obj The object for which the permission should be checked. codename The permission's codename which should be checked. request ...
2f5d71ce73efb4c38874d1d12a453dc7cda9ad00
3,622,533
def OD2RGB(OD): """Convert optical density back to RGB""" return 255 * np.exp(-OD)
7f0d395e8ebdd83376798507210ab8381a4c6380
3,622,535
def get_caqi_no2_1h(no2_max_1h: float) -> float: """ Calculates NO2 (max in 1h) CAQI Europe :param no2_max_1h: NO2 (max in 1h), ppm :return: NO2 CAQI Europe """ cp = __round_down(no2_max_1h * 1000) return __get_aqi_general_formula(cp, EU_NO2_1H, EU_CAQI)
29e83ee8627905df6f592c120514d35b7b1b732c
3,622,536
def visibility_define(config): """Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty string).""" hide = '__attribute__((visibility("hidden")))' if config.check_gcc_function_attribute(hide, 'hideme'): return hide else: return ''
b08e8515440c4bf1ebec51c4100e55fe9f14b17d
3,622,537
def get_best_path(digraph, start, end, path, max_buildings, best_dist, best_path): """ Finds the shortest path between buildings subject to constraints. Parameters: digraph: instance of Digraph or one of its subclasses The graph on which to carry out the search ...
d0e06d81abafa013fdbb1422e6f88298039a5a01
3,622,538
def calculate_num_points_in_solution(solution): """Calculates the number of data points in the given solution.""" return sum(len(points) for points in solution.values())
c75f7cb7d9c8c2731e4698040954c559b6b5d4ec
3,622,540
from typing import List def _create_dataset( mesh: salvus.mesh.unstructured_mesh.UnstructuredMesh, mask: np.ndarray, parameters: List[str], coords: str, ): """ Create an xarray dataset with relevant information from mesh :param mesh: Salvus UnstructuredMesh object :type mesh: salvus.m...
60c17af1a190e210eabd561a604c5abe2b8fca5d
3,622,541
def binarize_labels(labels): """ Change the labels to binary :param labels: np array of digit labels :return: """ labels = np.where(labels == 0, labels, 1) return labels
e5e1d63898e1f682fdacf90e7540872a1f4c03cf
3,622,542
def match_datasets(base_dataset, dataset_tomatch): """" Match two datasets defined on different grid. Given a base dataset and a dataset to be matched, find for each point in the dataset to mathc the closest cell in the base dataset and return its index. Parameters ---------- base_dataset:...
3f7edf0e47dc4018e58f041e2a3ea610b41cb0b7
3,622,543
from typing import Tuple from typing import Dict import traceback def rest_invalid_arguments_error_handler(exception: Exception) -> Tuple[Dict, int]: """Handle invalid arguments errors. :param exception: Python Exception :return: tuple with response and status code """ logger.warning(traceback.fo...
f32d6a686e2db2aae279aaca7ac9cb3c52a67f81
3,622,544
def _capabilities_semantic_checks(caps_dict): """ Early check of capabilities """ # Get supported capabilities valid_data = {} for key in caps_dict: if key in CAPABILITIES['backend']: valid_data[key] = caps_dict[key] continue for svc in constants.SB_CEPH_SVCS_SUP...
95584c7f06f91ab0d2fc0c72d011873790c374db
3,622,545
import torch def generate_spirals(n_samples=100, noise=1e-4, **kwargs): """Creates a *spirals* dataset of `n_samples` data points. :param n_samples: number of data points in the generated dataset :type n_samples: int :param noise: standard deviation of noise magnitude added to each data point :ty...
e1a6ffd7c3c0532bf9f443b9b64b6447b4ebfae6
3,622,546
def register_feature(fn, name=""): """ Decorator that can be used to register a feature. :param function fn: The function to register. :param str name: Optional string with the name of the function as it should be registered. If not provided the name of the function is used. """ ...
88a420dbabc3ac372ee1c7a71038916c8671c246
3,622,547
def apply_rotation_on_vector(q, v): """q is the quaternion describing the rotation to apply, v is the vector on which to apply the rotation""" quaternion_v = transform_vector_to_quaternion(v) transposed_q = conjugate_quaternion(q) r = quaternion_product(quaternion_product(q, quaternion_v), transpo...
72e64e8e36580d7ccf3e2876ae397fce616d2f3c
3,622,548
import re def get_polygon_speed(polygon_name): """Returns speed unit within a polygon.""" result = re.search(r"\(([0-9.]+)\)", polygon_name) return float(result.group(1)) if result else None
2d2cc99f30153c4fbc9ac358ad3debc15fc3227e
3,622,549
def pt_in_ploy(poly, x, y): """ 判断 点(x,y) 是否 在 poly 最大和最小坐标之外,粗略 判断点是否在图形之内 """ n = len(poly) if n < 3: return False xmax = xmin = poly[0]['x'] ymax = ymin = poly[0]['y'] for i in range(1, n): if poly[i]['x'] > xmax: xmax = poly[i]['x'] elif poly[i]['x'] < x...
2e07429edd6929a7e5747e6ba113f4186413dab8
3,622,550
def random_node_presence(t_windows, rep, plac, dur): """ Generate the occurrence and the presence of a node given occurrence_law(occurrence_param) and presence_law(presence_param). :param t_windows: Time window of the Stream Graph :param rep: Number of segmented nodes :param plac: Emplacement o...
416ea50c4cdd1280dde90816ec735b8eff6f81f1
3,622,552
def action_details(request, test_id, action_id): """ Generate HTML page with detail data about test action **Template:** :template:`test_report/action_details.html` """ action_aggregate_data = list( TestActionAggregateData.objects.annotate( test_name=F('test__name')).filte...
0ef73debe1031cc34fd41575ee19d9b29bd3a311
3,622,553
import pdb import torch def batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft'): """Build the triplet loss over a batch of embeddings. For each anchor, we get the hardest positive and hardest negative to form a triplet. Args: labels: labels of the batch, of size (batch_s...
2853124d06688eaca4f7da2a5bc19819490656c9
3,622,554
def rebin(x: VariableLike, dim: str, bins: _cpp.Variable) -> VariableLike: """ Rebin a dimension of a data array or dataset. The input must contain bin edges for the given dimension `dim`. :param x: Data to rebin. :param dim: Dimension to rebin over. :param bins: New bin edges. :raises: If...
8810775aa7a1f5ddfa9ee13f2f2f7cd0853fbde0
3,622,555
def scalar_div(x: Number, y: Number) -> Number: """Implement `scalar_div`.""" _assert_scalar(x, y) if isinstance(x, (float, np.floating)): return x / y else: return int(x / y)
c05cc4657ae250e8db8da0770fde80892e864987
3,622,557