content
stringlengths
22
815k
id
int64
0
4.91M
def test_basic_overlay_file( tmp_path: Path, config_default_builder: ConfigBuilder, datafiles: py.path, copy_test_files: Any, ) -> None: """Manually adds a config dict with a logging_configuration_file.""" from valiant.config.source import TomlSource config_default_builder.add_source( ...
76,700
def run(): """ Adapter to grab environmental zones from some obscure esri server """ connect_string = settings.IPO_ENVIRONMENTAL_ZONES url = urllib.request.urlopen(connect_string) if url.getcode() == 200: data = url.read() # Start inserting result = json.loads(data) ...
76,701
def init(bmap: str, difficulty: str, mirror: bool, download: bool): """ Args: map: search query for map difficulty: search query for difficulty mirror: mirror mode download: if kursordance should download the map """ global map map = beatmap.Beatmap("D:\\games\\osu!\\Songs\\Tokyo_mac...
76,702
def add_index(body): """ Added a new Index :param body: Object that needs to be added to the db. :type body: dict | bytes :rtype: AddIndexResponse """ return Indexes.add_index(connexion)
76,703
def create_tables(): """ Create database tables for each model. """ Playground.create_table() PlaygroundFeature.create_table() Revision.create_table()
76,704
def sum_reduce(iter, params): """ Sums the values for each key. This is a convenience function for performing a basic sum in the reduce. """ buf = {} for key, value in iter: buf[key] = buf.get(key, 0) + value return buf.iteritems()
76,705
def compose_graph(graph_dict, composed_name, name_list): """ Compose multiple graph together coming from a dictionary under a new entry of the dictionary. Parameters ---------- graph_dict : dict Dictionary of every graph. composed_name : str Name of the new key of graph_dict...
76,706
def subslr(method, target, et, fixref, abcorr, obsrvr): """ Compute the rectangular coordinates of the sub-solar point on a target body at a specified epoch, optionally corrected for light time and stellar aberration. This routine supersedes subsol_c. http://naif.jpl.nasa.gov/pub/naif/toolkit_...
76,707
def init_default_extractor(): """ create a new extractor, providing the default (all available extractors) """ return SchemaExtractorSet(DEFAULT_EXTRACTOR_LIST)
76,708
def save_as_npy(path, img): """ Save the image array as a .npy file: Args: Image as numpy array (H,W,3) """ # # You code here # np.save(path,img)
76,709
def load_class_from_path(path_and_class: str): """ Dynamically load a class from a module at the specified path Args: path_and_class: relative path where to find the module and its class name i.e. 'neo3.<package>.<package>.<module>.<class name>' Raises: ValueError: if the Module ...
76,710
def ROC(ds, count, timeperiod=-2**31): """Rate of change : ((price/prevPrice)-1)*100""" return call_talib_with_ds(ds, count, talib.ROC, timeperiod)
76,711
def install(): """ Install a gevent-based reactor. """ reactor = GreenReactor() from twisted.internet.main import installReactor installReactor(reactor)
76,712
def add_mutually_exclusive_groups(parser, groups): """ Add mutually exclusive groups to parser from list :param parser: parser to add groups to :param groups: list of dictionaries, each containing: 1. 'args': parameter to add_args 2. arguments to ArgumentParser.add_...
76,713
def get_xml_bones(document): """ This function returns the "bones" of an XML document, replacing all the text-data and attribute values with a round(length) For example: <xml></xml> ---> xml0/xml <xml>hello</xml> ---> xml0/xml <xml attr=123>he...
76,714
def write_d_reach_to_table(tup_max_dc, tup_ang_threshold, input_dir, output_dir, filename, write_ddl=False): """Conduct directional reach analysis for the map stored in a CSV file. :param tup_max_dc: a tuple of the maximum number of direction changes allowed :param tup_ang_threshold: a tuple of the ang...
76,715
def test_unbalanced_exception(): """Ensure the tokenization fails on unbalanced expressions""" try: tokenize("(bar))") assert True is False except LexException: pass try: tokenize("(baz [quux]])") assert True is False except LexException: pass
76,716
def main(): """ Install corefonts, dx9. Set to win7 and override msdmo """ log('Applying fixes for Battlefield: Bad Company 2') # https://github.com/ValveSoftware/Proton/issues/200#issuecomment-415905979 util.protontricks('win7') util.protontricks('corefonts') util.protontricks('directx9')...
76,717
def graph_encoder_layer(enc_input, # (batch_size, n_block, emb_dim) attn_bias, # (batch_size, n_head, n_block, n_block) graph_attn_bias, # (batch_size, n_head, n_block, n_block) pos_win, n_head, d_...
76,718
def trim_doc(doc): """ Strips indentation from a docstring; also removes leading and trailing blank lines. `doc`: ``str`` or ``None`` A docstring. """ assert isinstance(doc, maybe(oneof(str, unicode))) # Pass `None` through. if doc is None: return None # Convert to...
76,719
def initialize_concept_scheme(rdf, cs, label, language, set_modified): """Initialize a concept scheme: Optionally add a label if the concept scheme doesn't have a label, and optionally add a dct:modified timestamp.""" # check whether the concept scheme is unlabeled, and label it if possible lab...
76,720
def abbreviate_id(a_string): """ 1. Hack off the first 6 and the last 4 characters. 2. Then join them with an ellipsis. :param a_string: :return: An abbreviated id string """ return str(a_string[0:6]+'...'+a_string[-4::])
76,721
def checkenv(): """ ensures the environment is configured correctly """ missing = [] r_fields = [ "REDIS_PORT", "REDIS_HOST", "REDIS_DB", "REDIS_USER", "REDIS_PASSWORD", ] for field in r_fields: if not os.getenv(field): missing.appe...
76,722
def isbn(value: str) -> T.Union[T.Match[str], None]: """ Matched isbn 10 or 13 Example: 978-1-4302-1998-9 1–931836–59–0 1593270127 0 321 15420 7 978-0-07-162612-5 Detail: https://en.wikipedia.org/wiki/International_Standard_Book_Number """ _isbn_pat = r'((...
76,723
def test(net, testloader): """Validate the network on the entire test set.""" criterion = torch.nn.CrossEntropyLoss() correct, total, loss = 0, 0, 0.0 with torch.no_grad(): for data in testloader: images, labels = data[0].to(DEVICE), data[1].to(DEVICE) outputs = net(image...
76,724
def reverse_integer(x): """Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0. :type x: int :rtype: int """ x_string = str(x) if x_string[0] == "-": # in case t...
76,725
def _convertbits( data: typing.Iterable[int], from_bits: int, to_bits: int, pad: bool ) -> typing.Optional[typing.List[int]]: """General power-of-2 base conversion.""" acc = 0 bits = 0 ret = [] maxv = (1 << to_bits) - 1 max_acc = (1 << (from_bits + to_bits - 1)) - 1 for value in data: ...
76,726
def check_fh(fh, enforce_relative=False): """Validate forecasting horizon. Parameters ---------- fh : int, list, np.array, pd.Index or ForecastingHorizon Forecasting horizon specifying the time points to predict. enforce_relative : bool, optional (default=False) If True, checks if f...
76,727
def test_R7T15(capsys): """Additional test Testing R7T15: agent can transfer more then $10000.00 Arguments: capsys -- object created by pytest to capture stdout and stderr """ helper( capsys=capsys, terminal_input=['login', 'agent', 'transfer', '1234567', '2345678', '2000000'...
76,728
def should_install_lzo(): """ Return true if lzo is enabled via core-site.xml and GPL license (required for lzo) is accepted. """ config = Script.get_config() io_compression_codecs = default("/configurations/core-site/io.compression.codecs", None) lzo_enabled = io_compression_codecs is not None and "com.had...
76,729
def make_dir(path): """ Create a directory recursively, if it does not exist. """ if not os.path.exists(path): os.makedirs(path)
76,730
async def handle_equipment_history(cursor, eid, edit, content): """ 写入equipment history """ await cursor.execute(E_CMD, (eid, content, edit))
76,731
def optimal_compatible_subset(requests): """ Get optimal weighted subset Uses dynamic programming to get the subset of the requests with the largest weight """ dp_weights = dict() dp_subsets = dict() finishes = {r.finish for r in requests} while finishes: x = max(finishes) finishes.remove(x)...
76,732
async def load_accounts(db, names): """`get_accounts`-style lookup for `get_state` compat layer.""" sql = """SELECT id, name, display_name, about, reputation, vote_weight, created_at, post_count, profile_image, location, website, cover_image FROM hive_accou...
76,733
def test_mode_sample_regex_csv(eventgen_test_helper): """tTest sample mode with a regex wildcard pattern in the stanza name ('sample*')""" events = eventgen_test_helper("eventgen_sample_regex_csv.conf").get_events() assert len(events) == 20
76,734
def imgMakeMask(inImg, threshold=None, forgroundValue=1): """ Generates morphologically smooth mask with given forground value from input image. If a threshold is given, the binary mask is initialzed using the given threshold... ...Otherwise it is initialized using Otsu's Method. """ if thr...
76,735
def test_validate_test4(): """ Test to make sure that if the 'user' is empty throw an exception. """ jobs = { "testjob": { "executable": "testexec", "executableargs": "arg1 arg2 arg3", "host": "login.machine.ac.uk", "user": "", "remot...
76,736
def test_to_graph_should_return_skolemization(mocker: MockFixture) -> None: """It returns a choice graph as blank node isomorphic to spec.""" choice = Choice() mocker.patch( "skolemizer.Skolemizer.add_skolemization", return_value=skolemization, ) src = """ @prefix dct: <http://purl...
76,737
def fetch_vacancies(keyword, town=None, catalogues=None, currency=None, period=0, page=0, count=100): """Fetch vacancies from SuperJob API, return in json. Args: keyword (str): search the specific vacancies by keyword town (int, optional): search vacancies by area. Def...
76,738
def OpenDictionary(filenames): """Reads the dictionary into a list """ print("Opening the Chinese Notes dictionary") words = [] for dictfile in filenames.split(","): with codecs.open(dictfile, 'r', "utf-8") as f: for line in f: line = line.strip() if not line: continue ...
76,739
def test_check_nela_data_categories( initial_df_fixture: pd.DataFrame, initial_df_specification_fixture: dict ): """Test that check_nela_data_categories() raises an AssertionError when expected categories are absent from NELA data. initial_df_fixture only has a small number of rows so rare c...
76,740
def launch_cooja(name): """ Fabric command to launch an experiment """ path = update_script(name) from importlib.machinery import SourceFileLoader SourceFileLoader(name, path).load_module().launch_cooja()
76,741
def api_request(url, api_key=None): """ This function takes a url and returns the parsed json object. If necessary, it submits the auth header """ if api_key: return requests.get(url, headers={'Authorization': 'Token ' + api_key}).json() else: return requests.get(url).json()
76,742
def get_device(gpu_idx: int = 0) -> torch.device: """ Get default gpu torch device. :param gpu_idx: :return: """ device: torch.device = torch.device(f"cuda:{gpu_idx}" if torch.cuda.is_available() else "cpu") # device: torch.device = torch.device(f"cuda:0" if torch.cuda.is_available() else "...
76,743
def main(cmdline): """main(cmdline) -- process cmdline as if it were sys.argv""" # parse options/files options = [] optvalues = {} for opt in cmdline[1:]: if opt.startswith('-'): if ':' in opt: k, v = tuple(opt.split(':', 1)) optvalues[k] = v ...
76,744
def subjects(subjects=None, recursive=False, include_tables=False, lang=DEFAULT_LANGUAGE): """List subjects from the subject hierarchy. If subjects is not given, the root subjects will be used. Returns a generator. """ request = Request('subjects', *subjects,...
76,745
def getGOState(*args): """Access protected class data to evaluate if the Fuel, Liquid Oxygen (LOX), and Control Panel system state are a 'GO' as a 1 by 3 numpy array. This approach is a secure method to access saved system state values. If the system sensor values are all nominal and all three controller panels ope...
76,746
def assert_array_equal(x: numpy.ndarray, y: List[List[Union[int, float]]]): """ usage.orange3: 2 usage.scipy: 2 """ ...
76,747
def interpolate(src, trg, vals, Interpolator, *args, **kwargs): """ Convenience function to use the interpolation classes in an efficient way The interpolation classes in wradlib.ipol are computationally very efficient if they are applied on large multi-dimensional arrays of which the first d...
76,748
def CreateTemplateFile(source, patch, dest): """Creates a single PPAPI template file. Args: source: The path source file to create from. patch: The path to the patch file to apply. dest: The path to the file to create. Returns: None. """ source_xml = ElementTree.parse(source) patch_xml = El...
76,749
def cluster_commit(): """ Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit """ ret = {"comment": "", "success": False} cmd = __execute_cmd("riak-admin", "cluster commit") if cmd["retcode"] != 0: r...
76,750
def get_map_from_sqlalchemy(a_object): """A SQLAlchemy utility to make a dictionary out of an object""" # this can be done at the front-end side using node.js and JS # if the programming was done at the front-end from sqlalchemy import inspect # A variable assigned to the SQLAlchemy object inspect...
76,751
def get_tick_data(code=None, date=None, retry_count=3, pause=0.001, src='sn'): """ 获取分笔数据 Parameters ------ code:string 股票代码 e.g. 600848 date:string 日期 format: YYYY-MM-DD retry_count : int, 默认 3 ...
76,752
def DeletePlayer(request, callback, customData = None, extraHeaders = None): """ Removes a user's player account from a title and deletes all associated data https://docs.microsoft.com/rest/api/playfab/server/account-management/deleteplayer """ if not PlayFabSettings.DeveloperSecretKey: rais...
76,753
def config_template_files(): """ Fixture for the config template files """ template_file = { "input": TEST_DATADIR / "templates/config/sparcc.j2", "output": TEST_DATADIR / "templates/config/sparcc.config", } data = { "compute_correlations": {"niters": 10}, "resampling": {...
76,754
async def destroy_tournament(message, connection): """ Destroy a Challonge tournament Args: "Tournament Name" """ content = message.content[18:] # ^bot admin destroy $ # Extracting tournament name if "-name" in content: t_name = content.split("-name")[1][1:] else: t_name = " ".join(content.split(" ")[0]...
76,755
def add_expenses_to_db(file_path): """ Añadir facturas recibidas a la base de datos. En caso que no se pase un fichero, lo va a buscar al directory de entradas con el nombre 'factura_recibidas.csv'. """ if file_path == '': add_expenses('facturas_recibidas.csv') else: add_expens...
76,756
def normalize_ascii(j_string): """ Normalize a double-width ascii string, converting all characters to their single-width counterparts. :param six.text_type j_string: The string to convert. :return: The converted string. """ result = [] for char in j_string: ...
76,757
def part_2(data: list[str]) -> int: """ Figure out the sequence of closing characters for incomplete lines. Start with a total score of 0. Then, for each character, multiply the total score by 5 and then increase the total score by the point value given for the character. Returns middle sco...
76,758
def test_basic_iteration(): """Test that the :class:`~polymatheia.data.NavigableDictIterator` follows the basic iterator protocol.""" it = NavigableDictIterator(iter([{'a': 1}, {'a': 2}, {'a': 3}])) count = 0 for record in it: assert isinstance(record, NavigableDict) assert record.a is n...
76,759
def checkfile(file): """Checks file to to make sire itsx and itsxpress exited with an exit code of O and that ITSx did not throw a fatal error message Args: file: data file path Returns: Bool: True Raises: AssertError: if two lines with Exit Status 0 are not present ValueError: if ITSx returned a fatal...
76,760
def product(id): """Display selected product""" if request.method == "GET": product = db.session.query(Product).get(id) addons = db.session.query(ProductAddon).all() return render_template("product.html", error=check_error(), user=session, addons=addons, product=product) else: # Edit...
76,761
def debug_log(function): """Output debug information to the logger for a function call.""" argument_names = list(function.__code__.co_varnames) @functools.wraps(function) def write_log(*args, **kwargs): argument_values = ( "{} = {}".format(arg, value) for arg, value in l...
76,762
def is_string(s): """Check if the argument is a string which works for both Python 2 and 3.""" try: return isinstance(s, basestring) except NameError: return isinstance(s, str)
76,763
def retry(exception_to_check, attempts=3): """Decorator to retry a function upon exception. If the decorated function emits an exception that matches exception_to_check, the function will be repeated. This will happen a maximum of 'attempts' times. If none of the attempts were successful, this function raises ...
76,764
def get_all_task_queue(): """返回所有原子队列的key 返回类型:list """ task_queue = "ztq:queue:task:" return get_keys(task_queue)
76,765
def build_ami(configfile): """Build an EC2 instance AMI from the given config file. Build an AMI for Batch use with EFS. Common cloudformation infrastructure must already be deployed. """ config = yaml.load(configfile) if len(config["SubnetsPublic"]) != 2: raise ConfigError("Exactly 2 p...
76,766
def test_basic_install_relative_directory(script, data): """ Test installing a requirement using a relative path. """ egg_info_file = ( script.site_packages / 'FSPkg-0.1.dev0-py%s.egg-info' % pyversion ) egg_link_file = ( script.site_packages / 'FSPkg.egg-link' ) package_...
76,767
def print_permissions(permissions): """Prints out a users permissions""" table = formatting.Table(['keyName', 'Description']) for perm in permissions: table.add_row([perm['keyName'], perm['name']]) return table
76,768
def _download_to_dir(url, out_fname, dirname, version, cur_version): """ Grab an annotation file and place in /usr/share/gemini/data """ print "* downloading " + url + " to " + dirname + "\n" dest = os.path.join(dirname, out_fname) if not os.path.exists(dest) or version > cur_version: # ...
76,769
def delete_environment(environmentId=None): """ Deletes an AWS Cloud9 development environment. If an Amazon EC2 instance is connected to the environment, also terminates the instance. See also: AWS API Documentation Exceptions Examples Expected Output: :example: response = client.d...
76,770
def create_cloud_xyz32(header, points): """ Create a sensor_msgs.msg.PointCloud2 message with (x, y, z) fields. :param header: The point cloud header. (Type: std_msgs.msg.Header) :param points: The point cloud points. (Type: Iterable) :return: The point cloud as sensor_msgs.msg.PointCloud2. """...
76,771
def _test_buffered_generator_general2( bgfunc, bgargs, fgfunc, target_looptime=1.0, serial_cheat=1, buffer_size=2, show_serial=True, ): """ # We are going to generate output of bgfunc in the background while # fgfunc is running in the foreground. fgfunc takes results of bffunc as...
76,772
def cast_in_array(arg): """casts argument into np.array""" if isinstance(arg, np.ndarray): return arg msg = f"Can not cast type({type(arg)}), {arg} in array of floats.\n" try: arr = np.array(arg) except Exception as exc: raise exc(msg) arr = np.array(0) if not ...
76,773
def test_StatistiCALSolutionModel(file_path="Solution_Plus.txt"): """Tests the StatistiCALSolutionModel""" os.chdir(TESTS_DIRECTORY) new_solution=StatistiCALSolutionModel(file_path) print(("The solution's column names are {0}".format(new_solution.column_names))) print(("The solution is {0}".format(n...
76,774
def check_login() : """ check if the user is correctly logged. This function is called everytime a user function is called """ if not session.get('workspace_contract') and not session.get('username') : abort(403) return True
76,775
def validator_key(validator_account_and_key): """Private key of the validator running the confirmation sender.""" _, key = validator_account_and_key return key
76,776
def nn50(nni=None, rpeaks=None): """Find number of NN interval differences which are greater 50ms (NN50) and ratio between NN50 and total amount of NN intervals. References: [Electrophysiology1996], [Ewing1984] Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/time.html#nn50-nn50 Parameters ---------- n...
76,777
def get_random(file_handle: typing.TextIO, length: int = 32) -> bytes: """Request random bytes from /dev/nsm.""" if length < 1 or length > 256: raise ValueError('GetRandom supports length between 1 and 256 inclusive.') nsm_key = 'GetRandom' request_data = cbor2.dumps(nsm_key) # Prepare the...
76,778
def write_chunk_unique_ids(mapping, storagestr, chunk_bounds): """Writes a mapping from chunk ids to unique ids""" dframe = make_dframe_from_dict(mapping) if io.is_db_url(storagestr): tag = io.fname_chunk_tag(chunk_bounds) dframe["chunk_tag"] = tag io.write_db_dframe(dframe, storage...
76,779
def rx_mode_teardown(device, monitor): """Teardown rx_mode.""" system("ifconfig %s down" % monitor) system("iw dev %s del" % monitor) system("ifconfig %s up" % device) # TODO add old interface
76,780
def main(_): """Entry point for script, converts flags to arguments.""" label_wav(FLAGS.wav, FLAGS.audio, FLAGS.labels, FLAGS.graph, FLAGS.input_name, FLAGS.output_name, FLAGS.how_many_labels)
76,781
def do_exit(p_msg): """ Hard exits the application. p_msg: Exit message to print. """ sys.exit(p_msg)
76,782
def todataframe(table, index=None, exclude=None, columns=None, coerce_float=False, nrows=None): """ Load data from the given `table` into a `pandas <http://pandas.pydata.org/>`_ DataFrame. E.g.:: >>> import petl as etl >>> table = [('foo', 'bar', 'baz'), ... ...
76,783
def load(instream, where=None): """Load a Windows .FON file.""" data = instream.read() mz_header = _MZ_HEADER.from_bytes(data) if mz_header.magic not in (b'MZ', b'ZM'): raise FileFormatError('MZ signature not found. Not a Windows .FON file') ne_magic = data[mz_header.ne_offset:mz_header.ne_o...
76,784
def trace_predicate (predicate_name, partition, out_path): """ TODO: migrate this into `kglab` for unit tests """ df = model.get_predicate(predicate_name)._data[partition] df.columns = [ "P1", "P2", "value" ] df = df.sort_values(by=[ "P1", "P2" ]) df.to_csv(out_path, sep="\t", index=False) ...
76,785
def test_calc_logp_marginal_likelihood(): """ Implemented in `tests/test_model/test_model_inference.py`. """ pass
76,786
def api_get_instances_by_nemea_module_name(module_name): """ Returns instances of given NEMEA module """ # verify that module exists nm_model.get_by_name(module_name) insts = i_model.get_by_nemea_module_name(module_name) return json_resp(insts)
76,787
def test(): """ Test function for module testing Run 'run_before_close_gravity' only Go to gazebo to close the gravity Then run 'move_camera_without_process' for several times Then go to gazebo to open the gravity(fetch will fly, ignore this temporarily,I'll fix it later) ...
76,788
def dispatch_value(default_func): """Decorator to select a function implementation according to the value of its fist parameter""" registry: Dict[type, Callable[..., Any]] = {} default: Callable[..., Any] = default_func def register(value: Any): """Registers the decorated function f as the impl...
76,789
def run_retrohunt(http_session: requests.AuthorizedSession, version_id: str, start_time: datetime.datetime, end_time: datetime.datetime) -> Mapping[str, Any]: """Run a retrohunt. Args: http_session: Authorized session for HTTP requests. version_id: Unique ID of the detec...
76,790
def calc_theta(pref_cood, local_connectivity_dic, xt=139.69167, yt=35.68944): """ Returns array of the bearing of a linke between two prefectures. Parameters ---------- pref_cood : dict[str, Tuple[float, float]] Dictionary of coordinates of all 47 prefectures. local_connectivity_dic : dic...
76,791
def assets_decrypt(ctx, did): """ Decrypt asset service """ response = ctx.obj['ocean'].decrypt(did) echo(response)
76,792
def encode_int(value): """ Encode integer value into RLP format :param value: int value :return: RLP encoded bytes """ if value == 0: s = b"" else: s = int_to_big_endian(value) if len(s) == 1 and safe_ord(s[0]) < 128: return s return get_length_prefix_str(...
76,793
def project_create(project): """Create a project. If the project already exists, a DuplicateError will be raised. """ db = model.Session() _assert_absent(db, model.Project, project) project = model.Project(project) db.add(project) db.commit()
76,794
def ext_vnet(test_vars): """ Creates a resource group containing a new VNET, subnet, public IP, and jumpbox for use in other tests. """ log = logging.getLogger("ext_vnet") vnet_atd = ArmTemplateDeploy( location=test_vars["location"], resource_group=test_vars["atd_obj"].deploy_id ...
76,795
def khtrack(df:pd.DataFrame, kh:(list,str)=None, lims:list=None, dtick:bool=False, fill:bool=True, ax=None, fontsize: int=8, grid_numbers : list = [11,51], steps: list = None, correlation: pd.DataFrame = None...
76,796
def ood_detection(y_hat: Prediction, _, y_hat_ood: Prediction, __, score_type: str = 'AUROC', uncertainty_type: str = 'aleatoric') -> Tensor: """convenience function which computes the OOD APR/AUROC scores from model predictions on ID and OOD data based on estimates of 'aleatoric' or 'epistemic' u...
76,797
def summer_start(timestamp): """ Returns 00:00:01 on the Sunday following the 2nd Saturday of April for the year given in «timestamp», which is the end of Piedmont's Summer period. """ year = timestamp.year apr_7th = datetime(year=year, month=4, day=7, second=1) dow = apr_7th.weekday() i...
76,798
def PP(obj, indent=4, width=80, depth=None, c=None, b=None, a=None): """ Pretty-print colorized python object. indent amount of indentation added for each recursive level depth number of levels which may be printed width desired output width c, b, a see C(). """ tex...
76,799