content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def resnet18_feat(pretrained=False, initpath=None, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet_feat(BasicBlock, [2, 2, 2, 2], deep_base=False, **kwargs) if pretrained and initpath is ...
9724abbe0e4d1a578866626e14712ebb8994cd78
3,616,476
import pandas from typing import List from typing import Any def keep_these_labels_only( dataframe: pandas.DataFrame, label_column: str, labels_to_keep: List[Any] ): """ Parameters ---------- dataframe: `pandas.DataFrame`, required The input dataframe label_column: ...
25c9b1b83f690e1ef9ba15cc8dbd22fe939633b0
3,616,477
def create_blocks(arr, block_size=(1024, 1024)): """Split input array into uniformly-sized blocks This function will split the input array into uniformly-sized blocks with the size of each block specified as `block_size`. The input array will be zero-padded in either or both axes in order to expand th...
cd1456b967e0473031f74dde16445199d51b45de
3,616,478
import string def PrintableString(s): """For pretty-printing in tests.""" if all(c in string.printable for c in s): return s return repr(s)
4f22a5ed8152039a21e045ea2e04b4cff3dbec85
3,616,479
def expected_regularization(): """Build the expected alive vectors applying the rules of concat and group.""" concat = REG_STUB['conv1'] + REG_STUB['conv2'] # Grouping: Activation is alive after grouping if one of the constituents is # alive. grouped = [max(a, b) for a, b in zip(concat, REG_STUB['conv4'])] ...
cd3ee30a482bbd57a3cd7802b680a6a997ed86b1
3,616,480
def trans_concat(*args): """Concat all parts of tag and translate it.""" return _(''.join(args))
9d66c7ea0a8d2b68837db570824a93ac993c66a5
3,616,481
def mean_normalize_data(data: np.ndarray) -> np.ndarray: """ Mean normalization method. :param data: Data cube. :return: Normalized data. """ for band_id in range(data.shape[SPECTRAL_AXIS]): max_ = np.amax(data[..., band_id]) min_ = np.amin(data[..., band_id]) mean = np....
5c7a951a46fad9eb7178c4581a78fad50e7096eb
3,616,483
def make_intervals(b3, b4): """ Given the already parsed igs block 3 and 4 dictionaries (aka '3. GNSS Receiver Information' and '4. GNSS Antenna Information') as parsed from an IgsLogFile instance (see IgsLogFile::parse_block), concatenate the intervals based on changes either on the 3 or 4 bl...
474edeb9e3885ade5b645e039849a72e938c92e6
3,616,484
def discretize_kernel( kernel, sampling_rate, area_fraction=default_kernel_area_fraction, num_bins=None, ensure_unit_area=False): """ Discretizes a kernel. :param kernel: The kernel or kernel function. If a kernel function is used it should take exactly one 1-D array as argument. :t...
6eaad515117dbe3ea5b2835fc944419f73cf7219
3,616,485
import six def bitcast_to_bytes(s): """ Take a string and return a string(PY2) or a bytes(PY3) object. The returned object contains the exact same bytes as the input string. (latin1 <-> unicode transformation is an identity operation for the first 256 code points). """ return s if six.PY2 ...
b902550be03f447a286490653a2a1361257ac88c
3,616,486
import functools import signal def waiting_for(func=None, *, timeout=settings.DEFAULT_TIMEOUT): """ Set maximum execution time for a function :param func: function to decorate :param timeout: maximum allowed execution time :return: result of the func """ def _alarm_handler(signal_number,...
e2ab885369b013442d9003cc2936e19fb8814fcc
3,616,487
import numbers import logging def orthogonal_regularizer(scale, scope=None): """ Return a function that computes orthogonal regularization. :param scale: A scalar multiplier `Tensor`. 0.0 disables the regularizer. :param scope: An optional scope name. :return: A function with signature `orthogonal_sum...
fe2c7823232737bcc8dbc94c0b95c8b049e3ca16
3,616,488
from typing import Type from typing import Hashable def _lookup(key: str, typ: Type, *args, **kwargs) -> Hashable: """ Gets the value of the given key in args, defaulting to the first positional. :param key: key to find value of in args. :param typ: type that dispatch is being perform on. :param ...
195e95cd1d77137890d0608195677c344e698ad7
3,616,490
def MakeStatefulPolicyPreservedStateDiskEntry(messages, stateful_disk_dict): """Create StatefulPolicyPreservedState from a list of device names.""" disk_device = messages.StatefulPolicyPreservedStateDiskDevice() if stateful_disk_dict.get('auto-delete'): disk_device.autoDelete = ( stateful_disk_dict.ge...
10b1fcb79b46455bef8bbfba90c84bcdb80773df
3,616,491
def _doc(from_func): """copy doc from one function to another use as a decorator eg:: @_doc(file.tell) def tell(..): ... """ def decorator(to_func): to_func.__doc__ = from_func.__doc__ return to_func return decorator
907a12da3700cee02e4f369d5230bd8be04e55ea
3,616,493
async def get_prometheus_rules(ops_test: OpsTest, app_name: str, unit_num: int) -> list: """Fetch all Prometheus rules. Args: ops_test: pytest-operator plugin app_name: string name of Prometheus application unit_num: integer number of a Prometheus juju unit Returns: a list ...
c716c0d8293f5153e27ff7836c10e33a89e7d7bc
3,616,494
import sqlite3 def connect_to_sqlite3_db(): """ Connects to the sqlite3 database. :return: Connection of type sqlite3.Connection. """ config = ConfigParser() config.read(CFG_FILE) conn = sqlite3.connect(config['paths']['path_to_database']) conn.row_factory = sqlite3.Row return conn
a25373b104b15d6bef1f00a854e1a2e459d6defb
3,616,496
def quote(): """Get stock quote.""" if request.method == "POST": stock_info = lookup(request.form.get("symbol")) if stock_info == None: return apology("cannot find that stock symbol", 403) else: return render_template("quote.html", ...
ab3782027eb2a58e5a770bc631aca1725169a6c8
3,616,497
import re def validate_time_string(value, is_list): """ Checks that a "time string" quant is correctly formatted. A time string can contain three kinds of expressions, separated by + or -: Base values, which are just numeric (with an optional exponent on e form) Delta values, which are the...
802e7503f19ed1a5bb47ad887d1fe15219225fe1
3,616,499
def resnet101(rate=1, class_num=10, index=None): """ Get ResNet101 neural network. Args: class_num (int): Class number. Returns: Cell, cell instance of ResNet101 neural network. Examples: >>> net = resnet101(1001) """ return ResNet(rate, ResidualB...
dfc706eb4bd8ce205692d1c031b650f434ba605c
3,616,500
import typing import math def _smart_ceil(x: typing.Union[int, float], order: int = None) -> int: """Smart ceil to the nearest round integer. The 'nearest' is chosen based on the order of the given number """ order = int(order) if order else len(str(math.ceil(x))) if order <= 0: raise...
5a93521630b3241844d958eb07b738a62816b7ad
3,616,501
def get_file_storage_impl(request): """ Retrieves correct **IFileStorage** instance from the registry. :param request: Pyramid Request instance """ registry = getattr(request, 'registry', None) if registry is None: registry = request return registry.getUtility(IFileStorage)
2bd3a98728bea03b0870b36f982f019b473cf9c7
3,616,502
def norm_observation(mat, axis=-1, eps=EPSILON): """ L2 normalization for observation vectors """ denorm = np.linalg.norm(mat, axis=axis, keepdims=True) denorm = np.maximum(denorm, eps) return mat / denorm
1a931600f139ff5b66f780f3be3b021d64ae2f3a
3,616,503
def get_commercial_from_lowertext(transcript, video_desp): """ Get region with lower case transcript """ def is_lower_text(text): lower = [c for c in text if c.islower()] alpha = [c for c in text if c.isalpha()] if len(alpha) == 0: return False if 1. * len(lo...
898b4605a769b62e3c9fbd1b9aa8b446a1cf54c2
3,616,504
def rl_modelrl_breakout_ae_medium(): """Medium set for testing Breakout with an autoencoder.""" hparams = rl_modelrl_ae_medium() hparams.game = "wrapped_breakout" return hparams
bb1a54ebf5a2706fb29c85873e10e0052f4872e0
3,616,506
def layer_norm(inputs, center=True, scale=True, activation_fn=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, begin_norm_axis=1, begin_params_axi...
c53b552d8726d619be04ae27c9d0f9a61cd44518
3,616,507
def get_dependency_type(dependency): """Get dependency type from dependency name""" if dependency.startswith("."): return RELATIVE for internal in INTERNAL_ALLOWED_ORDER: if dependency.startswith(internal+"/"): return internal return EXTERNAL
80ed3a46c7740b573e849c11503e08a7509f0564
3,616,508
import random def generate_paired_images_to_inspect_three_different_ways(dataset_to_use, yhat): """ Try pairing images by KLG; by all image features (basically we take the max over feature categories); and by invididual and side. In all cases, the "high pain" image is on the right, although the way we de...
4101f0366ec96a2facd963367370d484e19baebc
3,616,509
def reducejson(j): """ Not sure if there's a better way to walk the ... interesting result """ authors = [] for key in j["data"]["repository"]["commitComments"]["edges"]: authors.append(key["node"]["author"]) for key in j["data"]["repository"]["issues"]["nodes"]: auth...
90e50ff58e830fbe902a42c4256b19d9c6c46ff0
3,616,510
from typing import Tuple def vis_mask(img: np.ndarray, mask: np.ndarray, col: Tuple[int, int, int], alpha: float = 0.4): """ Visualizes a single binary mask by coloring the region inside a binary mask as a specific color, and then blending it with an RGB image. Args: img: Numpy array, represe...
1abfd847a2882f99072f2668f62f86070c13e0c3
3,616,511
async def async_setup(hass, hass_config): """Set up the Plaato component.""" return True
b2c620c58aabcf788310e3aaf9cdf836f9be15ba
3,616,512
from typing import Union from typing import Dict def _get_upstream_seqs( ica_data: IcaData, imodulon: Union[str, int], seq_dict: Dict, upstream: int, downstream: int, ): """ Get upstream sequences for a table of operons Parameters ---------- ica_data: IcaData IcaData o...
ef7264f427849c51808494b06881393e78771e63
3,616,513
def json_value(obj): """Format obj in the JSON style for a value""" if type(obj) is bool: if obj: return '*true*' return '*false*' if type(obj) is str: return '"' + obj + '"' if obj is None: return '*null*' assert False
fc34c619d550af029536437c0eec7163e3ce673c
3,616,515
def exp(node) -> Node: """Exponential of the node, using np.exp(x)""" return Node(node, None, np.exp(node.value), 'exp' )
e24d6fffe24fde099ba1f1588aff20a4d848b975
3,616,516
def bias_variable(shape): """Generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name='bias')
cd71c9e0e36ea144cc30498fba03189b5c2d03b4
3,616,517
def padmat(input_mat,left_pad=0,right_pad=0,up_pad=0,down_pad=0): """ Helper function to pad zeros to image matrices to edges don't get cut off. """ new_mat = np.zeros((input_mat.shape[0]+up_pad+down_pad,input_mat.shape[1]+left_pad+right_pad)) new_mat[up_pad:new_mat.shape[0]-down_pad,left_pad:new_m...
3e7c23bdc38c8b2a4e2e83229c8d7a9b70f459a6
3,616,520
def calc_E_M_C_hs_d_t(): """冷房設備機器のその他の燃料による一次エネルギー消費量(MJ/h)(22d, 23d)を計算する Args: Returns: ndarray: 冷房設備機器のその他の燃料による一次エネルギー消費量(MJ/h) """ return calc_E_M_C_hs_MR_d_t() + calc_E_M_C_hs_OR_d_t()
0766106006545b36b97ca4cbbf980b27779e3d01
3,616,521
def load_adjacency_list(file: str, bipartite: bool = False, comment: str = '%#', delimiter: str = None, ) -> Bunch: """Parse Tabulation-Separated, Comma-Separated or Space-Separated (or other) Values datasets in the form of adjacency lists. Parameters ---------- file : str ...
256c3ec7515c54ac93f5d81df3b9d413752fadfa
3,616,522
import numpy def _check_input_args_many_predictors( predictor_matrix, predictor_names, cmap_object_by_predictor, cnorm_object_by_predictor, min_colour_value_by_predictor, max_colour_value_by_predictor, plot_wind_barbs): """Error-checks input arguments for `plot_many_predictors*`. :par...
303565534f8693cbf27bf99d63017aea9343f5cc
3,616,523
def sim_real_change(request): """ Return a dummy YATSM model container with a real change "Real change" dataset is simply a timeseries drawn from samples of two normal distributions with greatly different mean values. """ np.random.seed(123456789) dates = np.arange(dt.strptime('2000-01-01', '%Y...
a4f42d1235569da39375909f8db01cf7816ca17f
3,616,524
def plugin_reconfigure(handle, new_config): """ Reconfigures the plugin it should be called when the configuration of the plugin is changed during the operation of the South service; The new configuration category should be passed. Args: handle: handle returned by the plugin initialisation cal...
9626575a4ab1c82d6c6eccae56fa0158ab8da008
3,616,525
from operator import concat def homogenise_dates(d: DataFrame): """ Parameters ---------- d Returns ------- """ d.date = to_datetime(d.date, format="%Y-%m-%d") col_names = d.columns date = date_range( start=to_datetime(d.date).min(), end=to_datetime(d.date)...
4b556291b4322121d64234df5ee17a8b7d14e844
3,616,526
def compute_x_in_set(x, s): """Check if elements in tensor x are in set s. Args: x: batch_size, num_candidate s: batch_size, k (padded with -1) Returns: boolean tensor with shape of x """ s = tf.expand_dims(s, axis=2) # batch_size, k, 1 k = tf.shape(s)[1] x = tf.tile(tf.expand_dims(x, axis...
c20b29d4e1ec63e0bb12f582401a0b044025542a
3,616,527
def checkunique (uniquerules, rule) : """check if rule already exists Parameters uniquerules : list of unique rules rule : rule to check Returns True or False """ for r in uniquerules : if samerule (r, rule) : return True return False
0e803c007747dc997c5b9cda42997b375b180e43
3,616,528
def global_to_body(q, vec): """ Convert a vector from global to body coordinates. Parameters: ----------- q: quaternion The rotation quaternion vec: ndarray The vector in global coordinates Returns: vec: ndarray The vector in body coordinates """ # quate...
1aa3aedba92fdb513856477b8c9b7de6a7812a9d
3,616,529
import re def get_hostmask_regex(mask): """Get a compiled regex pattern for an IRC hostmask :param str mask: the hostmask that the pattern should match :return: a compiled regex pattern matching the given ``mask`` :rtype: :ref:`re.Pattern <python:re-objects>` """ mask = re.escape(mask) ma...
6e46d907d51e32139168d6f6405ca45ca38bbb98
3,616,530
def create_map(template_id, report_id, created_by): """Submits a request to CARROT's template_report create mapping""" return request_handler.create_map( "templates", template_id, "reports", report_id, [("created_by", created_by)], )
83335f2dc06dcfd7661e51df30e79b8ca9e3e231
3,616,531
from typing import Any import yaml from typing import List def read_yaml(file: Any) -> dict: """Read yaml file. Return dict.""" if isinstance(file, str) and any(file.endswith(x) for x in ('.yml', '.yaml')): with open(file, "r", encoding='utf-8') as fp: return yaml.load(fp, Loader=yaml.Full...
d696372cb5fb0b494d257b296dd6ac7946e296ff
3,616,532
def pass_alignment_qc(alignment, barcodes): """ Check high quality mapping, QC-passing barcode and UMI of alignment. alignment : aligned bam segment barcodes : list List of cellular barcode strings Returns ------- pass_qc : boolean true if a high quality, QC passing ...
2e75a6d66c1bbf4afed9f4fa1a3f9d21fcc6a853
3,616,533
def _netid_admin_url(netid): """ Return UWNetId resource for provided netid supported resources """ return "{0}/{1}/admin.json".format(url_base(), netid)
ab62b99efc92c20eda62e6c2fffc0f761cebd15c
3,616,534
def retrieve(customer, sub_id): """ Retrieve a subscription object from Stripe's API Args: customer: a legacy argument, we check that the given subscription belongs to the given customer sub_id: the Stripe ID of the subscription you are fetching Returns: the data fo...
ee348999090a14b3a7adf9b97a83ecbcd92605eb
3,616,535
from typing import List def get_total_innocent_reds(executions: List[RevisionResults]) -> int: """ Get number of innocent red commits from a given list of execution results. :param executions: list of execution results :return: number of innocent red commits """ count = 0 previous_fails =...
7fce0016664485154a03d5ef6996957c7dad472e
3,616,537
def read_ffindex(file): """Read a ffindex and return a list of all the lines in the file . Args: file (string): path to the ffindex Returns: list of string: The file read line by line """ fh = open(file, "r") index = [] for line in fh: index.append(line.rstrip(...
fae6494ddbda63abae1161f9fd22c8a94f506407
3,616,538
def load_ppi(fname='bio-decagon-ppi.csv'): """ Returns networkx graph of the PPI network and a dictionary that maps each gene ID to a number :param fname: :return: """ fin = open(fname) print('Reading: %s' % fname) fin.readline() edges = [] for line in fin: gene_id1, gene...
b482c86f1409caeb059fedee167b899529c094be
3,616,539
def get_field_from_args_or_session(config, args, field_name): """ We try to get field_name from diffent sources: The order of priorioty is following: read_default_contract_address - command line argument (--<field_name>) - current session configuration (default_<filed_name>) """ rez = getattr...
8979a90814bcab9c72f54835a31d69971f8b1437
3,616,540
def scrape_all_songs(): """ Gets all lyrics from all available songs on the wiki. """ print('Scraping all songs from {}'.format(URL)) soup = scrapekit.handle_url(URL) song_elements = [] tables = soup.findAll('table') for t in tables: field_index = scrapekit.get_col_index(t, field_name=...
be061ee05ee3873ce87f8c846213e92560162e1f
3,616,541
import networkx def load(filepath): """ :param filepath: A str or :class:`pathlib.Path` object gives a path of network graph data ({'nodes': ..., 'links': ...}) in JSON or YAML formats :param ac_args: keyword arguments given to anyconfig.load :return: An instance of networkx.Graph ...
bbab216df470d805f0b8b8f78cd856e167082ebb
3,616,542
def pdf_from_template(html_template, data): """ !Requirement: make sure that wkhtmltopdf is installed in your system For more configuration info: https://pypi.org/project/pdfkit/ Generate a pdf file from html template :param html_template str: html template with jinja template strings :param d...
71dc765c90b43a79b6d9ce5a1b76393b47da2bf7
3,616,544
import logging def get_db(): """Opens a new database connection if there is none yet for the current application context. """ logging.info("g %s, %s", g, hasattr(g, 'sqlite_db')) if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db
2f3867693b15adab25cc9aeafbf34e05b02eacf7
3,616,545
import functools def log_header(header=None): # pylint: disable=R0912 """Flask decorator to log headers or a specific header :param header: This can be a string as to which header to log """ def decorator(func): """Function decorator to log header(s)""" def wrapped_functio...
ddf00ee6cdb809ee7fb7c2631f802984a4828d1e
3,616,546
def show_abs_oovs(abstract, vocab, article_oovs): """Returns the abstract string, highlighting the OOVs. """ unk_id = vocab._word2id(UNKNOWN_TOKEN) words = abstract.split() vwords = [] for w in words: if vocab._word2id(w) == unk_id: if article_oovs is None: vw...
15c234f422f08e6ef5fd129bbc170923bb9abf02
3,616,547
import urllib import json def score_paper(arxiv_id): """ Sum up the 'influentialCitationCount' (Semantic Scholar) from each author """ if arxiv_id in paper_scores: return paper_scores[arxiv_id] # request data base_url = 'https://api.semanticscholar.org/v1/paper/arXiv:' try: ...
91fef478bf286cac8254d932bb4b1db99e207bc6
3,616,549
import importlib def resolve(module_name, obj_name): """ Resolve a named object in a module. """ return getattr(importlib.import_module(module_name), obj_name)
87ccef3456d28615b82a89a8e4ce405403eaade9
3,616,550
def mock_read_narrative(style): """ Mocks the NarrativeIO.read_narrative() function. Style should be one of "good", "bad", or "private". A "good" narrative will just return the valid read_narrative() results by loading and returning the given file. (will raise a ValueError if file is None). ...
5be8930591c3612b24784ba562d60a7731f7a43f
3,616,551
def normalize_query_parameters(query_string): """ normalize_query_parameters(query_string) -> dict Converts a query string into a dictionary mapping parameter names to a list of the sorted values. This ensurses that the query string follows % encoding rules according to RFC 3986 and checks for dup...
ea45fe96d0b22cde8677354769b764687a53f2bb
3,616,552
def read_in(fn): """Read in data to header and data""" with open(fn,'r') as f: data=[] start_right=0 for line in f: words = line.strip().split() words = [word.strip() for word in words] if words[0] == "#" or words[0]=='ID': start_right ...
a885b3031ff37ba6361cd8be342b585cb3d32ad2
3,616,554
def get_users(token, include_locale=False, presence=False): """ Get user list """ params = { "token": token, "include_locale": include_locale, "presence": presence } r = get("https://slack.com/api/users.list", params=params) if r.ok: rparsed = r.json() ...
aff2dcdb83a3a624e960ede3b36d73737d8c0982
3,616,556
def convertScene(convertContext, data): """ Converts a Scene. The data is expected to contain the following elements: - sharedItems: an optional array of shared item lists. Each element of the array is itself an array with the following members: - type: the name of the item list type. - name: the name of th...
fe840e525a84e88ae30ee26008849076f60c953c
3,616,557
def valid_rfc5737(network: str) -> bool: """ Verify an IP Address is in RFC5737 """ answer = False if IPNetwork(network) in IPNetwork('192.0.2.0/24'): answer = True elif IPNetwork(network) in IPNetwork('198.51.100.0/24'): answer = True elif IPNetwork(network) in IPNetwork('2...
a2b46f16cbf54c822a5ab193f671976ecdcc7d6c
3,616,558
def create_noisy_signal(signal_fp, snr, noise_fp=None, offset=None): """ Create a noisy signal of a specified SNR. Parameters ---------- signal_fp : string File path to clean input. snr : float SNR in dB. noise_fp : string File path to noise. Default is to use randoml...
d7176fc1a2ffb40d79aa71e921d4e9d833e843f0
3,616,559
def number_size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits, power = 0,1L while N >= power: bits += 1 power = power << 1 return bits
a8bbb68e836bb5a6b93cc6296ce8edc20ff7e6cc
3,616,560
import time import hashlib def default_login(): """View with login form.""" if len(request.access_route) > 1: ip = request.access_route[-1] else: ip = request.access_route[0] login_attempt = LoginAttempt() previous_attempts = login_attempt.get_failed_attempts_count( ip, ...
a74743cec37ef6a93f00ed3406c43151b95d4cf1
3,616,561
def mnist_1_5(): """ train: (12163, 784), test: (2027, 784) """ eps_dataset = 0.3 classes = [1, 5] # 2 is 1, 6 is -1 in the binary classification scheme (X_train, y_train), (X_test, y_test) = mnist_keras.load_data() X_train, X_test = ( X_train.astype(np.float64) / 255.0, X_...
91ed5897e29665b08891a838b6213ed83247763a
3,616,562
import logging def standardize_team_name(team: str) -> str: """Standardizes team name across sites Args: team (str): the code or team name Returns: str: team name, Atlanta Falcons, Baltimore Ravens, etc. """ matches = _standardize(team, TEAM_NAMES) if not matches: lo...
718f93d08f70575b259d5546760fa7486156a7e6
3,616,563
def get_num_shorts(string_list): """ Returns the number of occurences of 'Short' in an input string list. Args: string_list(list of string objects) Returns: numShorts(int): Number of occurences of 'Short' """ numShorts = 0 for marker in string_list: if (marker == '...
b8e9da454590a8b29965696be3265053cfc78729
3,616,564
def get_saved_artists(auths=None, offset=0, limit=20): """ Extracts and returns a list containing the IDs for all artists followed by any of the accounts defined in 'sources'. :param auths: dict() being the 'sources'-tree of the auth object as returned by authorize() :param offset: int() defining at whi...
38611e27821a466421dc3d21d59eb53443136626
3,616,565
import pandas def _try_to_date(x): """Wrapper around :func:`pandas.to_datetime` that returns the input unaltered if it's not a date. Don't attempt converting numeric or boolean arrays. """ if x.dtype.kind != 'U': # unicode string return x try: # In case of ambiguity, prefer Eu...
01d296b0578933954a3b6593fd52fc15620cc1cd
3,616,566
def at_2_Pa(value): """ converts pressure in at (technical atmosphere) to Pa :param value: pressure value in at (technical atmosphere) :return: pressure value in Pa """ return value * const_at
30b514cf97205ec7bb9dd5f6c8bd2d7cacdfbc6b
3,616,567
def evaluate(results, annotations, checkpoint, iou_threshold=0.5, save_path=None): """ Evaluate a given dataset using a given retinanet. # Arguments results : detection results annotations : original data iou_threshold : The threshold used to consider when a detection is po...
c0d2b5779d243600abed56c3690baf1d84b3c1c2
3,616,568
async def get(request: Request, organization_id: UUID) -> services.organization.Organization: """Organization get """ return await services.organization.get( organization_id=typeof.OrganizationID(organization_id), member=request.app.state.member, )
9e8a862c1c3c9a59d49265c5746bfc8f92fb8a3b
3,616,569
def w_quest_class(sentence): """ process what question about classification Input=sentence Output=class Sentence """ analysis = y_n_ques(W_QUESTION, 'classification' + '+' + sentence[4], sentence[5:]) if analysis.sn: #The d...
98a3ef03bbd32f81262d663401d84e637ca7d8eb
3,616,570
def exp_so3(v): """ Grassia, F. S. (1998). Practical parameterization of rotations using the exponential map """ angle = np.linalg.norm(v) if angle < np.power(np.finfo(float).eps, 0.25): na = 0.5 + angle * angle * 1.0 / 48.0 else: na = np.sin(angle * 0.5) / angle ct = n...
aee158e66024d9445757a066d12350794a33f284
3,616,571
from typing import Callable from typing import Iterable def choose(chooser: Callable[[TSource], Option[TResult]]) -> Projection[TSource, TResult]: """Choose items from the sequence. Applies the given function to each element of the list. Returns the list comprised of the results x for each element where ...
aa8f7008c3590c0a25100cb851e59f5efe6a3440
3,616,572
import jinja2 def create_j2env(template_dir) -> jinja2.Environment: """ Create a Jinja2 enviornment instance used when template building the containerlab topology file. Parameters ---------- template_dir: str The file path where the Jinja2 template file is located. Returns --...
1d6559eae0346c0b9fd6171c18da5f2d94e1db86
3,616,573
import ast def _unpack_lists(input_list): """Unpacks a list of strings containing sublists of strings such as provided by the data table in the 2d U-net training pipeline card Args: input_list (list): list of strings which contain sublists Returns: list: list of hidden items from the...
e80cd60e46b0ec5b5dd9b4a88ebe7193c0645f48
3,616,574
from astropy.table import vstack from .API_PS1_DR2 import ps1cone import math def cross_match_PS1_DR2(wcs_data, SE_catalog, image_bounds, band='g', radius=None, clean_catalog=True, pixel_scale=2.5, mag_thre=15, sep=2.5*u.arcsec, verbose=True): ...
8b595d4e583785ea9e04483cb4fe0be9ba14405e
3,616,575
def get_raw_column(table_name, column_name): """ Get a wrapped, registered column. This function cannot return columns that are part of wrapped DataFrames, it's only for columns registered directly through Orca. Parameters ---------- table_name : str column_name : str Returns ...
cab069c220836a0de4a8cdbb3189b01d94c0b5f7
3,616,576
def conv_shape_tuple(lhs_shape, rhs_shape, strides, pads, batch_group_count=1): """Compute the shape tuple of a conv given input shapes in canonical order.""" if isinstance(pads, str): pads = lax.padtype_to_pads(lhs_shape[2:], rhs_shape[2:], strides, pads) if len(pads) != len(lhs_shape) - 2: msg = "Wrong ...
a159092252a6159c3156107254b6134b0a557bb0
3,616,577
def shapes_chunks_maxmem(draw, ndim=3, itemsize=4, max_len=10_000): """Generate the data we need to test rechunking_plan.""" shape = [] source_chunks = [] target_chunks = [] for n in range(ndim): sh = draw(st.integers(min_value=1, max_value=max_len)) sc = draw(st.integers(min_value=1...
3df6a7a0bc74e74ececc3349c4a947996e6bf5f9
3,616,578
def vhat(train_position): """ Define the maximum speed of the train in (m/s) as a function of the position. """ # Take desired profile speed and add some buffer only if lower than 100 speed_profile = np.minimum(vbar(train_position) + 30 / 3.6, np.ones(train_positio...
a93f20b84d9f880385dfb569bfbbef76dc9de68c
3,616,580
def get(a_map, name): """Return a _DescriptorInspector around the attribute, or None.""" try: value = a_map[name] except KeyError: return None else: return DescriptorInspector(value)
ac346c1a964f2884c5d7a4c62a628240696b2a44
3,616,581
def jaccard(gt_bbox, bbox_list): """Compute the jaccard overlap of two sets of boxes. The jaccard overlap is simply the intersection over union of two boxes. Here we operate on ground truth boxes and default boxes. E.g.: A ∩ B / A U B = A ∩ B / (area(A) + area(B) - A ∩ B) Args: box...
1b1f8bf381fc521fcf60ff0bf636a0058103c48e
3,616,582
import torch def cc_sample(shape, sigma, alpha, mu=None, repeats=1, **backend): """Sample random fields with a constant correlation. This function computes the square root of the covariance matrix by SVD. Parameters ---------- shape : sequence[int] Shape of the image / volume.å sigma...
2fd23cf054b96cdf590f919f7afda9ea9bbd71b7
3,616,583
def _ActivationParams(op, inexpr, etab): """Get activation parameters""" whichActivation = op.WhichOneof('NonlinearityType') par = getattr(op, whichActivation) if whichActivation == 'linear': alpha = _expr.const(par.alpha, dtype='float32') beta = _expr.const(par.beta, dtype='float32') ...
afd3ec77f4940b6c727201cb9bcf324bb54fa53a
3,616,585
import torch def ln2float(module): """Batchnorm to Float.""" if isinstance(module, torch.nn.LayerNorm): print('Warning: Casting LayerNorm to fp32 ...') module.float() for child in module.children(): ln2float(child) return module
42bb1769a42a722f5332c0d4f1e635cdca2d6451
3,616,587
def error_view(template_dir=None): """ Create the Error view Must be instantiated import error_view ErrorView = error_view() :param template_dir: The directory containing the view pages :return: """ if not template_dir: template_dir = "Pylot/Error" template_page = "%s/...
ec3fb650283c4879d981f1359328012e57ec9db3
3,616,588
from typing import Union import logging def supply_backend(optional: Union[callable, bool]=False, index_exists: bool=True): """ Decorator to pass the initialized backend to the decorated callable. \ Used by command line entries. If the backend cannot be created, return 1. :param optional: Either a de...
950d18ae4765acc71dd7272d2f444e4105f65ff3
3,616,589
def task_detail(request, structure_slug, ticket_id, task_id, structure, can_manage, ticket, office_employee=None): """ View task details :type structure_slug: String :type ticket_id: String :type task_id: String :type structure: OrganizationalStructure (from @has_admin_privilege...
dbb6b16e708ea455075817738d24df27770f725b
3,616,590
import ctypes def isOutputFileClosed(path): """Returns true if target output file is closed, else false. Shows popup if file already in use. Clears contents, so only usable for mode 'w'""" try: f = open(path, "w") f.close() return True except PermissionError: ...
32d7b50b40d9fb50e0466740efa3cb7baeeed6e4
3,616,591
from datetime import datetime def convert_time(timestring, date='1990-01-01'): """Convert time string to have leading zeros. :param timestring: Byte array in '%H:%M:%S' without leading zeros. :param date: Date of the timestamp (defaults to 1990-01-01) :return: time object """ return datetime...
118e205396118e7e64c7b368dc4347d0a6daab63
3,616,592