content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def rotate(password, rotate_type, *params): """Rotate password - rotate left/right X steps - means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc. - rotate based on position of letter X - means that the whole string should be rotat...
5b8248d56b1143a2d1ac41e890645649c6a434f5
648,664
def calc_max_length(tensor): """ find the maxinum length of any caption in our dataset :param tensor: an array with shape (n,m) :return: """ return max(len(t) for t in tensor)
7c13c80423c1328dac7b80bc590f153da4e425a8
648,665
from typing import OrderedDict def point_asdict(search_space, point_as_list): """Convert the list representation of a point from a search space to the dictionary representation, where keys are dimension names and values are corresponding to the values of dimensions in the list. .. seealso:: :class:`s...
f59aba0e6f64d93de31c9d7844f8e87e2c4eea70
648,666
def split(arr, n_devices): """Splits the first axis of `arr` evenly across the number of devices.""" return arr.reshape(n_devices, arr.shape[0] // n_devices, *arr.shape[1:])
204cb478ee4c39169c5142111842445e806845a1
648,667
def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (elemen...
26de771b5d1f5b0d8a255bd8cfbdbee314724dff
648,668
import optparse def _ParseOptions(): """Parses command-line options.""" parser = optparse.OptionParser(usage="%prog [options] [builders]") parser.add_option("-m", "--max_builds", type="int", default=-1, help="Maximum number of builds to check for each builder." ...
05952569ec98eb27e503e89fd2329c2f45017cd3
648,669
def find_root(node): """ Find the root of the current node. :param node: :return: """ current = node while current.parent: current = current.parent return current
4b0821e52af8c05321cf9d2a58ebcbe7df41cd29
648,670
def de_standardize(x, mean_x, std_x): """Reverse the procedure of standardization.""" x = x * std_x x = x + mean_x return x
3c69471f8fbf2bfe9a4b3da26b156acb814a7c13
648,672
import json import importlib def get_wechat_clients(value: str): """A list of WeChat clients, the value can be a JSON string like this: [ { "AppID": "...", "AppSecret": "...", "Type": "gapp_login.wechat.MiniProgramClient" } ] """ clients = json.l...
2ad51a400c02e88b94e2490f3b7510dc9ded6abb
648,674
def _strip_empty(d): """Strips entries of dict with no value, but allow zero.""" return { k: v for k, v in d.items() if v or (type(v) == int and v == 0) or (type(v) == str and v == "") }
57be868273b3d5e47cbf360c6df6e0eec238cf28
648,675
def adapt_param(p: float, p_min: float, p_max: float, d: float, d_target: float, xi: float ) -> float: """ Self adapts a param p given a measure m and control xi Args: p (float):...
f3d0b63aee18f8b5143aee81b4146acefbe76d26
648,676
from numpy.polynomial import Polynomial as P from numpy import isreal def irr(CashFlow, all=False): """ irr - Internal Rate of Return :param CashFlow: A list with the cash flow stream :return: A list containing the internal rate of return Example: >>> irr([-100000, 10000, 2...
109d8864c260c2874e7626bb2c35eabf23c49654
648,677
def repeated_argument(e: SyntaxError) -> str: """Generates a feedback for a repeated keyword argument error. Parameters ---------- e : SyntaxError the error object Returns ------- str feedback message """ msg = "I couldn't parse your function call because I got a re...
7022e891d1780f10def78376deb8a6f79dce6dfc
648,678
import argparse def argumentSetup(): """set up the commandline args""" parser = argparse.ArgumentParser(description="A Swiss-German dependency parser based on TurboParser") parser.add_argument('inputFile', help="The input text file, usually a normal text file encoded in utf-8") parser.add_argumen...
95e155ad7511de4366d1c057b1af343492749f0e
648,679
def is_up(gaze): """Returns true if the user is looking to the up""" if gaze.pupils_located: return gaze.vertical_ratio() <= 0.3
375942671b5f47a1cbc0c7d3f9ea9b6d7d12e081
648,680
def crcJK232(byteData): """ Generate JK RS232 / RS485 CRC - 2 bytes, the verification field is "command code + length byte + data segment content", the verification method is thesum of the above fields and then the inverse plus 1, the high bit is in the front and the low bit is in the back. """ ...
8ced1a29208fa298d294ecd2eedb8c75019108c2
648,681
def _Cond(test, if_true, if_false): """Substitute for 'if_true if test else if_false' in Python 2.4.""" if test: return if_true else: return if_false
18b5f69c0a8087753d8790a9d96c6e1d74e989b1
648,682
def is_within_cabal(module, cabal=None): """ Returns whether module loaded from cabal specified """ return cabal is not None and module.cabal == cabal
ae689431b4b963c792c1acdb0e5f39d74d8e2600
648,683
def euclids_formula(m, n): """ """ assert type(m) is int, "" assert type(n) is int, "" a = m*m - n*n b = 2*m*n c = m*m + n*n return (min(a, b), max(a, b), c)
420a17345f7a9b6e4133ed963e3abfbb6e5bce7b
648,684
def dictfetchall(connection, sql, *params, **kwargs): """ Return all rows from a cursor as a dict, if kwargs.get("format") == 'list', return as list """ with connection.cursor() as cursor: cursor.execute(sql, params) columns = [col[0] for col in cursor.description] if kwargs.get("...
6f1ff2fe0fc1a21d76a7f761c85fc5a65dc505e2
648,685
import numpy def classification_rate(ground_truth, classified, verbose=False): """ Computes the classification rate (i.e., fraction of samples correctly classified) Args: ground_truth (list or 1-dim ndarray): ground truth classes. Assumed to be integer. classified (list or 1-dim ndarray)...
4d6b3dfd6091c725212601f10ae5625aa00fa4f9
648,686
def get_video_shape(params, is_space_to_depth=False): """Returns exact video shape as model's input.""" if is_space_to_depth: video_shape = [params.num_frames // 2, params.frame_size // 2, params.frame_size // 2, 24] else: video_shape = [params.num_...
ede7857e0a41c869c61472e344ca97266949e352
648,687
def search_again(): """ Gives the option to search again if wanted. Parameters ---------- None Returns ------- int | function() Either 1 if we want to search again o quit() if we do not want to search again. """ while True: choice = input("Would you like...
654a5bf014378660b3c38e854983ae51f3691ec0
648,688
def remove_doublequotes(x:list): """ removes double quotes from list """ x_cleaned=[el.replace("'",'') for el in x] return x_cleaned
d663d1cbde55981f912aa5a8b6614138e418f342
648,689
import json def make_request_callback(timeout_count, body_on_success, http_error_status=504): """Make a request callback that timeout a couple of time before returning body_on_success. Returns: A tuple (request_callback, attempts), attempts is an array of size one ...
17d19e19c16a13a657adac04f60eb150ad84a846
648,691
import os import re def gulp_relax_finish_ok(dot_castep): """Check the relaxation of gulp_relax""" if not os.path.isfile(dot_castep): return False with open(dot_castep) as fh: content = fh.read() mathch = re.search(r'Final Enthalpy += ([-e0-9\.]+)', content) if mathch: re...
f584f1603a69a4c17b8553a4cbe3f70d22db7b7e
648,692
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since ...
a0c7c7c920dca18811c25a81081b8dee1c8b35db
648,693
def factorial_recursive(num): """returns the factorial of num using a recursive method.""" if num == 1: return 1 return num * factorial_recursive(num -1)
430c93f14484bb8bfaa4581279b10daa79614e85
648,694
import time def timed(func): """ This decorator adds a timer to the decorated function. The original function results and the timer results are returned as a tuple of size 2 :param func: the function to decorate :return: decorated function """ def timed_method(*args, **kwargs): sta...
2bcedf03a8dff9021a2404094cfd39b5f81b44d5
648,697
def get_min_max_t_per_patient(df_patient, col='vol in ml', target_col='t_norm'): """ Helper to get min/max of one columns returns a dict with {patient: 123abc , min: timestep as int, max: timestep as int}""" result = dict() patient = df_patient['patient'].unique() assert len(patient) == 1, 'mo...
972bdb16253b3e6f28a194c56494a4a030d317cb
648,698
import ipaddress def validate_server_domain_name(server, domain_name): """ Validates the server and domain_name variables Args: server (str) : string of an IP address to test the domain against domainname (str) : string for the domain to test against Return: tuple...
bd89437afefcd585ce240123580f35547a9ee758
648,699
def fit_predict_for_chain(chain, train_input, predict_input): """ Function apply fit and predict operations :param chain: chain to process :param train_input: InputData for fit :param predict_input: InputData for predict :return preds: prediction of the chain """ # Fit it chain.fit_fro...
10677b0395170125dd8691179fc03a631721e8e8
648,700
import copy import torch def average_weights(w): """ Returns the average of the weights. """ w_avg = copy.deepcopy(w[0]) for key in w_avg.keys(): for i in range(1, len(w)): w_avg[key] += w[i][key] w_avg[key] = torch.div(w_avg[key], len(w)) return w_avg
abe276fa8ad9cfd6114671d7b6727c0a9684f84a
648,701
def busquedaBinaria(numero, lista): """ Esta busqueda no me devuelve la posisicion en el array original pero me devuelve un entero positivo si es que el valor se encuentra y -1 caso contrario """ listaTemp = lista medio = len(lista) while medio >0: n = len(listaTemp) medi...
841caf4228e3cd30159da2ccc31f95dcbdc11756
648,702
from typing import List def ListIntToSequence(l: List[int], separator: str = '.') -> str: """Merge [192,168,42,1] to '192.168.42.1' Returns: str: int join with sep """ return separator.join(str(x) for x in l)
512322e923192ed13a6d0e99abe2a2e921d4bbc3
648,703
import os def checkEnvironVariable(variable_name): """ Checks the definition of some environment variable specifying directory. Returns the path to that directory. """ try: var = os.environ[variable_name] except KeyError: raise OSError("Environment variable %s not defined!" % ...
b648bcde422f875af9cb64587288154403bf1319
648,704
def get_exec_command_python(language_cmd: str, in_file_path: str) -> str: """ Function which provides the execution command for an upcoming python execution @param language_cmd: base language command, in this case "python" @param in_file_path: file where the input code will exist @return the execu...
8b273054be14865d5a74b97b6fc40b5742a00652
648,707
import yaml def read_config(config, key=None): """Read a config file and return the right configuration.""" print("INFO: Loading configuration from", config) config = yaml.load(open(config, 'r'), Loader=yaml.SafeLoader) if key is not None: if key in config: print("INFO: Using the '...
dcedb58a0d97653f53c9fb93abc67f25e8e6a6dc
648,708
import os def in_dir(f): """Go to a specified directory before executing the function and then return to the original directory. """ def wrapper(self, *args, **kwargs): start = os.getcwd() os.chdir(self.dirpath) try: return f(self, *args, **kwargs) finally:...
08a6b099ac54a75bec198cb1858c91f84d4e3b9d
648,709
def get_user_display_name(u): """Get `display_name` for a user Args: u: user Returns: A string example: 'Donald J. Trump' """ name = [] if u.first_name: name.append(u.first_name) if u.last_name: name.append(u.last_name) return '|'.joi...
01aaefc0de548784f864501d2c8e6541ed125767
648,710
def devices_json(): """Define a response to /v1/devices.""" return [ { "last_connected_at": "2019-12-16T01:35:52.971Z", "address": { }, "firmware_version": "0030", "name": "Home", "type": "bridge", "battery": None, "image_url": "https://s3-us-west-2.amazonaws.com/orbit-irrigati...
8dd573423d3472b9ce936d6a8e940300c68e6a9a
648,711
def get_random_ingredients(kind=None): """ Return a list of random ingredients as strings. :param kind: Optional "kind" of ingredients. :type kind: list[str] or None :raise lumache.InvalidKindError: If the kind is invalid. :return: The ingredients list. :rtype: list[str] """ return...
3bfc65d6759286d41fd60191e889a8edb61085e3
648,712
def init_rna_dna(): """Return [enthalpy, entropy] list in kcal/mol and cal/(mol*Kelvin) for RNA/DNA duplex initiation. Values from Sugimoto et al 1995 """ initH = 1.9 # kcal/mol initS = -3.9 # cal/(mol * Kelvin) return [initH, initS]
110a790389c593b3f5de1ee327b5306bb752e630
648,713
def positions_sync_out_doc_template_values(url_root): """ Show documentation about positionsSyncOut """ required_query_parameter_list = [ { 'name': 'format', 'value': 'string', # boolean, integer, long, string 'description': 'Currently must be...
ba4a0ebb962230a0872b45409d52e8ecb061bc92
648,714
def launch_label(cfg): """Returns a label based on how far the piepline has progressed""" order = ["Initial", "Classify", "Post", "Upload", "Debase", "RM", "RVM_initial", "RVM_final", "Finish"] counter = sum(cfg["completed"].values()) # Number of True statements return order[counter]
391f0fd678d89935fa0f1facd9bc09dbfbeee1a6
648,715
import base64 import hashlib def make_hash_string(string, output_length=10): """Create a hash for given string Truncates an md5 hash to the desired length. Will always be safe for file names. Args: string (str): input string output_length (int): length for output Returns: ...
0982d6478d781a2d0e86b7ada2d7c12768c0214d
648,716
def dot_prod(a,b): """ This function takes two vectors, a and b, and finds the dot product,c. """ c = a[0]*b[0] + a[1]*b[1] + a[2]*b[2] return(c)
41724465bb8dc9d0bd154fbb5b41be4bcdfd5ff7
648,717
def drop_msg(module_name, module_package): """ Create info message for dropped modules. """ if module_package is not None: ignore_msg = "drop %s (in %s)" % (module_name, module_package) else: ignore_msg = "drop %s" % module_name return ignore_msg
e56461cbb6a195babd3d8038654df1d3ffb57bbe
648,721
def format_coverage_line(text, statements, missed, coverage, missed_lines=False): """Format one line with code coverage report of one class or for a summary.""" format_string = "{:80} {:3d} {:3d} {:3d}%" if missed_lines: format_string += " N/A" return format_string.format(text, statements...
a274ad021f1e12171c28ab5e218c93930120d55b
648,722
def extract_7z(archive, compression, cmd, verbosity, interactive, outdir): """Extract a 7z archive.""" cmdlist = [cmd, 'x'] if not interactive: cmdlist.append('-y') cmdlist.extend(['-o%s' % outdir, '--', archive]) return cmdlist
243a473657306866cb5a4d860c9ae6e48d4d3de6
648,724
def find_failed_results(run_artifacts: dict) -> list: """find the index and ID for which elements failed in run Args: run_artifacts (dict): dbt api run artifact json response Returns: list: list of tuples with unique id, index """ failed_steps = [] for index, result in enumera...
43333b823841ce84543319e64293ca233ea7d920
648,725
def _check(value,x,y): """ Check if a value is between x and y Parameters ---------- value : float Value of interest. x : float Limit x. y : float Limit y. Returns ------- int Numerical bool if value is between limits x and y. """ if x <...
43b09200577497793bf90649be990f55b2119452
648,726
def d2l(dx, fc, i): """ second-order left-sided derivative at index i """ D = -fc[i+2] + 4.0*fc[i+1] -3.0*fc[i] D = D/(2.0*dx) return D
0e2664d4ef6e17e98173c57aec66e805e0095723
648,728
from typing import Tuple def custom_ravel(tup: Tuple[int, int], shape: Tuple[int, int]) -> int: """Ravel indexes for 2D array. This is a jitted function, equivalent to the `numpy` implementation of `ravel_multi_index`, but configured to accept only a single tuple as the index to ravel, and only works...
31741efb20dd22b1512b9ff3287d1bb56ded33ba
648,730
import numpy def STmag_from_flux( v ): """ Convert to ST magnitude from erg/s/cm2/AA (Flambda) mag = -2.5 \log_{10}(F) - 21.10 M0 = 21.10 F0 = 3.6307805477010028 10^{-9} erg/s/cm2/AA Parameters ---------- v: np.ndarray[float, ndim=N], or float array of fluxes ...
0165b481c9eca48916f8208ca7770c382232e23d
648,731
import sys def nbytes(o): """ Number of bytes of an object >>> nbytes(123) # doctest: +SKIP 24 >>> nbytes('Hello, world!') # doctest: +SKIP 50 >>> import numpy as np >>> nbytes(np.ones(1000, dtype='i4')) 4000 """ if hasattr(o, 'nbytes'): return o.nbytes if hasa...
6fc2ac1138a3361bd7a16df8b47f62721569e47f
648,732
import torch def cat_arange(counts, dtype=torch.int32): """ Concatenate results of multiple arange calls E.g.: cat_arange([2,1,3]) = [0, 1, 0, 0, 1, 2] Credits: https://stackoverflow.com/a/20033438 :param torch.tensor counts: a 1D tensor :return: equivalent to torch.cat([torch.arange(c) for c...
61baf564bf03e7c0713ea2ef1b3ff9f08ae8949d
648,733
def _KindsListToTuple(get_schema_kinds_list): """Called to return default tuple when no datastore statistics are available. """ results = [] if get_schema_kinds_list: for kind_str in sorted(get_schema_kinds_list): results.append({'kind_name': kind_str}) return '', results
1c2ac0c0f5189aac6b97af469652ba0f11e518d0
648,734
def _basis_str(origin_shift): """Return the string to get the sgtbx basis_op for the given origin shift""" bstr = '' for i, axis in enumerate(['x', 'y', 'z']): if origin_shift[i] == 0.0: s = axis else: s = '{0}{1:+F}'.format(axis, origin_shift[i]) if i == 0: ...
e35a212b4ff1f1c822fe92e46f8d9b07767169a8
648,735
import logging def make_error_worker(name, error_service, error_q): """ Closure to make the end of line worker - for jobs the terminated with errors :param name: for context, such as error-worker-1 :param error_service: the error service that handles the errors :param error_q: to consume jobs from...
9fc5ee9b121a8bdf340fd36a308c0f60f1022769
648,736
def help_messages(definition): """ Returns a decorator that will apply help messages to all options in the CLI. It prevents missed and outdated help messages and allows options to be defined without the distraction of a long help message. """ def validate_params(params): help_params = ...
c04a9b062eceef2119b0c1accd93f073cacc9b03
648,737
def is_ends_with_underscore(value: str): """Does value end with underscore.""" if value == "": return False else: return value[-1] == '_'
19a1d9f117aa9804594ed05369aff73f07b753ea
648,738
def verify_operator(operator): """ Check that ``operator`` is one of the allowed strings. Legal operators include the following strings: - '=' - '<=' - '>=' - '<' - '>' - '<>' - 'like' - 'regexp' - 'is null' - 'is not null' EXAMPLES:: sage: from sage.da...
e3ade6551993e05e386ac1f992f52dacba15439a
648,739
import requests def _get_sid_bearer_token(auth_endpoint, credentials): """ :param auth_endpoint: :param credentials: :return: """ response = requests.post(auth_endpoint, json=credentials) response_json = response.json() return {"Authorization": "Bearer " + response_json["key"]}
41f9eb32f6b3e8a2a0df6020d5a86c8800a0d061
648,740
def str_to_float(source: str) -> float: """Converts a str to a float.""" return float(source)
05081e2155ffe33e03f60e0fb945cd110c1fc4ab
648,741
def test_2(self, request): """Test 2: Single database query""" return {'id': self.id, 'randomNumber': self.randomnumber}
5151eac846fd942bce2dbd26e91612519baa60ff
648,742
from pathlib import Path def default_pickle_file(): """Give the default path of the QNM dict pickle file, `<dirname of this file>/data/Schw_dict.pickle`. Returns ------- Path object `<dirname of this file>/data/Schw_dict.pickle` """ return Path(__file__).parent.resolve() / 'data' / 'S...
6be7e7a97aa909716a0e4e402fc6748028476cc0
648,743
def reorder_module_calls(lines): """ Reorder the module calls in the program For I/O module calls, we will reverse the sequence of calls for output modules. Starting from the first module, enlist the module calls until the boundary module is met. Reverse the list and print it. Parameters -...
895a4f0abab3c3f99d10ab44090549c9ac62f292
648,744
def get_parameter_list_from_request(req,parameter): """Extracts a parameter from the request. Parameters ---------- req : HttpRequest The HTTP request. parameter : str The parameter being extracted. Returns ------- List List of comma separated parameters. "...
4b9f66e64455229a998eb199a3fc890d2ba8ba02
648,745
def notify_upgrade(app, flash): """If a new version is available, notifies the user via flash that there is an upgrade to specter.desktop :return the current version """ if app.specter.version.upgrade: flash( f"Upgrade notification: new version {app.specter.version.latest} is ava...
01e5d2c3d6865a9dfafb61a3f7b8cd349ddb56c6
648,746
def serialize_recent_url(analysis, type_str): """Convert output of images to json""" tmp_output = [] output = {} if type_str == 'recentimages-thumbs': output['id'] = None output['type'] = type_str for e in range(len(analysis)): temp_obj = { 'source': a...
2c6a8440e77a008ad6b32e828a7fd3791c5f17bc
648,747
def hydra_app(category='import', name=None): """A decorator to mark a click Command as a Hydra app.""" def hydra_app_decorator(func): func.hydra_app_category = category func.hydra_app_name = name return func return hydra_app_decorator
6077fb1cc16fe3547b0277235d4c029ae5d3439d
648,748
import pickle def load_data(folder_path, file_name='/global_save.txt'): """unpickle the data file""" if '/' not in file_name: file_name = '/' + file_name file_path = folder_path + file_name try: data = pickle.load(open(file_path, "rb")) except: print('Make sure your par...
985d4823a57cc2a2d67f36e58ac21e935b8c88e4
648,751
import argparse def get_command_line_input(): """Read in the command line input""" parser = argparse.ArgumentParser("Basic parameters for TBG construct.") parser.add_argument('-m', '--num-vec1', dest='m', default=6, type=int, help='The less(n-1) one supercell length....
9cad8bcbf567498382a6aacaea9fe9bdc49d8cc4
648,752
import argparse def parse_arguments(): """ Parse command line arguments """ parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('checkpoint_path', type=str) parser.add_argument('--mode', type=str, choices=['from_npy', 'from_file', 'from_...
771e1ae4949ff329788b31c5610d995e2cf19061
648,753
def get_last_run(args, knack_records): """Summary: get the most recent modified date from all knack signal_pm object Args: args (namespace): command line inputs knack_records (knack object): a list of all knack pm records with fulcrum id Returns: """ knack_records_data...
53f0ab1d58ad4ac8a7fe7dbadb173425500fab79
648,755
def underscore_to_camel( text: str, lower_first: bool = True ) -> str: """Convert a string with words separated by underscores to a camel-cased string. Args: text (:obj:`str`): The camel-cased string to convert. lower_first (:obj:`bool`, optional): Lowercase the first charac...
b33d322d957f9492c70382fe8ed6f05f5e2f8fc2
648,756
import yaml def import_config(conf_name): """ Load YAML configuration file """ with open("../etc/config.yaml", 'r') as ymlfile: cfg = yaml.safe_load(ymlfile) cfg_sect = cfg[conf_name] return cfg_sect
ba55cdc7c853792027cf6a9083b3e19cecd40164
648,757
import os def get_log_file(log_dir, pid, sid, date_str, trial_num): """ Creates a path to a new log file in the given log directory. Example: <RECORDING_DIR>/log_2014-08-12_t01.json """ log_file = os.path.join( log_dir, 'log_' + date_str + '_' + pid + '_' + 't' + ('%02d' % ...
9e25e3e1595119b3728a0e200a3089b0916c8ef8
648,758
import re def sub_name(s): """replaces brackets with '-' and removes ',* """ #replace brackets with '_' and remove ',* #s = re.sub('\W', '',s_n) # dont do that, will replace '-' as well s_n = re.sub('[()]',"-",s) s_n = re.sub("'","",s_n) s_n = re.sub('\*',"",s_n) return s_n
7e27257f192bd6ebf67e958bfbde6f26fd340794
648,759
import os def make_containerized_cmd(args, image, dcommand, scommand, indir=None, outdir=None, sing=None): """ note that memory must be provided in gigabytes """ if indir is None: indir = os.getcwd() if outdir is None: outdir = os.getcwd() if args.vir...
c25b314ce1f2e7e9dabf2053ecb155fc5123e608
648,760
import ctypes def feed_ndarray(dali_tensor, arr): """ Copy contents of DALI tensor to pyTorch's Tensor. Parameters ---------- `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU Tensor from which to copy `arr` : torch.Tensor Destinati...
54d74fc58c46bbb25ec903b94e0fdbb00a4571cb
648,761
def service(policy_settings, backends_mapping, custom_service, service_settings, service_proxy_settings, lifecycle_hooks): """Preconfigured service with backend defined existing over whole testsing session""" svc = custom_service(service_settings, service_proxy_settings, backends_mapping, hooks=life...
d5a1ef7d041870b0f219154f9f606bf477142726
648,762
import re def is_inline_name(op): """Tell if given name is viable for inlining.""" if re.match(r'^i_.*$', op.getName(), re.I): return True return False
fd9044f6809cc6f437c5dc72df14a4057bcc6ca4
648,763
from typing import List from typing import Dict from typing import Any from typing import Tuple def get_status_simlarity(sim_table: List[Dict[str, Any]]) -> Tuple[float, float, float]: """類似度の統計情報を算出する :param sim_table: :returns: :rtype: """ ar: List[float] = [] for id, rec in enumera...
565cfd4741b6f6a2f64d2cffd058c7150339d10e
648,764
import pathlib import yaml def load_yaml(file): """ Loads the yaml file and returns a dictionary of the file contents. Parameters ---------- file : string Name of the yaml file with extension i.e. 'filename.yaml'. Returns ------- dict Structured contents of the yaml f...
e52d60878cd6cf31ccda9429a4bf45e38fa5e9df
648,765
import unicodedata def string_width(string): """Measure rendering width of string. Count ZENKAKU-character as 2-point and non ZENKAKU-character as 1-point """ widthmap = {'Na': 1, 'N': 1, 'H': 1, 'W': 2, 'F': 2, 'A': 2} return sum(widthmap[unicodedata.east_asian_width(c)] for c in string)
89e15d853f3e5caf5961f1635104f7647203bfb2
648,766
def fixIncorrectDateEncoding(Date): """ Fix date string to make it conform to ISO standard. """ if 'T00:00:00Z' in Date: return Date return Date + "T00:00:00Z"
57b0bed00c214794d3d1e25c313ce3e3cbe61526
648,767
import re def replace_forceinline(input_string): """__forceinline__'d methods can cause 'symbol multiply defined' errors in HIP. Adding 'static' to all such methods leads to compilation errors, so replacing '__forceinline__' with 'inline' as a workaround https://github.com/ROCm-Developer-Tools/HIP/blo...
e7e8fe24c8d7c0273268f22499ce0437e0fcc768
648,768
import torch def normalize_pixel_coordinates3d(pixel_coordinates, depth, height, width, eps=1e-8): """ Normalize pixel coordinates between -1 and 1. Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1) """ if pixel_coordinates.shape[-1] != 3: raise ValueError("Input pixel_co...
02b5bfd3a7b0d62b27aff0a3236afc64eee89942
648,769
import argparse def get_parser(): """Creates and returns parser object. Returns: (argparse.ArgumentParser): Parser object from which to parse arguments. """ description = "Queries NCAR RDA REST API." parser = argparse.ArgumentParser(prog='rdams', description=description) parser.add_ar...
8bd9fc1e1ca6a88206f4f07ce5994ae9ed381ebe
648,771
def getInputOrder(ast, input_order=None): """Derive the input order of the variables in an expression. """ variables = {} for a in ast.allOf('variable'): variables[a.value] = a variable_names = set(variables.keys()) if input_order: if variable_names != set(input_order): ...
38b534681d3035f1f95fbe0c5cc545459fdc9ce6
648,772
def split_macros(macros): """Split user-provided macro strings into a dictionary.""" split = [macro.split('=', 1) for macro in macros] return {var: value for var, value in split}
a22b4e13a858abed93b84fc6623dc45db924135e
648,773
def sanitize_cr(realmrep): """ Removes probably sensitive details from a realm representation. :param realmrep: the realmrep dict to be sanitized :return: sanitized realmrep dict """ result = realmrep.copy() if 'secret' in result: result['secret'] = '********' if 'attributes' in res...
63c4992736b936abe96611b002f212063134b6b5
648,774
def _fullcoordinate_field_name(): """ Key name for a solr field that contains package coordinates """ return "coord_full"
1c8b99b9176f3733020b9a883936ad6ddf2b1351
648,775
from datetime import datetime def format_modified_time(entry): """Formats the modified time (seconds since epoch) for display on screen""" return datetime.fromtimestamp(entry['mtime']).strftime('%b %-d %H:%M')
51589bae554732f89bf24bfd0f70aa1e57eb7a9d
648,776
import re def change_selection(SubjectDB_obj, args, op): """Parses selection command arguments, creates a dict of sets -- where key is subject index and value is a set of class index -- and iterates through each item and its set elements which through it does select, deselect or toggle operation to cl...
9fa520f9766ef91bbf9d66af0cc1b4359a972d78
648,777
from os import system def execute_program(progpath, params=None): """run a program according to it's path on windows params: progpath - program execute path params - program params """ return system('CMD /C'+ progpath + params)
d80d0438824489a226956c444c82e054c50368c2
648,778
import csv import io def parse_points(text): """Parse 3D points from a comma separated value formatted table. This function is deliberately fussy about the input. Only an n x 3 table with rows of either 3 empty cells of 3 floats. No metadata rows or columns are allowed. If any of the above condi...
a6d2bdc1dd9b6887c2cce951cd7a24d93c8811f6
648,779
def record_item_style(context): """ Return the style to be usd for the metric's current record specific item. Like the :func:`record_style` template tag, this expects a template context variable ``'metric'`` referring to the metric instance in question, as well as a context variable ``'record'`` co...
dcd3cd406e4f26fbdc9d57785988c5dcb6739509
648,780