content
stringlengths
22
815k
id
int64
0
4.91M
def split_last_dimension(x, n): """Reshape x so that the last dimension becomes two dimensions. The first of these two dimensions is n. Parameters ---------- x A Tensor with shape [..., m] n: int An integer. Returns ------- y A Tensor with shape [..., n, m/...
5,317,400
async def authenticate_user( request: web.Request, for_password_modification=False ) -> Tuple[User, Claims]: """Multiple schemes authentication using request Authorization header. Raises HTTPUnauthorized on failure. """ if not request.headers.get("Authorization"): raise web.HTTPUnauthorized(...
5,317,401
def download_data(destination="data"): """ Downloads training and evaluation data for the CTP retrieval. Args: destination: Where to store the downloaded data. """ datasets = [ "gprof_conv.npz", ] Path(destination).mkdir(exist_ok=True) for file in datasets: file...
5,317,402
def display(values): """ Display the values as a 2-D grid. Args: values(dict): The sudoku in dictionary form Returns: None """ width = 1+max(len(values[s]) for s in boxes) line = '+'.join(['-'*(width*3)]*3) for r in rows: print(''.join(values[r+c].center(width)+('|' i...
5,317,403
def nest(collection, *properties): """This method is like :func:`group_by` except that it supports nested grouping by multiple string `properties`. If only a single key is given, it is like calling ``group_by(collection, prop)``. Args: collection (list|dict): Collection to iterate over. ...
5,317,404
def pyav_decode_stream( container, start_pts, end_pts, stream, stream_name, buffer_size=0 ): """ Decode the video with PyAV decoder. Args: container (container): PyAV container. start_pts (int): the starting Presentation TimeStamp to fetch the video frames. end_pts (i...
5,317,405
def encode_data_for_sqlite(value): """Fix encoding bytes.""" try: return value.decode() except (UnicodeDecodeError, AttributeError): return sqlite3.Binary(value)
5,317,406
def copyto(dst, src, casting='same_kind', where=None): """Copies values from one array to another with broadcasting. This function can be called for arrays on different devices. In this case, casting, ``where``, and broadcasting is not supported, and an exception is raised if these are used. Args:...
5,317,407
def inject_sync_poller(sender, caller, st_type, user, **kwargs): """Inject javascript code.""" condition = ( caller != "top" or st_type != "js" or not hasattr(user, "mailbox") or not user.parameters.get_value("enable_carddav_sync") ) if condition: return "" re...
5,317,408
def plot_losses(train_err, val_err = None): """ Plots training loss and, if present, validation loss. Parameters ---------- train_err : list List of errors on the training set val_err : list, optional List of errors on the validation set """ _, ax = plt.subplots() ax.se...
5,317,409
def findExtensions(extensionsPath): """ Finds extensions in the selected Firefox profile. Parameters ---------- extensionsPath : str Path to the extensions.json file. Return Values ------------- extensionsList : [Extension] List of identified extensions. """ extensionLi...
5,317,410
def extendRun(run, extendByDays): """extend run function""" # mark run found global foundMonthly foundMonthly = True # get run date for printing runStartTimeUsecs = run['copyRun'][0]['runStartTimeUsecs'] runStartTime = datetime.strptime(usecsToDate(runStartTimeUsecs), '%Y-%m-%d %H:%M:%S') ...
5,317,411
def plot_template_matching( matched: np.ndarray, plots_dir: Path, dec_rac_center: Tuple[float, float], ) -> None: """ Create plot with the results of the cross-correlation. """ print('Plotting cross-correlation results...', end=' ', flush=True) # Define shortcuts frame_size = (matc...
5,317,412
def parse_pointstamped(point_input): """ Parse point_input into PointStamped. """ try: assert isinstance(point_input, PointStamped) return point_input except: pass try: assert isinstance(point_input, Point) point = PointStamped(point = point_input) ...
5,317,413
def test_handler_parse_module_missing_class(): """Test Handler.parse_module when a class is missing.""" skill_context = SkillContext( skill=MagicMock(skill_id=PublicId.from_str("author/name:0.1.0")) ) dummy_handlers_path = Path(ROOT_DIR, "tests", "data", "dummy_skill", "handlers.py") with un...
5,317,414
def ext_binary_gcd_env(a, b): """Extended binary GCD. Given input a, b the function returns d, s, t such that gcd(a,b) = d = as + bt.""" u, v, s, t, r = 1, 0, 0, 1, 0 while (a & 1 == 0) and (b & 1 == 0): a, b, r = a >> 1, b >> 1, r + 1 alpha, beta = a, b # # from here on we ma...
5,317,415
def write_init_file(name, data, path=""): """ This function writes config files for devices and default files :param name: Name of the file to be written to :param data: Data in Dict format :param path: Path where to write :return: """ # find the resource and ex...
5,317,416
def iter_file(infile): """Iterate through the dap output and yield (peak=>[(SNP, prior, post)]). :infile: The location of the DAP output file. """ with open_zipped(infile) as bob: out = {} nexts = '' for line in bob: f = line.rstrip().split('\t') if no...
5,317,417
def evaluate_model(model, X_test, Y_test, category_names): """ Prints scores of provided predition results using sklearn's classifation_report function. Parameters ---------- Y_pred : pandas Dataframe object, numpy array Dataframe with predicted values. Y_test : pandas Dataframe obj...
5,317,418
def gen_tasksets( number_of_sets=100, number_of_task=15, util_req=0.5, period_pdf=[0.03, 0.02, 0.02, 0.25, 0.40, 0.03, 0.2, 0.01, 0.04], scalingFlag=True, threshold=0.1, cylinder=4, sumRunnable=True): """Main function to generate task sets with the WATERS benchmark. Variables: number...
5,317,419
def remove(env, securitygroup_id, network_component, server, interface): """Detach an interface from a security group.""" _validate_args(network_component, server, interface) mgr = SoftLayer.NetworkManager(env.client) component_id = _get_component_id(env, network_component, server, interface) ret ...
5,317,420
def get_categories_and_file_names() -> Dict: """Returns a dictionary of categories and files Returns ------- Dict Key is the name of the category, value is a dictionary with information on files in that \ category """ path = Path("apd-core/core") category_files: Dict = {} ...
5,317,421
def process_class_items(game_class: GameClass, categories: Dict[str, Dict[str, int]], items_def: Dict, removals: Set[str], locked: Set[str]) -> ClassUnlockables: """ Process a hierarchical definition of a class's items into a ClassUnlockables structure :param game_class: the game cl...
5,317,422
def mako_plugin(dictionary): """The exported plugin code for transitive_dependencies. Iterate over each list and check each item for a deps list. We add a transitive_deps property to each with the transitive closure of those dependency lists. The result list is sorted in a topological ordering. """...
5,317,423
async def resolve_rrid( identifier: str, client: ClientSession, settings: SciCrunchSettings ) -> Optional[ResolvedItem]: """ Provides a API to access to results as provided by this web https://scicrunch.org/resolver """ # Example https://scicrunch.org/resolver/RRID:AB_90755.json identifier = id...
5,317,424
def MakeByte(ea): """ Convert the current item to a byte @param ea: linear address @return: 1-ok, 0-failure """ return idaapi.doByte(ea, 1)
5,317,425
def create_schedule(request_args): """Handle the schedule of an update for the site, via a form. Append the created schedule to the global current_schedules array. :param request_args: Arguments passed in the html form for schedule creation (request.args) :type request_args: Dictionary """ if...
5,317,426
def get_all(): """Returns all activation functions.""" fns = inspect.getmembers(sys.modules[__name__]) fns = [f[1] for f in fns if len(f)>1 and f[0] != "get_all"\ and isinstance(f[1], type(get_all))] return fns
5,317,427
def upload_persons(request): """ Options for upload form to define person and person roles :param request: :return: """ print('persons upload request: ', request.GET) selection = NmPersonsEntries.objects.all().distinct('entry_id') myFilter = PersonsFilter(request.GET, queryset=selection...
5,317,428
def gen_backend(backend='cpu', rng_seed=None, datatype=np.float32, batch_size=0, stochastic_round=False, device_id=0, max_devices=get_device_count(), compat_mode=None, deterministic_update=None, deterministic=None): """ Construct and return a backend instance of t...
5,317,429
def get_redis_error_classes(): """Return tuple of redis error classes.""" from redis import exceptions # This exception suddenly changed name between redis-py versions if hasattr(exceptions, 'InvalidData'): DataError = exceptions.InvalidData else: DataError = exceptions.DataError ...
5,317,430
def create_property(supported_prop: Dict[str, Any]) -> HydraClassProp: """Create a HydraClassProp object from the supportedProperty.""" # Syntax checks doc_keys = { "property" : False, "title": False, "readonly": True, "writeonly": True, "required": True } re...
5,317,431
def test_indent(): """Should indent the given output by the given indent level.""" nose.assert_equal( cidrbrewer.indent('IP Address:', indent_level=2), '{}IP Address:'.format(' ' * 6))
5,317,432
def expr_to_filename(expr): """ Convert an arbitrary expr string to a valid file name. The name is based on the md5 check sum for the string and Something that was a little more human readable would be nice, but the computer doesn't seem to care. """ import scipy.weave.md5_load as m...
5,317,433
def getIDList(): """getIDList() -> list(string) Returns a list of all lanes in the network. """ return _getUniversal(tc.ID_LIST, "")
5,317,434
def cmor(B, C): """ Returns the n-point continuous Morlet wavelet Args: B the bandwidth parameter C the central frequency """ def time(t, s=1.): s = jnp.atleast_2d(jnp.asarray(s)).T t = t / s # the sinusoid output = jnp.exp(1j * 2 * jnp.pi * C * t) ...
5,317,435
def coefficient(n: int) -> None: """ Function to calculate the coefficients of (x - 1) ^ n - (x ^ n - 1) with the help of Pascal's triangle. """ CONST[0] = 1 for i in range(n): CONST[1 + i] = 1 for j in range(i, 0, -1): CONST[j] = CONST[j - 1] - CONST[j] C...
5,317,436
def inner_join_indexer_int32(*args, **kwargs): # real signature unknown """ Two-pass algorithm for monotonic indexes. Handles many-to-one merges """ pass
5,317,437
def set_trunk_native_vlan(module): """Configures the trunk native vlan attribute for the switchport """ name = module.attributes['name'] value = module.attributes['trunk_native_vlan'] module.log('Invoked set_trunk_native_vlan for eos_switchport[%s] ' 'with value %s' % (name, value)) ...
5,317,438
def calculateMid(paddle): """Calculates midpoint for each paddle, much easier to move the paddle this way""" midpoint = int(paddle[0][1] + paddle[1][1]) / 2 return midpoint
5,317,439
def autotune(i): """ Input: { See 'crowdsource program.optimization' (iterations) - change iterations Force: local = yes only_one_run = yes keep_tmp = yes skip_exchange...
5,317,440
def generate_from_file(abouts, is_about_input, license_dict, scancode, min_license_score, template_loc=None, vartext=None): """ Generate an attribution text from an `abouts` list of About objects, a `template_loc` template file location and a `vartext` optional dict of extra variables. Return a tup...
5,317,441
def cli(env, name, datacenter, pod, network, billing): """Order/create a VLAN instance.""" item_package = ['PUBLIC_NETWORK_VLAN'] complex_type = 'SoftLayer_Container_Product_Order_Network_Vlan' extras = {'name': name} if pod: datacenter = pod.split('.')[0] mgr = SoftLayer.NetworkMan...
5,317,442
def user_past_parties(): """List parties the logged in user has been in. Params: page (int): Optional. Page number to return. """ received = request.get_json() page = received.get('page', 1) # User record user = util.user_from_jwt(received.get('token')) if not user: re...
5,317,443
def bits_list(number): """return list of bits in number Keyword arguments: number -- an integer >= 0 """ # https://wiki.python.org/moin/BitManipulation if number == 0: return [0] else: # binary_literal string e.g. '0b101' binary_literal = bin(number) bit...
5,317,444
def build_stats(ctx, build_id, tasks): """ Collect stats for the given evergreen build. :param ctx: Command context. :param build_id: Id of build to analyze. :param tasks: If true include tasks in output. """ api = ctx.obj['api'] fmt = ctx.obj['format'] build = api.build_by_id(buil...
5,317,445
def show_funcs(): """ List of of algos presently available """ return(sorted(func_registry.keys()))
5,317,446
def _FakeQuantWithMinMaxVars(inputs, min_var, max_var, per_channel, num_bits, narrow_range): """Adds a fake quantization operation. Depending on value of per_channel, this operation may do global quantization or per channel quantization. min_var and max_var should have correspo...
5,317,447
def join_and_keep_order(left, right, remove_duplicates, keep='first', **kwargs): """ :type left: DataFrame :type right: DataFrame :rtype: DataFrame """ left = left.copy() right = right.copy() left['_left_id'] = range(left.shape[0]) right['_right_id'] = range(right.shape[0]) result = left.merge(right=right, **...
5,317,448
def count_variants(graph) -> typing.Counter[str]: """Count how many of each type of variant a graph has. :param pybel.BELGraph graph: A BEL graph """ return Counter( variant_data[KIND] for data in graph if has_variant(graph, data) for variant_data in data[VARIANTS] )
5,317,449
def collate(expression, collation): """Return the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin """ expr = _literal_as_binds(expression) return _BinaryExpression( expr, _literal_as_text(col...
5,317,450
def crop_images(x, y, w, h, *args): """ Crops all the images passed as parameter using the box coordinates passed """ assert len(args) > 0, "At least 1 image needed." cropped = [] for img in args: cropped.append(img[x : x + h, y : y + w]) return cropped
5,317,451
def WriteResultToJSONFile(test_suites, results, json_path): """Aggregate a list of unittest result object and write to a file as a JSON. This takes a list of result object from one or more runs (for retry purpose) of Python unittest tests; aggregates the list by appending each test result from each run and wri...
5,317,452
def svn_prop_has_svn_prop(*args): """svn_prop_has_svn_prop(apr_hash_t props, apr_pool_t pool) -> svn_boolean_t""" return _core.svn_prop_has_svn_prop(*args)
5,317,453
def test_mobile_double_stereochemistry_enumeration3(): """Remove stereochemistry from mobile double bonds""" assert enumerate_tautomers_smiles('C/C=C\\C(C)=O') == {'C=C(O)C=CC', 'C=CCC(=C)O', 'CC=CC(C)=O', 'C=CCC(C)=O', 'C=CC=C(C)O'}
5,317,454
def test_labels_match_clustering(case, labels): """ train a GMM, assert predictions match labels """ # should get 100% accuracy since the two clusters are super different latent = case.latent_left_ gmm = GaussianMixture(n_components=2) predicted_labels = gmm.fit_predict(latent) assert np...
5,317,455
def _setup_logging(): """ Setup logging. """ log_handler = logging.StreamHandler() formatter = logging.Formatter(logging.BASIC_FORMAT) log_handler.setFormatter(formatter) logging.getLogger().addHandler(log_handler) logging.getLogger().setLevel(logging.INFO) if _OPTIONS.log_config: ...
5,317,456
def test_analysis_dual_grad(n, lbda): """ Test the gradient of dual analysis. """ rng = check_random_state(None) x, _, _, _, D, A = synthetic_1d_dataset(n=n, s=0.5, snr=0.0, seed=rng) eps = 1e-3 v_dim = D.shape[1] v = np.clip(rng.randn(n, v_dim), -(lbda - eps), (lbda - eps)) Psi_A = np.linal...
5,317,457
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) try: json_string = parse_snapcraft_file(find_snapcraft_file(os.getcwd())) json_doc = json.loads(json_string)...
5,317,458
def multiplyVectors(): """Function to take input of two complex numbers and print their product """ re = floatInput("Enter the Real part of 1st Vector: ") im = floatInput("Enter the Complex part 1st Vector: ") v1 = ComplexNumbers(re, im) re = floatInput("Enter the Real part of 2nd Vector: "...
5,317,459
def dojo_gbrv_results(pseudo, struct_type, num_sites, volumes, etotals): """ This function computes the GBRV results and returns the dictionary to be inserted in the dojoreport file. Args: pseudo: Pseudopotential object. struct_type: "fcc" or "bcc" num_sites: Number of sites in ...
5,317,460
def split_person_name(name): """ A helper function. Split a person name into a first name and a last name. Example. >>> split_person_name("Filip Oliver Klimoszek") ("Filip Oliver", "Klimoszek") >>> split_person_name("Klimoszek") ("", "Klimoszek") """ parts = name.split(" ") return " ".join(parts[:-1...
5,317,461
def readFile(file): """Reads file and returns lines from file. Args: string: file name Returns: list: lines from file """ fin = open(file) lines = fin.readlines() fin.close() return lines
5,317,462
def StartsWithComparator(current, compare): """Compare if current starts with compare.""" if not current.startswith(compare): msg = '{0} ({1}) does not starts with value {2} ({3})' raise JsonPatchTestFailed(msg.format(current, type(current), compare, type(compare)))
5,317,463
def default_formatter(fig, axes): """Default formatter placeholder Override this to apply a default format function to all graphs and figures """
5,317,464
def vec_rotate_left(x): """Circular left shift the contents of the vector Args: x (jax.numpy.ndarray): A line vector. Returns: jax.numpy.ndarray: Left rotated x. """ return jnp.roll(x, -1)
5,317,465
def play_game(my_play='PUT',game_id='PUT'): """Submit a play to a game. Return results of the game.""" # If no my_play then something is wrong # If no game_id and no match_id then create a new game and play it # If game_id then play that game # If match_id and no game_id then .. idk .. tea? # Pu...
5,317,466
def get_inputs(seq_len): """Get input layers. See: https://arxiv.org/pdf/1810.04805.pdf :param seq_len: Length of the sequence or None. """ names = ['Token', 'Segment', 'Masked'] return [keras.layers.Input( batch_shape=(1, seq_len,), name='Input-%s' % name, ) for name in name...
5,317,467
def get_credentials(args): """Read credentials from args""" # cmdline credentials override those stored in config file if args.api_key or args.api_secret: if not args.api_key or not args.api_secret: raise AuthError( ( "Both --key and --secret must be p...
5,317,468
def GetRange(spreadsheet_id, sheet_name, range_in_sheet): """Gets the given range in the given spreadsheet. Args: spreadsheet_id: The id from Google Sheets, like https://docs.google.com/spreadsheets/d/<THIS PART>/ sheet_name: The name of the sheet to get, from the bottom tab. range_in_sheet: The ...
5,317,469
def format_price(raw_price): """Formats the price to account for bestbuy's raw price format Args: raw_price(string): Bestbuy's price format (ex: $5999 is $59.99) Returns: string: The formatted price """ formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric...
5,317,470
def get_directory(directory=None): """Get directory to work with.""" # Set variable fdir = current directory, if user didn't specify another dir if not directory: fdir = os.getcwd() # Set variable fdir = directory chosen by the user, if a dir is specified else: fdir = os.path.realpat...
5,317,471
def access_app(app_label, *permissions): """ Returns a scope that represents access for the given permissions to the given app. """ return _make_grant( ( app_label, ), permissions, )
5,317,472
def mock_device_with_capabilities(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, '__abstractmethods__', frozenset()) m.setattr(Device, '_capabilities', mock_device_capabilities) def get_device(wires=1)...
5,317,473
def Error(msg): """Prints the given message and, if debugging is on, logs it. """ print color.B_RED + '[-] %s' % (msg) + color.END if config.get('debug'): debug(msg)
5,317,474
def replicated_data(index): """Whether data[index] is a replicated data item""" return index % 2 == 0
5,317,475
def create_source_list(uris_list): """ Create a source_list object Adds list of uris to soure_list object. @arg uris_list List of list of GCS uris @returns A source_list object @example uris_list = [["gs://my-bucket/my-image-1.tif"], ["gs://my-bucket/my-image-2.tif"]] print(create_s...
5,317,476
def sigmoid_rampup(current, rampup_length): """ Exponential rampup from https://arxiv.org/abs/1610.02242 . """ if rampup_length == 0: return 1.0 else: current = np.clip(current, 0.0, rampup_length) phase = 1.0 - current / rampup_length return float(np.exp(-5.0 * phase * ...
5,317,477
def photos_restaurants(): """returns photos""" return render_template('photos.html')
5,317,478
def encode(obj, outtype='json', raise_error=False): """ encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- ...
5,317,479
def minorify_scale(scale): """Turns a major scale into a minor scale""" return rotate(scale, 5)
5,317,480
def _get_dtype_maps(): """ Get dictionaries to map numpy data types to ITK types and the other way around. """ # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (...
5,317,481
def ShowSyntax(exit_code=0): """Documentation function to describe how to use this funtion""" if sys.stderr.isatty() and sys.stdin.isatty(): # Ensure that STDERR can be written to print("{0}: ".format(sys.argv[0])) print("") print("Perform an analysis of an historical event set a...
5,317,482
def get_user_roles_common(user): """Return the users role as saved in the db.""" return user.role
5,317,483
def getlist(self, option: str, fallback: list=None, *, raw: bool=False, vars: dict=None) -> list: """ Converts a SectionProxy cvs option to a list :param option: the option to get :param fallback: default value, if option does not exist :param raw: True to disable interpolation :param vars: addi...
5,317,484
def _schedule_spatial_pack(cfg, s, output, conv, data_vec, kernel_vec): """schedule the spatial packing for conv2d""" data = s[data_vec].op.input_tensors[0] max_unroll = 16 vec_size = [1, 2, 4, 8, 16] # get tunable parameters (they are defined in compute) BC, TC, VC = cfg["tile_co"].size BH...
5,317,485
def create_fermi_isotropic_diffuse_model(filename, **kwargs): """Read Fermi isotropic diffuse model. See `LAT Background models <https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html>`_ Parameters ---------- filename : str filename kwargs : dict Keyword argument...
5,317,486
def yumFood(username, password, foodList): """ Yums the host's food by the guest user :param username: guest Instagram username :param password: guest Instagram password :param foodList: all yummed food on the index page """ guest = Guest(username, password) result = guest.login() if...
5,317,487
def get_auto_sync(admin_id): """Method to return status of the auto synchronization statement. Args: admin_id (str): Root privileges flag. """ return r_synchronizer.is_sync_auto()
5,317,488
def create_inchi_groups(ctfile): """Organize `InChI` into groups based on their identical `InChI` string and similar coupling type. :param ctfile: `SDfile` instance. :type ctfile: :class:`~ctfile.ctfile.SDfile` :return: Dictionary of related `InChI` groups. :rtype: :rtype: :py:class:`dict` """ ...
5,317,489
def qmax_statistics(sample_q, sample, uncertainty, qmax, qmin, qmaxinst, relative_max_uncertainty,): """ """ #TODO: Include background statistics in this? if qmax is 'statistics': old_settings = np.seterr(divide='ignore') uncertainty_percent_array = uncertainty ...
5,317,490
def make_source(): """ Runs make command on c scripts. """ PathToLaunch = sys.path[1]+'/sources/vir/' origWD = os.getcwd() # remember our original working directory os.chdir(PathToLaunch) command = 'make clean ' subprocess.run(command, shell=True) command = 'make video2signature ' subpro...
5,317,491
def loocvRF(data, idcolumn, outcomevar, dropcols=[], numestimators=1000, fs=0.02): """ Main loocv RF function that calls other functions to do RF feature selection, training, and testing. Args: data (pandas DataFrame): This is a dataframe containing each participant's features and outcome...
5,317,492
def main(eps=0.01, plot=False, test=False): """Решение системы нелинейных уравнений методами простой итерации и Ньютона :param eps: точность вычисления :param plot: флаг, отвечающий за вывод графика решения :param test: флаг, запускающий тестирование """ init_dict = { "f": ["x1 - cos(x...
5,317,493
def sqla_session(x: Union['db_url', 'engine']): """ Do a pile of sane defaults to get a sqla session. Example usage: db = sqla_session(...) df = pd.read_sql(sql=..., con=db.bind) """ # Resolve args if isinstance(x, str): db_url = x if '/' not in db_url: ...
5,317,494
def box_iou(box1, box2, order='xyxy'): """Compute the intersection over union of two set of boxes. The default box order is (xmin, ymin, xmax, ymax). Args: box1: (tf.tensor) bounding boxes, sized [A, 4]. box2: (tf.tensor) bounding boxes, sized [B, 4]. order: (str) box order, either 'xyxy'...
5,317,495
def git(ctx, list=False, fetch=False, pull=False, update=False, branch=None): """ Run batch operations for each git repositories. The included repositories exists in direct sub directories of the current directory). The task supports providing multiple actions at once. :param ctx: (implicit fab...
5,317,496
def strings_2(string): """ Prints the given string, but with: -- Each occurrence of xxx replaced by Siri, and then -- The string printed in "title" mode. For example: strings_2("do THIS in title mode!") prints Do This In Title Mode! strings_2("Hey xxx: who isxxx?") prints ...
5,317,497
def get_bmi_category(df): """ This function adds the BMI category and Health risk based on the BMI value :param df: input dataframe with BMI values :return: Dataframe with BMI category and Health risk derived from their respective BMI values """ return df.withColumn('BMI Category', F.when(df.BM...
5,317,498
def setup(projectdir='.', resourcedir='mm'): """Initialise a default modelmanager project in the current directory.""" resourcedir = osp.join(projectdir, resourcedir) settings_path = osp.join(resourcedir, SettingsManager.settings_file_name) print('Initialising a new modelmanager project in: %s\n' % pro...
5,317,499