content
stringlengths
22
815k
id
int64
0
4.91M
def random_value(t): """ Construct a stream of values in type t """ if isinstance(t, TBag): yield Bag() for v in random_value(t.elem_type): yield Bag((v,)) for v1 in random_value(t.elem_type): for v2 in random_value(t.elem_type): yield Bag(...
5,357,400
def get_pool_name(pool_id): """Returns AS3 object name for TLS profiles related to pools :param pool_id: octavia pool id :return: AS3 object name """ return "{}{}".format(constants.PREFIX_TLS_POOL, pool_id)
5,357,401
def simulate_processing(): """Simulate daily processing and capture provenance.""" options.simulate = True options.test = True sequence_list = build_sequences(options.date) # simulate data calibration and reduction for sequence in sequence_list: processed = False for sub_list i...
5,357,402
def search_sliceable_by_yielded_chunks_for_str(sliceable, search_string, starting_index, down, case_insensitive): """This is the main entry point for everything in this module.""" for chunk, chunk_start_idx in search_chunk_yielder(sliceable, starting_index, down): found_at_chunk_idx = search_list_for_st...
5,357,403
def split_page(array, limit, index): """ 按限制要求分割数组,返回下标所指向的页面 :param array: 需要分割的数组 :param limit: 每个数组的大小 :param index: 需要返回的分割后的数组 :return: 数组 """ end = index * limit start = end - limit return array[start:end]
5,357,404
def update_metadata(desc, key, value): """ Update the metadata of a package descriptor. If the key doesn't exist in the metadata yet the key-value pair is added. If the key exists and the existing value as well as the passed value are dictionaries the existing value is updated with the passed valu...
5,357,405
def creatKdpCols(mcTable, wls): """ Create the KDP column Parameters ---------- mcTable: output from getMcSnowTable() wls: wavelenght (iterable) [mm] Returns ------- mcTable with an empty column 'sKDP_*' for storing the calculated KDP of a given wavelength. """ ...
5,357,406
def create_db(): """Creates the db tables.""" db.create_all()
5,357,407
def test_range(init, final): """Test a range of numbers, using range with initial and final values.""" init = validate_num(init) final = validate_num(final) if init and final and final > init: final += 1 for i in range(init, final): steps = 0 new_value = i ...
5,357,408
def get_products_by_user(user_openid, allowed_keys=None, filters=None): """Get all products that user can manage.""" return IMPL.get_products_by_user(user_openid, allowed_keys=allowed_keys, filters=filters)
5,357,409
def sample_from_ensemble(models, params, weights=None, fallback=False, default=None): """Sample models in proportion to weights and execute with model_params. If fallback is true then call different model from ensemble if the selected model throws an error. If Default is not None then return default if ...
5,357,410
def Flatten(matrix): """Flattens a 2d array 'matrix' to an array.""" array = [] for a in matrix: array += a return array
5,357,411
def create_verification_token( data: dict ) -> VerificationTokenModel: """ Save a Verification Token instance to database. Args: data (dictionary): Returns: VerificationToken: Verification Token entity of VerificationTokenModel object Raises: None """ ...
5,357,412
def upload_file(file_name, bucket, s3_client, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param s3_client: boto3 s3 client :param object_name: S3 object name. If not specified then file_name is used :return: True if fi...
5,357,413
def _find_highest_cardinality(arrays: Union[int, Sequence, np.ndarray, Tuple]) -> int: """Find the highest cardinality of the given array. Args: arrays: a list of arrays or a single array Returns: The highest cardinality of the given array. """ return max([len(array) for array in ...
5,357,414
def get_yesterday() -> tuple: """Get yesterday`s date and split it to year,month and day strings""" logging.debug("Starting get_yesterday function.") today = datetime.now(pytz.timezone("America/New_York")) yesterday = (today - timedelta(days=1)).strftime("%Y-%m-%d") yesterday_split = yesterday.split...
5,357,415
def rowmap(table, rowmapper, header, failonerror=False): """ Transform rows via an arbitrary function. E.g.:: >>> import petl as etl >>> table1 = [['id', 'sex', 'age', 'height', 'weight'], ... [1, 'male', 16, 1.45, 62.0], ... [2, 'female', 19, 1.34, 55.4], ...
5,357,416
def squeeze(dataset, how: str = 'day'): """ Squeezes the data in dataset by close timestamps Args: dataset (DataFrame) - the data to squeeze how (str) - one of 'second', 'minute', 'hour', 'day', 'month' (default day) Returns: dataset (DataFrame) - a dataframe where the indexes are squeez...
5,357,417
def callback(): """ Process response for "Login" try from Dropbox API. If all OK - redirects to ``DROPBOX_LOGIN_REDIRECT`` url. Could render template with error message on: * oAuth token is not provided * oAuth token is not equal to request token * Error response from Dropbox API Def...
5,357,418
def get_ws_param(args, attr): """get the corresponding warm start parameter, if it is not exists, use the value of the general parameter""" assert hasattr(args, attr), 'Invalid warm start parameter!' val = getattr(args, attr) if hasattr(args, 'ws_' + attr): ws_val = getattr(args, 'ws_' + attr) ...
5,357,419
def _redundant_relation(lex: lmf.Lexicon, ids: _Ids) -> _Result: """redundant relation between source and target""" redundant = _multiples(chain( ((s['id'], r['relType'], r['target']) for s, r in _sense_relations(lex)), ((ss['id'], r['relType'], r['target']) for ss, r in _synset_relations(lex)),...
5,357,420
def get_ph_bs_symm_line(bands_path, has_nac=False, labels_dict=None): """ Creates a pymatgen PhononBandStructure from a band.yaml file. The labels will be extracted from the dictionary, if present. If the 'eigenvector' key is found the eigendisplacements will be calculated according to the formula:...
5,357,421
def get_peer_ip(result_host_dic: dict): """ find peer multi address based on peerID :param result_host_dic: [provider_peerID : who provides (peerID)] :return: dic {provider_peerID : Address[]} """ provider_ip = {} for peer in result_host_dic.keys(): process = subprocess.Popen(['/root...
5,357,422
def LinterPath(): """Ascertain the dxl.exe path from this .py files path because sublime.packages_path is unavailable at startup.""" ThisPath = abspath(dirname(__file__)) if isfile(ThisPath): # We are in a .sublime-package file in the 'Installed Package' folder return abspath(join(ThisPath, ...
5,357,423
def encrypt_and_encode(data, key): """ Encrypts and encodes `data` using `key' """ return base64.urlsafe_b64encode(aes_encrypt(data, key))
5,357,424
def yum(packages): """Install yum packages. Args: packages (list): Yum packages to install. """ try: if not shutil.which("yum"): return logging.info('Installing prerequisites using "yum".') devtools = "sudo -E yum groupinstall -y --skip-broken " '"Developme...
5,357,425
def _get_undelimited_identifier(identifier): """ Removes delimiters from the identifier if it is delimited. """ if pd.notna(identifier): identifier = str(identifier) if _is_delimited_identifier(identifier): return identifier[1:-1] return identifier
5,357,426
def yield_rxn_syst(output_dir, pars, file=None, verbose=False): """ Iterate over reaction systems for analysis. """ if file is None: react_syst_files = sorted(glob.glob(join( output_dir, 'sRS-*.gpkl' ))) else: react_syst_files = [] with open(...
5,357,427
def build_movie_json(mongodb_result, hug_timer): """ For reducing the duplicate lines in the 'get_goat_movies' function. TODO: Modify nodejs code if integrating this info! """ combined_json_list = [] movie_vote_quantities = [] for result in mongodb_result: #print(result) total_votes = int(result['goat_upvot...
5,357,428
def _pick_keywords(db): """ Go thru downloaded data stored in `db` and filter keywords, which are parsed and then yielded. Shows nice progress bar. Args: db (obj): Opened database connection. Yields: obj: :class:`KeywordInfo` instances for yeach keyword. """ for key, v...
5,357,429
def has_product_been_used(uuid): """Check if this product has been used previously.""" existing = existing_processed_products() if not isinstance(existing, pd.DataFrame): return False has_uuid = not existing.query("uuid == @uuid").empty return has_uuid
5,357,430
def _FilterMemberData( mr, owner_ids, committer_ids, contributor_ids, indirect_member_ids, project): """Return a filtered list of members that the user can view. In most projects, everyone can view the entire member list. But, some projects are configured to only allow project owners to see all member...
5,357,431
def escape_name(name): """Escape sensor and request names to be valid Python identifiers.""" return name.replace('.', '_').replace('-', '_')
5,357,432
def show_user_following(user_id): """Show list of people this user is following.""" user = User.query.get_or_404(user_id) return render_template('users/following.html', user=user)
5,357,433
def sqlsplit(sql, delimiter=";"): """A generator function for splitting out SQL statements according to the specified delimiter. Ignores delimiter when in strings or comments.""" tokens = re.split("(--|'|\n|" + re.escape(delimiter) + "|\"|/\*|\*/)", sql if isString(sql) else delimiter...
5,357,434
def logout(): """ This API revokes all the tokens including access and refresh tokens that belong to the user. """ current_user = get_jwt_identity() logout_user(current_user.get('id')) return jsonify(message="Token revoked."), 200
5,357,435
def multiset_counter(mset): """ Return the sum of occurences of elements present in a token ids multiset, aka. the multiset cardinality. """ return sum(mset.values())
5,357,436
def get_v6_subnet(address): """derive subnet number for provided ipv6 address Args: address (str): ipv6 address in string with mask Returns: str: subnet zero == network address """ return IPv6(address).subnet_zero()
5,357,437
def get_ros_package_path(env=None): """ Get the current ROS_PACKAGE_PATH. :param env: (optional) environment override, ``dict`` """ if env is None: env = os.environ return env.get(ROS_PACKAGE_PATH, None)
5,357,438
def load_scenario(file_name: str) -> Waypoint: """ Create an object Waypoint from a Scenario file :param file_name: :return: """ # read file with open(f"{waypoint_directory_path}/{file_name}", "r") as scenario_file: scenario_data = yaml.load(scenario_file, Loader=yaml.FullLoader) ...
5,357,439
def parseArguments(argv=None): # pragma: no cover """ I parse arguments in sys.argv and return the args object. The parser itself is available as args.parser. Adds the following members to args: parser = the parser object store_opt = the StoreOpt object """ store_opt = Stor...
5,357,440
def parse_example(serialized_example): """Parse a serialized example proto.""" features = tf.io.parse_single_example( serialized_example, dict( beam_id=tf.io.FixedLenFeature(shape=[], dtype=tf.int64), image_id=tf.io.FixedLenFeature(shape=[], dtype=tf.int64), question_id=tf....
5,357,441
def save_data(df): """ Save Data to SQLite Database """ #engine = create_engine('sqlite:///' + database_filepath) df.to_csv('data/messages_response.csv', index=False)
5,357,442
def _compute_bootstrap_quantiles_point_estimate_custom_bias_corrected_method( metric_values: np.ndarray, false_positive_rate: np.float64, n_resamples: int, random_seed: Optional[int] = None, ) -> Tuple[Number, Number]: """ An internal implementation of the "bootstrap" estimator method, returning...
5,357,443
def dem_plot(workdir, project_name, **kwargs): """ DEM3D creates a 3D representation from a Grass DEM file """ length = 1 width = 1 # Read the Header # str_hd_dem = {'north':0,'south':0,'east':0,'west':0,'rows':0,'cols':0} str_hd_dem = {} with open( os.path.join(workdir, pr...
5,357,444
def test_snail_attributes(): """Test snail attributes.""" s = Snail() assert s.nlate == 0 assert s.deaths == 0 assert s.nlate_max == -1 assert not s.active assert s.delay_max == 0.0 assert s.delay == 0.0
5,357,445
def bytes_to_b64(data: bytes, remove_padding=True) -> str: """ byte string to URL safe Base64 string, with option to remove B64 LSB padding :param data: byte string :param remove_padding: remove b64 padding (``=`` char). True by default :return: base64 unicode string """ text = urlsafe_b64e...
5,357,446
def _case_sensitive_replace(string, old, new): """ Replace text, retaining exact case. Args: string (str): String in which to perform replacement. old (str): Word or substring to replace. new (str): What to replace `old` with. Returns: repl_string (str): Version of stri...
5,357,447
def test_read_message_with_parent_process_dead_and_should_not_exit(os): """ Test simple worker processes exit when parent is dead and shutdown is not set when reading messages """ # Setup SQS Queue conn = boto3.client('sqs', region_name='us-east-1') queue_url = conn.create_queue(QueueName="t...
5,357,448
def testauth(): """Tests auth-related functions""" # check the hashpass() base function p = 'dofij' pw = hashpass(p) print pw x = hashpass(p, pw) print x assert x == pw, 'The two passes should be identical' # check the auth() wrapper u = 'user 1' p = 'user password' hashp...
5,357,449
def deserialize_transaction_from_etherscan( data: Dict[str, Any], internal: bool, ) -> EthereumTransaction: """Reads dict data of a transaction from etherscan and deserializes it Can throw DeserializationError if something is wrong """ try: # internal tx list contains no gaspric...
5,357,450
def ar(p): """ Given a quaternion p, return the 4x4 matrix A_R(p) which when multiplied with a column vector q gives the quaternion product qp. Parameters ---------- p : numpy.ndarray 4 elements, represents quaternion Returns ------- numpy.ndarray 4x4 matrix des...
5,357,451
def preprocess_list(lst,tokenizer,max_len=None): """ function preprocesses a list of values returning tokenized sequences Args: lst: list of strings to be processed tokenizer: a tokenizer object max_len: if we need to ensure the same length of strings, we can provide an integer here...
5,357,452
def get_GEOS5_as_ds_via_OPeNDAP(collection='inst3_3d_aer_Nv', fcast_start_hour=12, mode='seamless', dt=None): """ Get the GEOS-5 model product (GEOS-5) as a xr.Dataset (using OPeNDAP) Parameters ---------- mode (str): retrieve the fore...
5,357,453
def to_dataframe(ticks: list) -> pd.DataFrame: """Convert list to Series compatible with the library.""" df = pd.DataFrame(ticks) df['time'] = pd.to_datetime(df['time'], unit='s') df.set_index("time", inplace=True) return df
5,357,454
def initialize_conditions(segment): """Sets the specified conditions which are given for the segment type. Assumptions: Descent segment with a constant rate. Source: N/A Inputs: segment.altitude [meters] segment.tim [second] ...
5,357,455
def keysCode(code): """ Download user's keys from an email link GET: If the code is valid, download user keys Else abort with a 404 """ #Check if code exists and for the correct purpose. Else abort if (hl.checkCode(code,"Keys")): user = hl.getUserFromCode(code) ...
5,357,456
def lengthenFEN(fen): """Lengthen FEN to 71-character form (ex. '3p2Q' becomes '111p11Q')""" return fen.replace('8','11111111').replace('7','1111111') \ .replace('6','111111').replace('5','11111') \ .replace('4','1111').replace('3','111').replace('2','11')
5,357,457
def keyboard_mapping(display): """Generates a mapping from *keysyms* to *key codes* and required modifier shift states. :param Xlib.display.Display display: The display for which to retrieve the keyboard mapping. :return: the keyboard mapping """ mapping = {} shift_mask = 1 << 0 ...
5,357,458
def convertPeaks(peaksfile, bedfile): """Convert a MACS output file `peaksfile' to a BED file. Also works if the input is already in BED format.""" regnum = 1 with open(bedfile, "w") as out: with open(peaksfile, "r") as f: tot = 0 chrom = "" start = 0 ...
5,357,459
def run(): """Starts the node Runs to start the node and initialize everthing. Runs forever via Spin() :returns: Nothing :rtype: None """ rospy.init_node('yumi_trials', anonymous=True) # Positions measured # x positions x_inizio = 0.150 # [m] # Length of desk in x direction ...
5,357,460
def set_workspace(path=None): """ Set a custom workspace for use """ if not Settings.InstaPy_is_running: if path: path = verify_workspace_name(path) workspace_is_new = differ_paths(WORKSPACE["path"], path) if workspace_is_new: update_workspace(path) ...
5,357,461
def create_freud_box(box: np.ndarray, is_2D=True) -> Box: """Convert an array of box values to a box for use with freud functions The freud package has a special type for the description of the simulation cell, the Box class. This is a function to take an array of lengths and tilts to simplify the crea...
5,357,462
def hrrr_snotel_pixel(file, x_pixel_index, y_pixel_index): """ Read GRIB file surface values, remove unsed dimensions, and set the time dimension. Required to be able to concatenate all GRIB file to a time series """ hrrr_file = xr.open_dataset( file.as_posix(), engine='cfgrib',...
5,357,463
def write_model_inputs( scenario_directory, scenario_id, subscenarios, subproblem, stage, conn ): """ Get inputs from database and write out the model input transmission_lines.tab file. :param scenario_directory: string, the scenario directory :param subscenarios: SubScenarios object with all su...
5,357,464
def convert_to_diact_uttseg_interactive_tag(previous, tag): """Returns the dialogue act but with the fact it is keeping or taking the turn. """ if not previous: previous = "" trp_tag = uttseg_pattern(tag) return trp_tag.format(convert_to_diact_interactive_tag(previous, tag))
5,357,465
def refresh(app): """Refresh all migrations. Arguments: app (App): Main Service Container """ app.make('migrator').refresh()
5,357,466
def allocate_gpio_pins(project_json, ip_json) -> None: """ Goes through the project, finds unassigned "GPIO" pinmaps, assigns them to unclaimed GPIO pins in ascending order of pins and order of appearance of modules. :param project_json: :param ip_json: :return: Edits project_json in place ...
5,357,467
def R12(FMzul, FAmax, FZ, alphaA, Phi_en, qF = 1, muTmin = 1, qM = 1, ra = 1, Atau = 1, Rm = 1, tauB = 1, deltaFVth = 1, FQmax = 1, MYmax = 1): """ R12 Determining the safety margin against slipping SG and the shearing stress tauQmax (Sec 5.5.6) --- FMzul FAmax F...
5,357,468
def compute_good_coils(raw, t_step=0.01, t_window=0.2, dist_limit=0.005, prefix='', gof_limit=0.98, verbose=None): """Comute time-varying coil distances.""" try: from mne.chpi import compute_chpi_amplitudes, compute_chpi_locs except ImportError: chpi_locs = _old_chpi_l...
5,357,469
def prep_request(items, local_id="id"): """ Process the incoming items into an AMR request. <map name="cite_1"> <val name="{id_type}">{value}</val> </map> """ map_items = ET.Element("map") for idx, pub in enumerate(items): if pub is None: continue local_i...
5,357,470
def calc_variables ( ): """Calculates all variables of interest. They are collected and returned as a list, for use in the main program. """ # In this example we simulate using the cut (but not shifted) potential # but we only report results which have had the long-range corrections applied # ...
5,357,471
def analyse_results_ds_one_station(dss, field='WetZ', verbose=None, plot=False): """analyse and find an overlapping signal to fields 'WetZ' or 'WetZ_error' in dss""" # algorithm for zwd stitching of 30hrs gipsyx runs: # just take the mean of the two overlapping signals...
5,357,472
def check_gradients(m: torch.nn.Module, nonzero: bool) -> None: """ Helper function to test whether gradients are nonzero. """ for param in m.parameters(): if nonzero: assert (param.grad != 0).any() else: assert param.grad is None or (param.grad == 0).all()
5,357,473
def findDocument_MergeFields(document): """this function creates a new docx document based on a template with Merge fields and a JSON content""" the_document = MailMerge(document) all_fields = the_document.get_merge_fields() res = {element:'' for element in all_fields} return res
5,357,474
def load_mushroom(data_home=None, return_dataset=False): """ Loads the mushroom multivariate dataset that is well suited to binary classification tasks. The dataset contains 8123 instances with 3 categorical attributes and a discrete target. The Yellowbrick datasets are hosted online and when reque...
5,357,475
def get_current_project(user_id): """Return from database user current project""" try: current = CurrentProject.objects.get(user_id=user_id) except CurrentProject.DoesNotExist: return None keystone = KeystoneNoRequest() return keystone.project_get(current.project)
5,357,476
def main() -> None: """ Loads the configration files and then attempts to start the WDS and flask processes accordingly. """ config: Union[config_loader.ConfigTemplate, None] = None # Allow setting config file from cli if "--config-file" in sys.argv: config = config_loader....
5,357,477
def docstring(app, what, name, obj, options, lines): """Converts doc-strings from (Commonmark) Markdown to reStructuredText.""" md = '\n'.join(lines) ast = commonmark.Parser().parse(md) rst = commonmark.ReStructuredTextRenderer().render(ast) lines.clear() lines += rst.splitlines()
5,357,478
def cmd_busca_fundo(args): """Busca informacoes cadastral sobre os fundos.""" inf_cadastral = Cadastral() inf_cadastral.cria_df_cadastral() if args.cnpj: inf_cadastral.mostra_detalhes_fundo(args.cnpj) else: fundo = inf_cadastral.busca_fundos(args.name, args.type, args.all) if...
5,357,479
def get_random_successful_answer(intent: str) -> str: """ Get a random successful answer for this intent * `intent`: name-parameter of the yml-section with which the successful answers were imported **Returns:** None if no successful answers are known for this intent, otherwise a random eleme...
5,357,480
def formatter( source: str, language: str, css_class: str, options: dict[str, Any], md: Markdown, classes: list[str] | None = None, id_value: str = "", attrs: dict[str, Any] | None = None, **kwargs: Any, ) -> str: """Execute code and return HTML. Parameters: source: ...
5,357,481
def generate(): """ Command to generate faces with a trained model. """ parser = argparse.ArgumentParser( description = "Generate faces using a trained model.", usage = "faces [<args>]", ) parser.add_argument('-m', '--model', type=str, required=True, help= ...
5,357,482
def test_custom_class_no_backends(UseBackend: HasBackends): """Ensures custom defined test class does not have registered backends.""" assert len(UseBackend.get_backends()) == 0
5,357,483
def find_visible(vertex_candidates, edges_to_check): """ # IMPORTANT: self.translate(new_origin=query_vertex) always has to be called before! (for computing the angle representations wrt. the query vertex) query_vertex: a vertex for which the visibility to the vertices should be checked. als...
5,357,484
def gather_data( network_stats: Iterable, start_time: int, end_time: int, step: int ) -> Dict: """This function takes Prometheus data and reshapes it into a multi-level dictionary of network name to link name to link dir to list of values.""" label_val_map: defaultdict = defaultdict( lambda: de...
5,357,485
def delete_protection(ProtectionId=None): """ Deletes an AWS Shield Advanced Protection . See also: AWS API Documentation :example: response = client.delete_protection( ProtectionId='string' ) :type ProtectionId: string :param ProtectionId: [REQUIRED] ...
5,357,486
def get_balance_sheet(ticker, limit, key, period): """Get the Balance sheet.""" URL = 'https://financialmodelingprep.com/api/v3/balance-sheet-statement/' try: r = requests.get( '{}{}?period={}&?limit={}&apikey={}'.format(URL, ...
5,357,487
def softmax_loss(scores, y): """ Computes the loss and gradient for softmax classification. Inputs: - scores: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input. - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and 0 <= y[i] <...
5,357,488
def load_flags(save_dir, save_file="flags.obj"): """ This function inflate the pickled object to flags object for reuse, typically during evaluation (after training) :param save_dir: The place where the obj is located :param save_file: The file name of the file, usually flags.obj :return: flags ...
5,357,489
def text_to_lines(path): """ Parse a text file into lines. Parameters ---------- path : str Fully specified path to text file Returns ------- list Non-empty lines in the text file """ delimiter = None with open(path, encoding='utf-8-sig', mode='r') as f: ...
5,357,490
def measure_hemijunctions_timelapse(ims_labels, ims_labels_hjs): """ Measure the hemijunction traits from a timelapse of a live-imaged epithelium. Parameters ---------- ims_labels : 3D ndarray (t,y,x) Each timepoint is a 2D array with labeled regions. ims_labels_hjs : 3D ndarray (t,y,x)...
5,357,491
def get_compare_tables_checks_tasks(): """Get list of tasks that will compare tables checks between databases. Args: Returns: list: list of tasks to be executed in a process pool. Each item is a dict instance with following strucutre: { 'function' (f...
5,357,492
def label_pr_failures(pull: Union[PullRequest, ShortPullRequest]) -> Set[str]: """ Labels the given pull request to indicate which checks are failing. :param pull: :return: The new labels set for the pull request. """ pr_checks = get_checks_for_pr(pull) failure_labels: Set[str] = set() success_labels: Set[s...
5,357,493
def test_index_is_target(): """Assert that an error is raised when the index is the target column.""" with pytest.raises(ValueError, match=r".*same as the target column.*"): ATOMClassifier(X_bin, index="worst fractal dimension", random_state=1)
5,357,494
def _replace_folder_path(path: str, from_folder: str, to_folder: str) -> Optional[str]: """Changes the path from the source ('from') folder to the destination ('to') folder Arguments: path: the path to adjust from_folder: the folder to change from to_folder: the folder to change the path...
5,357,495
def arrange_images(total_width, total_height, *images_positions): """Return a composited image based on the (image, pos) arguments.""" result = mel.lib.common.new_image(total_height, total_width) for image, pos in images_positions: mel.lib.common.copy_image_into_image(image, result, pos[1], pos[0])...
5,357,496
def import_core_utilities() -> Tuple[ModuleType, ModuleType, ModuleType]: """Dynamically imports and return Tracing, Logging, and Metrics modules""" return ( importlib.import_module(TRACING_PACKAGE), importlib.import_module(LOGGING_PACKAGE), importlib.import_module(METRICS_PACKAGE), ...
5,357,497
def create_folders(*folders): """ Utility for creating directories :param folders: directory names :return: """ for folder in folders: os.makedirs(folder, exist_ok=True)
5,357,498
def pancakeSort(self, A): # ! 这个方法实际上是在每轮循环中寻找最大的那个数,使其在正确的位置 """ :type A: List[int] :rtype: List[int] """ bucket = sorted(A) ans = [] for k in range(len(A),0,-1): i = A.index(bucket.pop())+1 ans += [i, k] A = A[i:k][::-1] + A[:i] + A[k:] prin...
5,357,499