content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
async def circuit_sat_prover( generators, code, x, gf, pivot_choice=cs.PivotChoice.compressed ): """Non-interactive implementation of Protocol 8, prover-side, including Nullity using compressed pivot (Protocol 5). """ logger_cs_mpc.debug(f"Enter circuit_sat_prover. pivot_choice={pivot_choice}") ...
38f6c19ddc59c1b28620a1d9b1c520a57e79ed79
3,616,505
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
from sys import path def get_view(): """Responds with the form for the example""" return render_template( "eg015_envelope_tab_data.html", title="Envelope information", envelope_ok="envelope_id" in session, source_file=path.basename(path.dirname(__file__)) + "/controller.py", ...
e98246f15825c037d30d485d03ccd8ee3caa55dc
3,616,514
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
from . import kerneldll import os def precompile_dlls(path, dtype="double"): # type: (str, str) -> List[str] """ Precompile the dlls for all builtin models, returning a list of dll paths. *path* is the directory in which to save the dlls. It will be created if it does not already exist. Thi...
566088c8f8dbaca077b54235d03fb8393d13245d
3,616,518
import subprocess def main() -> int: """Main""" # TODO(pwbug/456): Refactor the code so that each test bundle generation # is done in a separate function or script. # pylint: disable=too-many-locals args = parse_args() test_bundle = Bundle() dev_signed_root = test_bundle.generate_dev_sig...
76039cb9ef6978ffc40ab6aa6944c1ddee1432c7
3,616,519
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
import os def read_file(fname): """ Read a file and return the raw data. Create a new file if necessary. """ if not os.path.isfile(fname): with open(fname, mode='w', encoding='utf-8') as f: #TODO: Um. Something more professional perhaps print('NEWFILE!!!!') f.write(...
cce26ca3f0c6ddd26461a7b52d6f3637a9e5eeb8
3,616,536
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
import hashlib import os def calculate_patch_digest(target, hash=hashlib.md5): """Calculate the digest of the entire project based on the files listed in the esky_filelist. This will ensure that patches don't break if any superfluous files have been added to the application folder""" filelist = load_f...
b9437f51dc4e2e782521e6aeadf3dbcb2a3acd77
3,616,543
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 logging import os import glob import re import shutil def compute_rq_name(rq_type, oslevel): """ Compute rq_name. if oslevel is a complete SP (12 digits) then return RqName = oslevel if oslevel is an incomplete SP (8 digits) or equal Latest then execute a metadata suma request t...
daeeba2e5b491f202b62fc096ff0558184549728
3,616,548
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 _match(token: bytes, request: HttpRequest) -> bool: """ Calculate signature and return True if it matches header. Args: token: string, the webhook_token. request: an HttpRequest object from which the body content and X-Signature header will be extracted and matched. Ret...
ee57fe8230290c91b3a0caa526078feba8c55ed9
3,616,553
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
import argparse from typing import TextIO from typing import List from pathlib import Path def arg_filtered_tests(pav_cfg, args: argparse.Namespace, verbose: TextIO = None) -> List[Path]: """Search for test runs that match based on the argument values in args, and return a list of match...
b1af83c5c1a04e31aec46fbfcbe87d06b97a9ed1
3,616,555
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
import os import time def db_insert_filename_mutagen(conn, cursor, filename, size, metadata, filehash): # print ("Scanning file {}".format(filename)) """ insert data into database :param conn: connection :param filename: filename to insert :param size of file :param metadata object :param ...
6aa4280118e65cffb549b211a88e70c680380fc7
3,616,579
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 get_KKP_mech_from_eqn_file_as_df(folder=None, Mechanism='Tropchem', filename=None, verbose=True, debug=False): """ Get KPP mechanism as a pandas DataFrame """ # Set the filename if not provided if isinstance(filename, type...
e932fede2f784b7c40a9249d0cf558894a7d0a9f
3,616,584
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 argparse def parse_arguments(argv): """Parse command line arguments Args: argv (list): list of command line arguments including program name Returns: The parsed arguments as returned by argparse.ArgumentParser """ parser = argparse.ArgumentParser(description='Preprocessing') parser.add...
9a94c3b8ee7a0cdf98581fc7bf19fd0503dd8de8
3,616,586
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
def compute_t_shift(metadata, i, t_p_interp, p_interp, p_file, date_ref, time_ref, dpdt_thresh=10, plot_pressure=True): """ ***OBSOLETE***: I determined that a multiplicative factor more accurately adjusts the Belsorp time than a time shift. See compute_t_multiplier. Computes number...
2a7d5cfd9ba2026b4179cb4629ca5d2f7b8409d9
3,616,593
def quickHBar(ax, xticks, values, colors="b", lw=None): """ This function draws an horizontal bar graph :Arguments: :type ax: matplotlib Axis2D :param ax: Axis on which bar graph will be drawn :type xticks: list :param xticks: Listo of labels for the bars :type val...
15bdcb7b7c78682419af6d53ef103527f434c553
3,616,594
from datetime import datetime def exportFromNotebook(notebookPath, outFNames, outFPath=None, encoding='utf-8') : """ Routine to auto-generate a python script from Jupyter notebook cells. Exports code cells that start with # export name1 name2 ... where one of the names is in the supplied list ...
332597f76c692080ffc561775ee2b837dbc1720b
3,616,595
from re import T def enable_train_mode(mod: T) -> T: """Return a module in training mode.""" return mod.train()
f72448d7b4bc908b8f6fe58b52993d546698e8fd
3,616,596
def train_step(real_image, label, noise): """ :param real_image: :param fake_image: :return: """ with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: generated_image = generator(noise, label, training=True) real_output = discriminator(real_image, label, training=...
6323a5fa0e4982b004151844b84d41b3d557348b
3,616,597
import torch def compute_accuracy(logits, labels, mask): """Compute the accuracy""" logits = logits[mask] labels = labels[mask] _, indices = torch.max(logits, dim=1) correct = torch.sum(indices == labels) return correct.item() * 1.0 / len(labels)
a7ee234837024598fc95fa9c54c55802ea411577
3,616,598
import random import string import traceback def run(ceph_cluster, **kw): """ pre-requisites: 1. Create a volume with a name 2. Create a subvolume with a name 3. Create a subvolume group with a name Test operation: 1. Try to create a volume with the same name 2. Try to create a subvol...
e11dad62bac4033954848050c5f8a1b9c3588e3e
3,616,599