content
stringlengths
22
815k
id
int64
0
4.91M
def convert_reconstruction( bruker_directory, series, reconstruction, iod_converter, writer): """ Convert and save a single reconstruction. :param bruker_directory: Bruker directory object :param series: series number in the Bruker directory :param reconstruction: reconstruc...
26,400
def dash_min_det_areas(bars, m, with_min_det): """ Dash the areas of the bars that represent cost incurred while being considered by the MIN^det algorithm. :param bars: Collection (tuple) of matplotlib bar objects (matplotlib.patches.Rectangle). """ bar_count = 0 alg_count = 0 for bar in bar...
26,401
def make3DArray(dim1, dim2, dim3, initValue): """ Return a list of lists of lists representing a 3D array with dimensions dim1, dim2, and dim3 filled with initialValue """ result = [] for i in range(dim1): result = result + [make2DArray(dim2, dim3, initValue)] return result
26,402
def generate_boxes(bounds=(-1, -1, 1, 1), method='size', size=math.inf): """ Generate a stream of random bounding boxes Has two methods for generating random boxes: - *size* - generates a random central point (x0, y0) within the bounding box, and then draws widths and heights ...
26,403
def create_assets(asset_ids, asset_type, mk_parents): """Creates the specified assets if they do not exist. This is a fork of the original function in 'ee.data' module with the difference that - If the asset already exists but the type is different that the one we want, raise an error - Start...
26,404
def cp(from_path: str, to_path: str, fs, user): """cp [from:string] [to:string] [EXTEND] cp - copy file or folder from the first specified path to the second """ fs.cp(user, from_path.split("/"), to_path.split("/"))
26,405
def decoration(markdown: str, separate: int = 0) -> str: """見出しが使われているマークダウンをDiscordで有効なものに変換します。 ただたんに`# ...`を`**#** ...`に変換して渡された数だけ後ろに改行を付け足すだけです。 Parameters ---------- markdown : str 変換するマークダウンです。 separate : int, default 1 見出しを`**`で囲んだ際に後ろに何個改行を含めるかです。""" new = "" ...
26,406
def get_fingerprint(file_path: str) -> str: """ Calculate a fingerprint for a given file. :param file_path: path to the file that should be fingerprinted :return: the file fingerprint, or an empty string """ try: block_size = 65536 hash_method = hashlib.md5() with open(f...
26,407
def set_publish_cluster_args(args): """Set args to publish cluster """ public_cluster = {} if args.public_cluster: public_cluster = {"private": False} if args.model_price: public_cluster.update(price=args.model_price) if args.cpp: public_cluster.update(cr...
26,408
def test_permutation_operator_standard_swap_list_dim(): """Generates the standard swap operator on two qubits.""" expected_res = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]) res = permutation_operator([2, 2], [2, 1]) bool_mat = np.isclose(res, expected_res) np.testing.assert_...
26,409
def create_session(): """creates database session""" db_engine = sa.create_engine(os.environ.get('DATABASE_URL'), echo=True) return sessionmaker(bind=db_engine)
26,410
def _get_iforest_anomaly_score_per_node(children_left, children_right, n_node_samples): """ Get anomaly score per node in isolation forest, which is node depth + _average_path_length(n_node_samples). Will be used to replace "value" in each tree. Args: children_left: left children childr...
26,411
def get_invalid_value_message(value_name: str, value: str, line_no: int, uid: str, expected_vals: "list[str]") -> str: """ Returns the formatted message template for invalid value while parsing students data! """ msg = f"Invalid {value_name} <span class=\"font-weight-bold\">{value}</span>\ o...
26,412
def test_ShortestPairs_sparse_nacl(ph_nacl: Phonopy, helper_methods): """Test ShortestPairs (parse) by NaCl.""" scell = ph_nacl.supercell pcell = ph_nacl.primitive pos = scell.scaled_positions spairs = ShortestPairs(scell.cell, pos, pos[pcell.p2s_map]) svecs = spairs.shortest_vectors multi =...
26,413
def compute_score_for_coagulation(platelets_count: int) -> int: """ Computes score based on platelets count (unit is number per microliter). """ if platelets_count < 20_000: return 4 if platelets_count < 50_000: return 3 if platelets_count < 100_000: return 2 if plate...
26,414
def check_horizontal_visibility(board: list): """ Check row-wise visibility (left-right and vice versa) Return True if all horizontal hints are satisfiable, i.e., for line 412453* , hint is 4, and 1245 are the four buildings that could be observed from the hint looking to the right. >>> che...
26,415
def _get_soup(header, url): """This functions simply gets the header and url, creates a session and generates the "soup" to pass to the other functions. Args: header (dict): The header parameters to be used in the session. url (string): The url address to create the session. ...
26,416
def format_details(details, countries): """ Format details given a countries object. The countries object can be retrieved from read_country_names. """ details["country_name"] = countries.get(details.get("country")) details["latitude"], details["longitude"] = read_coords(details.get("loc"))
26,417
def test_model(model, name_model, X_train, y_train, X_test, y_test, details=False, normalize=False, weights=None, return_model=False, lib='scikit-learn', fit_params=None): """ Function that does a detailed investigation of a given model. Confusion matrices are generated and various metrics ar...
26,418
def get_text_block(dunning_type, language, doc): """ This allows the rendering of parsed fields in the jinja template """ if isinstance(doc, string_types): doc = json.loads(doc) text_block = frappe.db.get_value('Dunning Type Text Block', {'parent': dunning_type, 'language': language}, ['top_text_block...
26,419
def load(test=False, cols=None): """Loads data from FTEST if *test* is True, otherwise from FTRAIN. Pass a list of *cols* if you're only interested in a subset of the target columns. """ fname = FTEST if test else FTRAIN df = pd.read_csv(os.path.expanduser(fname)) # load pandas dataframe #...
26,420
def flow_read(src_file): """Read optical flow stored in a .flo, .pfm, or .png file Args: src_file: Path to flow file Returns: flow: optical flow in [h, w, 2] format Refs: - Interpret bytes as packed binary data Per https://docs.python.org/3/library/struct.html#format-char...
26,421
def group_create_factory(context, request): """Return a GroupCreateService instance for the passed context and request.""" user_service = request.find_service(name="user") return GroupCreateService( session=request.db, user_fetcher=user_service.fetch, publish=partial(_publish, reques...
26,422
def test_cray_badger_create_suite(cli_runner, rest_mock): """ Test `cray init` for creating the default configuration """ # pylint: disable=too-many-locals runner, cli, opts = cli_runner name = 'someName' description = 'someDescription' config = opts['default'] hostname = config['hostname'] ...
26,423
def verify(params, vk, m, sig): """ verify a signature on a clear message """ (G, o, g1, hs, g2, e) = params (g2, X, Y) = vk sig1 , sig2 = sig return not sig1.isinf() and e(sig1, X + m * Y) == e(sig2, g2)
26,424
def prepend_items(): """ Return a function than prepend any item from "paths" list with "prefix" """ def prepend_func(prefix, paths): return [os.path.join(prefix, item) for item in paths] return prepend_func
26,425
def generate_data(n): """ 生成训练数据 """ X, y = make_classification(n_samples=n, n_features=4) data = pd.DataFrame(X, columns=["x1", "x2", "x3", "x4"]) data["y"] = y return data
26,426
def glob_to_chain(chain, paths): """ Default TChain::Add functionality doesn't support wildcards in directories, only base filename. Workaround by adding individual files one by one. paths: wildcard or list of filepaths """ if type(paths) is str: # glob wildcard paths = glob.gl...
26,427
def _configure_logging(app): """configure logging""" pass
26,428
def blsimpv(p, s, k, rf, t, div=0, cp=1): """ Computes implied Black vol from given price, forward, strike and time. """ f = lambda x: blsprice(s, k, rf, t, x, div, cp) - p result = brentq(f, 1e-9, 1e+9) return result
26,429
def container_describe(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /container-xxxx/describe API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Containers-for-Execution#API-method%3A-%2Fcontainer-xxxx%2Fdescribe """ return DXHTTPRequest('...
26,430
def nested(fields: Union[Dict[str, Dict], DataSpec], **config) -> dict: """ Constructs a nested Field Spec Args: fields: sub field specifications config: in kwargs format Returns: the nested spec """ spec = { "type": "nested", "fields": utils.get_raw_sp...
26,431
def test_standardize_teams(ps): """Tests standardize_teams""" teams = ['KCC', 'GBP', 'LAC'] assert ps.standardize_teams(teams) == ['KC', 'GB', 'LAC']
26,432
def generate_graphs(dat_dir, graph_dir, graph_infra, platform_name): """ Generate graphs using the existing .dat files and graph infrastructure. """ genGraphs = os.path.join(get_chpl_util_dir(), 'genGraphs') cmd = [genGraphs, '--perfdir', dat_dir, '--outdir', graph_dir, ...
26,433
def make_cluster_cmap(labels, grey_pos='start'): """ Creates an appropriate colormap for a vector of cluster labels. Parameters ---------- labels : array_like The labels of multiple clustered points grey_pos: str Where to put the grey color for the noise Returns ...
26,434
def init_weights(net, init_type='normal', init_gain=0.02): """ Initialize network weights. Parameters: net (Cell): Network to be initialized init_type (str): The name of an initialization method: normal | xavier. init_gain (float): Gain factor for normal and xavier. """ for...
26,435
def objects_from_array( objects_arr: np.ndarray, default_keys=constants.DEFAULT_OBJECT_KEYS ) -> List[btypes.PyTrackObject]: """Construct PyTrackObjects from a numpy array.""" assert objects_arr.ndim == 2 n_features = objects_arr.shape[1] assert n_features >= 3 n_objects = objects_arr.shape[0]...
26,436
def run_policy(env, policy, scaler, logger, episodes): """ Run policy and collect data for a minimum of min_steps and min_episodes Args: env: ai gym environment policy: policy object with sample() method scaler: scaler object, used to scale/offset each observation dimension ...
26,437
def load_data(): """Load database""" db = TinyDB(DATABASE_PATH) data = db.all() return pd.DataFrame(data)
26,438
def test_update_where_string(dataframe, spark_dataframe): """Test update_where and update with a string.""" assert_frame_equal( spark_dataframe.update_where( conditions=""" `decorated-elephant` = 1 AND `animals@#$%^` = 'rabbit' """, target_column_name="cit...
26,439
def uit2xml(source,target): """Converts UIT to Across XML files""" dlg = wx.MessageDialog(None, 'Not yet implemented. Use classic TFC for now', 'Error', wx.OK) dlg.ShowModal() return
26,440
def test_output_logs_path(output, tmpdir): """Testing if logs directory is created in the provided output_directory.""" assert output.logs_path() == os.path.join(tmpdir, "logs")
26,441
def plotcmaponaxis(ax, surf, title, point_sets=None): """Plot a Surface as 2D heatmap on a given matplotlib Axis""" surface = ax.pcolormesh(surf.X, surf.Y, surf.Z, cmap=cm.viridis) if point_sets: for x_y, z, style in point_sets: ax.scatter(x_y[:, 0], x_y[:, 1], **style) ax.set_xlabe...
26,442
def get_log_storage() -> TaskLogStorage: """Get current TaskLogStorage instance associated with the current application.""" return current_app.config.get("LOG_STORAGE")
26,443
def test_similarity_forest_wrongly_the_same_pred(data): """There should not be a situation when models predicts the same when there is no random_state set""" X, y = data X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=42) clf1 = SimilarityForestClassifier(...
26,444
def test_optional_posonly_args1(a, b=10, /, c=100): """ >>> test_optional_posonly_args1(1, 2, 3) 6 >>> test_optional_posonly_args1(1, 2, c=3) 6 >>> test_optional_posonly_args1(1, b=2, c=3) # doctest: +ELLIPSIS Traceback (most recent call last): TypeError: test_optional_posonly_args1() g...
26,445
def _build_schema_resource(fields): """Generate a resource fragment for a schema. Args: fields (Sequence[google.cloud.bigquery.schema.SchemaField): schema to be dumped. Returns: Sequence[Dict]: Mappings describing the schema of the supplied fields. """ return [field.to_api_repr() f...
26,446
def update_component_docs(): """Update the components.rst file with currently implemented components.""" BuildDocs().update_docs()
26,447
def modificar_nota (lista_alumnos): """ """ posicion = buscar_alumno (lista_alumnos, nombre_alumno) if posicion == -1: print('Alumno no encontrado') else: nota_nueva = float(input('Nueva nota: ')) lista_alumnos[posicion].nota = nota_nueva print('\nNombre: ',lista_alum...
26,448
def flatten_swtn(x): """ Flatten list an array. Parameters ---------- x: list of dict or ndarray the input data Returns ------- y: ndarray 1D the flatten input list of array. shape: list of dict the input list of array structure. """ # Che...
26,449
def checkpoint(cache, **csv_args): """ Return a decorator which automatically caches the result of a function which returns a pandas.DataFrame. Parameters ---------- cache : str or path object The path to the file which contains the results of `func`. **csv_args : Optional[Mapping] ...
26,450
def crossing(series, value, **options): """Find where a function crosses a value. series: Series value: number options: passed to interp1d (default is linear interp) returns: number """ interp = interp1d(series.values, series.index, **options) return interp(value)
26,451
def param_docs(a: int, b, c: float) -> str: """Detailed param docs and annotations"""
26,452
def test_monitor_args_fails() -> None: """ Check MonitorArguments object is not created if both run id and experiment name are not provided. """ with pytest.raises(ValueError) as ex: patch_and_parse([]) assert "list of run ids or an experiment name" in ex.value.args[0]
26,453
def equilSoundSpeeds(gas, rtol=1.0e-6, maxiter=5000): """ Returns a tuple containing the equilibrium and frozen sound speeds for a gas with an equilibrium composition. The gas is first set to an equilibrium state at the temperature and pressure of the gas, since otherwise the equilibrium sound spee...
26,454
def yaml_to_json(yaml_file, json_file): """Convert YAML to JSON. Args: yaml_file (str): Input YAML file name. json_file (str): Output JSON file name. """ with open(yaml_file) as f: with open(json_file, 'w') as f1: f1.write(json.dumps(yaml.load(f.read()), ensure_asci...
26,455
def benchmark(partitioner_list: list, item_list: list, bucket_list: list, iterations: int = 1, begin_range: int = 1, end_range: int = 10, specified_items_sizes: list = None, verbose: bool = False)\ -> pd.DataFrame: """ Args: Returns: Raises: """ r = pd.DataFrame(columns=(...
26,456
def qso_template(outfil='Figures/qso_template.pdf'): """ van den berk """ # Load telfer = pyicq.get_telfer_spec() clight = const.c.cgs # Beta spliced to vanden Berk template with host galaxy removed van_file = resource_filename('pyigm', '/data/quasar/VanDmeetBeta_fullResolution.txt') ...
26,457
def adj_by_strand(genes): """ liste: list of hmm gene with homogenous strand Check if the gene is in tandem with another and if so store the gene inside a set obj.TA_gene.linked In parallel it clean up the list obj.TA_gene.genes by removing the genes that forme a tandem. Then TA_gene.genes has only ...
26,458
def register_user(): """ register a user and take to profile page """ form = RegisterForm() if form.validate_on_submit(): username = form.username.data password = form.password.data email = form.email.data first_name = form.first_name.data last_name = form.last...
26,459
def stack_init_image(init_image, num_images): """Create a list from a single image. Args: init_image: a single image to be copied and stacked num_images: number of copies to be included Returns: A list of copies of the original image (numpy ndarrays) """ init_images = [] ...
26,460
def process_problem(_path, _lang=EN): """ Обработка задачи """ path = os.path.join(_path, 'problem.xml') with open(path, 'r', encoding='utf-8') as file: root = ET.parse(file).getroot() titles = root.find('names').findall('name') title = titles[0].attrib['value'] for t in titles: ...
26,461
def refresh_task(tenant_id, source_id): """Run the Refresh task""" logger.info("First checking its availability") svc = CheckSourceAvailability(source_id) svc.process() if svc.source.availability_status == "available": logger.info("Starting Inventory Refresh") obj = RefreshInventory...
26,462
def input_to_text(s): """Convert the given byte string or text type to text using the file system encoding of the current system. :param basestring s: String or text type to convert :return: The string as text :rtype: unicode """ return avalon.compat.to_text(s, sys.getfilesystemencoding())
26,463
def doomed_parser(line): """Fixture to test error handling""" raise exceptions.LineParseException('Error occurred')
26,464
def f5(x, eps=0.0): """The function f(x)=tanh(4x)+noise""" return np.tanh(4*x) + eps * np.random.normal(size=x.shape)
26,465
def graph_history_scan(dataset, df_search, best_models): """ creates a graph of scores with various percentages of data (20%, 40%, .., 100%) for the 5 best models :param dataset: dataset object :param df_search: dataframe of the search history :param best_models: selection within df_search with bes...
26,466
def test_max_chunk_settings_overrides(et_code, settings, basic_exporter_class, new_exporter): """ Using EXPORTER_MAX_RC_CONFIG and EXPORTER_MAX_DC_CONFIG settings should override values set on the class when an exporter is instantiated. """ expclass = basic_...
26,467
def get_next_event(game, players): """ return None if a player has to move before the next event otherwise return the corresponding Event enum entry """ active_player = get_active_player(players, game.finish_time) if active_player is None: return None planet_rotation_event = ( ...
26,468
def _convert_requirements(requirements): """Convert the requirements to an array of strings. ["key op value", "key op value", ...] """ # TODO(frossigneux) Support the "or" operator # Convert text to json if isinstance(requirements, six.string_types): try: requirements = json...
26,469
def max_width(string, cols, separator='\n'): """Returns a freshly formatted :param string: string to be formatted :type string: basestring or clint.textui.colorred.ColoredString :param cols: max width the text to be formatted :type cols: int :param separator: separator to break rows :type se...
26,470
def print_params(params, ns): """ Print contents of param dictionary to screen """ if type(params) == dict: for k, v in params.iteritems(): if type(v) == dict: print_params(v, ns_join(ns, k)) else: print("%s=%s"%(ns_join(ns, k), v)) els...
26,471
def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets): """Check if any aliens have reached the bottom of the screen.""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Treat this the same as if the shi...
26,472
def aes_encrypt(text, sec_key): """ AES encrypt method. :param text: :param sec_key: :return: """ pad = 16 - len(text) % 16 if isinstance(text, bytes): text = text.decode('utf-8') text += pad * chr(pad) encryptor = AES.new(sec_key, 2, '0102030405060708') cipher_text =...
26,473
def get_value_at_coords(matrix, x, y): """Returns the value of the matrix at given integer coordinates. Arguments: matrix {ndarray} -- Square matrix. x {int} -- x-coordinate. y {int} -- y-coordinate. Returns: int -- Value of the matrix. """ offset = matrix_offset(m...
26,474
def rms(vector): """ Parameters ---------- vector Returns ------- """ return np.sqrt(np.mean(np.square(vector)))
26,475
def parse(text): """Parse a tag-expression as text and return the expression tree. .. code-block:: python tags = ["foo", "bar"] tag_expression = parse("foo and bar or not baz") assert tag_expression.evaluate(tags) == True :param text: Tag expression as text to parse. :param...
26,476
def average_distance(points, distance_func): """ Given a set of points and their pairwise distances, it calculates the average distances between a pair of points, averaged over all C(num_points, 2) pairs. """ for p0, p1 in itertools.combinations(points, 2): # assert symmetry assert abs...
26,477
def get_bin_alignment(begin, end, freq): """Generate a few values needed for checking and filling a series if need be.""" start_bin = get_expected_first_bin(begin,freq) end_bin = (end/freq)*freq expected_bins = expected_bin_count(start_bin, end_bin, freq) return start_bin, end_bin, expecte...
26,478
def TagAndFilterWrapper(target, dontRemoveTag=False): """\ Returns a component that wraps a target component, tagging all traffic coming from its outbox; and filtering outany traffic coming into its inbox with the same unique id. """ if dontRemoveTag: Filter = FilterButKeepTag else: ...
26,479
async def test_login_hack(logged_in_page): """Test that logged_in_page is in fact logged in.""" # Wait for elements that should only be present if login succeeded await logged_in_page.waitForXPath('//button[contains(., "Logout")]') await logged_in_page.waitForXPath('//a[contains(., "My Images")]')
26,480
def tweets(url): """tweets count""" try: twitter_url = 'http://urls.api.twitter.com/1/urls/count.json?url=' + url r = requests.get(twitter_url, headers=headers) json_data = json.loads(r.text) return json_data['count'] except: return 0
26,481
def CLJPc(S): """Compute a C/F splitting using the parallel CLJP-c algorithm. CLJP-c, or CLJP in color, improves CLJP by perturbing the initial random weights with weights determined by a vertex coloring. Parameters ---------- S : csr_matrix Strength of connection matrix indicating the...
26,482
def displayTwoDimMapPOST(): """Run displayTwoDimMap""" executionStartTime = int(time.time()) # status and message success = True message = "ok" plotUrl = '' dataUrl = '' # get model, var, start time, end time, lon1, lon2, lat1, lat2, months, scale jsonData = request.json model...
26,483
def encrypt(msg, hexPubkey): """Encrypts message with hex public key""" return pyelliptic.ECC(curve='secp256k1').encrypt( msg, hexToPubkey(hexPubkey))
26,484
def indexing(zDatagridLeft,zDatagridRight,zModelgridLeft,zModelgridRight): """ Searches for closest distances between actual and theorectical points. zDatagridLeft = float - tiled matrix (same values column-wise) of z coordintates of droplet on left side, size = [len(z...
26,485
def torch2np(tensor): """ Convert from torch tensor to numpy convention. If 4D -> [b, c, h, w] to [b, h, w, c] If 3D -> [c, h, w] to [h, w, c] :param tensor: Torch tensor :return: Numpy array """ array, d = tensor.detach().cpu().numpy(), tensor.dim() perm = [0, 2, 3, 1] if d == 4 el...
26,486
def test_api_fetch_single_row_fail(client): """test fetch unexisting single row from API""" fetch = client.get("/api/resolution/10") response = fetch.get_json() response_status = response.get("status") response_message = response.get("message") assert response_status is False assert respon...
26,487
def get_filenames(feature_folder, glob_pattern, sample_size=None): """ Finds the all the files in the given feature folder which matches the glob pattern. :param feature_folder: The folder to search for files. :param glob_pattern: The glob pattern to use for finding files. :param sample_size: If giv...
26,488
def test_3_best(): """s0 iterates; s1~3 are all [[1,0,0],[1,2,1],[2,2,0]]""" most_successes = 0 for raw_strat in itertools.product(range(3), repeat=9): strat = list(chunks(raw_strat, 3)) successes = 0 for hats in itertools.product(range(3), repeat=4): guesses = [...
26,489
def message_to_csv(msg: Any, truncate_length: int = None, no_arr: bool = False, no_str: bool = False) -> str: """ Convert a ROS message to string of comma-separated values. :param msg: The ROS message to convert. :param truncate_length: Truncate values for all message fields to this ...
26,490
def create_message(username, message): """ Creates a standard message from a given user with the message Replaces newline with html break """ message = message.replace('\n', '<br/>') return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username)
26,491
def overlaps(sdf, other): """ Indicates if the intersection of the two geometries has the same shape type as one of the input geometries and is not equivalent to either of the input geometries. ========================= ========================================================= **Argument** ...
26,492
def squarelimit(picture, depth, qstart=1, qstop=4): """Squarelimit is drawn in a triangular style. For the whole picture, 4 triangles forming a square are drawn. """ # no of quarters n = 4 # advance in degrees q = 90 transform(CORNER) scale(1, 1) for i in range(n): pu...
26,493
def render_page(request, page): """Рендер страницы""" if page.registration_required and not request.user.is_authenticated: from django.contrib.auth.views import redirect_to_login return redirect_to_login(request.path) # if page.template: # template = loader.get_template(page.templat...
26,494
def latex_table(report: dict, file_path: str) -> None: """Convert an sklearn style classification report into a LaTeX table and save the result. Args: report (dict): sklearn style classification report. file_path (str): File destination. """ df = prepare_report_df(report) table...
26,495
def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) # 16,16, 7.5, 7.5 return w, h, x_ctr, y_ctr
26,496
def obtener_atletas_pais(atletas: list, pais_interes: str) -> list: """ Función que genera una lista con la información de los atletas del país dado, sin importar el año en que participaron los atletas. Parámetros: atletas: list de diccionarios con la información de cada atleta. pais_in...
26,497
def kl_div_mixture_app(m1, v1, m2, v2, return_approximations=False, return_upper_bound=False): """Approximate KL divergence between Gaussian and mixture of Gaussians See Durrieu et al, 2012: "Lower and upper bounds for approximation of the Kullback-Leibler dive...
26,498
def wilson_primality_test(n: int) -> bool: """ https://en.wikipedia.org/wiki/Wilson%27s_theorem >>> assert all(wilson_primality_test(i) for i in [2, 3, 5, 7, 11]) >>> assert not all(wilson_primality_test(i) for i in [4, 6, 8, 9, 10]) """ return ((factorial_lru(n - 1) + 1) % n) == 0
26,499