content
stringlengths
22
815k
id
int64
0
4.91M
def write_multiple_score_matrix_box_plot( evaluation_result: DefaultScoreMatrixResult, plot_filepath: str ): """Generate the score matrix box plot comparing multiple datasets and write it as html file.""" score_matrices = [er.overall_score_matrix for er in evaluation_result] dataset_names = [er.data...
5,291,000
def d2vardx2(var, lon, lat, xdim, ydim, cyclic=True, sphere=True): """ calculate second center finite difference along x or longitude. https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py :param var: ndarray, grid values. :param lon: array_like, longitude ...
5,291,001
def docker_login(username, password, registry): """ Performs docker login to a specified ecr region. Parameters __________ username: str Docker registry username password: str Docker registry password registry: AuthData.registry AWS Region to authenticate to. """ docker_client = docker.fro...
5,291,002
def get_chain() -> str: """ Endpoint to query all of the data to display """ chain_data = [] for block in blockchain.chain: chain_data.append(block.__dict__) return json.dumps({"length": len(chain_data), "chain": chain_data})
5,291,003
def read_terrace_csv(DataDirectory,fname_prefix): """ This function reads in the csv file with the extension "_terrace_info.csv" and returns it as a pandas dataframe Args: DataDirectory (str): the data directory fname_prefix (str): the name of the DEM Returns: pandas datafr...
5,291,004
def eval_net(net, loader, device, n_val): """Evaluation without the densecrf with the dice coefficient""" net.eval() tot = 0 with tqdm(total=n_val, desc='Validation round', unit='img', leave=False) as pbar: for batch in loader: imgs = batch['image'] true_masks = batch['m...
5,291,005
def load_image(file_path, average=True): """ Load data from an image. Parameters ---------- file_path : str Path to a file. average : bool, optional Average a multi-channel image if True. Returns ------- array_like """ if "\\" in file_path: raise Val...
5,291,006
def test_AsciiDataTable_to_XmlDataTable(input_file="700437.asc"): """Tests a one port ascii data table to an XmlDataTable transformation and saves the result in the tests directory. The one port file should be the output of Calrep7.1 or similar.""" os.chdir(TESTS_DIRECTORY) one_port=OnePortRawModel(...
5,291,007
def interp(frame, idx, **args): """ Get interpolated values at indices """ unique_idx = [i for i in idx if i not in frame.index] aug_frame = frame.append(pd.DataFrame(index=unique_idx), sort=True) in_frame = aug_frame.sort_index().interpolate('index', **args) return in_frame.loc[idx, frame.columns]
5,291,008
def test_fit_selfconsist(): """ Tests that the masses we get from orbitize! are what we expeect. Note that this does not test for correctness. """ # generate planet b orbital parameters b_params = [1, 0, 0, 0, 0, 0.5] tau_ref_epoch = 0 mass_b = 0.001 # Msun m0 = 1 # Msun plx = 1 # ma...
5,291,009
def calcStateTransitionMatrix(orbit, dt, mu=0.0002959122082855911, max_iter=100, tol=1e-15): """ Calculate the state transition matrix for a given change in epoch. The state transition matrix maps deviations from a state at an epoch t0 to a different epoch t1 (dt = t1 - t0). Parameters ---------- ...
5,291,010
def macro_calc(item): """ Calculate PPV_Macro and TPR_Macro. :param item: PPV or TPR :type item:dict :return: PPV_Macro or TPR_Macro as float """ try: item_sum = sum(item.values()) item_len = len(item.values()) return item_sum / item_len except Exception: ...
5,291,011
def convert_from_pj_fat_food(pj_fat_food): """ Convert the given PyJSON Fat-Food to a Natural :param pj_fat_food: The PyJSON Fat-Food being converted :type pj_fat_food: PJ_FatFood :return: The resulting Natural :rtype: Natural """ if not is_pj_fat_food(pj_fat_food): raise ValueError(...
5,291,012
def raw_to_multiindex(raw_df, name): """ Takes a raw dataframe (vertically oriented) and transforms it in a multiindexed one. The indices are (date, feature). """ iterables = [raw_df.index, raw_df.columns] index = pd.MultiIndex.from_product(iterables, names=[DATE_COL, FEATURE_COL]) data_df =...
5,291,013
def sizeof_fmt(num, suffix='B'): """Size to human readable format. From stack overflow. """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
5,291,014
def clear_queue(queue_name): """Clear all Requests in the given queue Will iterate through all requests on a queue and mark them as "CANCELED". :param queue_name: The queue to clean :raises InvalidSystem: If the system_name/instance_name does not match a queue """ queue.clear(queue_name)
5,291,015
def patch_resource(step: model.Step) -> None: """Perform the Verb "patch" for given test step. It results in patching custom resource inside Kubernetes cluster per the specification from the step. Args: step: test step Returns: None """ logging.debug(f"patch: {step}") if n...
5,291,016
def op_register(tag: str, selector: str, info: str, min_version: Optional[str] = None): """ Decorator used for registering operational-data items with the op catalog. The class being decorated needs to be a subclass of OperationalItem. @param tag: Tag string associated with this item. String 'all' is re...
5,291,017
def macdext(candles: np.ndarray, fast_period: int = 12, fast_matype: int = 0, slow_period: int = 26, slow_matype: int = 0, signal_period: int = 9, signal_matype: int = 0, source_type: str = "close", sequential: bool = False) -> MACDEXT: """ MACDEXT - MACD with controllable MA type :...
5,291,018
def group_gene_records_from_sorted_genbank( record_iter: Iterator[SeqRecord], parse_func: Callable[[GeneFeature], Dict[str, Any]], feature_parse_func: Callable[[FeatureIntervalGenBankCollection], Dict[str, Any]], ) -> Iterator[ParsedAnnotationRecord]: """Model 1: position sorted GenBank. This funct...
5,291,019
def user_info(): """ 个人中心 :return: """ user = g.user if not user: return credits("/") data = { "user_info":user.to_dict() } return render_template("/news/user.html", data=data)
5,291,020
def height_implied_by_aspect_ratio(W, X, Y): """ Utility function for calculating height (in pixels) which is implied by a width, x-range, and y-range. Simple ratios are used to maintain aspect ratio. Parameters ---------- W: int width in pixel X: tuple(xmin, xmax) x-range i...
5,291,021
def convert_to_valid(seq, correction_dictionary=None, alignment=False): """ Function that converts non-standard amino acid residues to standard ones. Specifically: B -> N U -> C X -> G Z -> Q ' ' -> <empty string> (i.e. an empty space) * -> <empty string> - -> <empty string> (ON...
5,291,022
def CTPixel8_getPixelName(): """CTPixel8_getPixelName() -> char const *""" return _VPLPython.CTPixel8_getPixelName()
5,291,023
def get_output_folder_path(provided_folder_path, first_font_path): """ If the path to the output folder was NOT provided, create a folder in the same directory where the first font is. If the path was provided, validate it. Returns a valid output folder. """ if provided_folder_path: ...
5,291,024
def create_access_token(identity: str) -> bytes: """Create a jwt based on identity.""" payload = { "identity": identity, "exp": datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS), } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) # type: ignore return jwt_token
5,291,025
def apply_vs30_mod_non_parametric( im_values: pd.DataFrame, site_info: site.SiteInfo, im: IM ) -> pd.Series: """Applies the user vs30 modification for non-parametric data""" assert "PGA" in im_values.columns pga = im_values["PGA"].copy() return im_values[str(im)] * __get_site_amp_ratio( pga...
5,291,026
def test_multiplicative_seasonality( seasonal_type, trig_function, seasonality, amplitude, maximum, abs_cum_sum, sum_forecast, ): """Testing multiplicative seasonality (no trend or level events).""" jp = JudgyProphet() multiplicative_seasonal_data = _create_seasonal_data( ...
5,291,027
def test_invalid_dates(value, expected_errors): """Verify that invalid date values are detected correctly.""" record = DRecord() record.field = value assert record.validation_errors == expected_errors
5,291,028
def find_all_landroid_ljava_over(smali_file_list): """Find all the class definition subclasses of an SDK class""" for smali_file in smali_file_list: # For each file for smali_line in u.open_file_input(smali_file): # For each line class_match = re.search(r'^([ ]*?)\.class(.*?)(?P<class...
5,291,029
def calc_earfcn(low_freq_hz: int, high_freq_hz: int) -> int: """ Calculate EARFCN in mhz for CBRS Args: low_freq_hz: int, Low frequency limit taken from available channel high_freq_hz: int, High frequency limit taken from available channel Returns: EARFCN in mhz """ mid...
5,291,030
def sortino_ratio(returns, required_return=0, period=DAILY): """ Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. returns_s...
5,291,031
def test_read_notebooks_magic_lines(name, path, expect_err, config): """ Tests magic line parsing in notebooks, with edge-cases like multiline strings containing what appear to be multiline strings. """ notebook_dict = read_notebook(path) if expect_err: with pytest.raises(SyntaxError): ...
5,291,032
def test_extra_space_cleaner(): """Testing that cleaner removes extra spaces.""" dirty_text = " there is lots of spaces here " cleaned_text = cleaner(dirty_text) assert cleaned_text == "there is lots of spaces here"
5,291,033
def confusion_matrix( prediction_detections: ndarray, truth_detections: ndarray, threshold: float = DEFAULT_NEG_THRESHOLD, num_foreground_classes: int = 3, ) -> np.ndarray: """ Compute confusion matrix to evaluate the accuracy of a classification. By definition a confusion matrix :math:`C` is s...
5,291,034
def subsol_vector(str1, str2, in11, str3, str4): """subsol_vector(ConstSpiceChar * str1, ConstSpiceChar * str2, ConstSpiceDouble * in11, ConstSpiceChar * str3, ConstSpiceChar * str4)""" return _cspyce0.subsol_vector(str1, str2, in11, str3, str4)
5,291,035
def step_impl(context): """ Delete all Wishlists and load new ones """ headers = {'Content-Type': 'application/json'} #context.resp = requests.delete(context.base_url + '/wishlist/reset', headers=headers) #assert context.resp.status_code == 204 create_url = context.base_url + '/wishlists/1' for ...
5,291,036
def compute_per_char(ground_truth, predictions): """ compute per char accuracy :param ground_truth: :param predictions: :return: """ accuracy = [] for index, label in enumerate(ground_truth): prediction = predictions[index] total_count = len(label) correct_count =...
5,291,037
def getBinaryFormat(name: str) -> type[BinaryFormat]: """ Looks up a binary format by its name attribute. Returns the binary format with the given value for its name attribute. Raises KeyError if there is no match. """ return _formatsByName[name]
5,291,038
def cholesky_method( A, B=None, gram=False, exponent=1, invert_cholesky=True, cholmod=None): """ Computes trace of inverse of matrix using Cholesky factorization by .. math:: \\mathrm{trace}(\\mathbf{A}^{-1}) = \\| \\mathbf{L}^{-1} \\|_F^2 where...
5,291,039
def extractNextlevelforthePLOT(item): """ 'Next level for the PLOT' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp is not None or vol is not None or frag is not None) or 'preview' in item['title'].lower(): return None if 'scan-trad' in item['tags']: return None ...
5,291,040
def kitti_squeezeSeg16_config(): """Specify the parameters to tune below.""" mc = base_model_config('KITTI') mc.CLASSES = ['unknown', 'car', 'pedestrian', 'cyclist'] mc.NUM_CLASS = len(mc.CLASSES) mc.CLS_2_ID = dict(zip(mc.CLASSES, range(len(mc.CLASSES)))) mc...
5,291,041
def main(): """The main function of the script""" cleaned_results_file_name = "cleaned_tr_representation_" + \ "experiment_results.json" mozilla_exp_2_results_plotter = \ MozillaExp2ResultsPlotter(cleaned_results_file_name) mozilla_exp_2_results_plotter.plot_results()
5,291,042
def get(args): """ Copy file from the repository :param args: dict :return: None """ repo = _checkRepo() tags = _get_repo_tags() filename = os.path.basename(args.file) if os.path.isfile(os.path.expanduser(args.target)): sys.exit("File already exists at {}".format(os.path.j...
5,291,043
def filter_modules(command_loader, help_file_entries, modules=None, include_whl_extensions=False): """ Modify the command table and help entries to only include certain modules/extensions. : param command_loader: The CLICommandsLoader containing the command table to filter. : help_file_entries: The dict of...
5,291,044
def read_scan_options(config): """Read the Options from the configuration file.""" options_dict = get_config_section_dict(config, SECTION_OPTIONS) # vprint("options_dict: " + str(options_dict)) if options_dict is not None: # Check for license scan slack length option # Set global variabl...
5,291,045
def RunBatch(options): """Run one-off batch processing of WebpageTest testing.""" test_params = {'f': 'xml', 'private': 1, 'priority': 6, 'video': options.video, 'fvonly': options.fvonly, 'runs': options.runs, 'lo...
5,291,046
async def async_setup(hass, config): # pylint: disable=unused-argument """Set up this component.""" _LOGGER.info(STARTUP) config_dir = hass.config.path() github_token = config[DOMAIN]["token"] if config[DOMAIN]["appdaemon"]: ELEMENT_TYPES.append("appdaemon") if config[DOMAIN]["...
5,291,047
def convert_gym_space(spc): """Converts a :gym:`gym.Space <#spaces>` instance to a :class:`~texar.agents.Space` instance. Args: spc: An instance of `gym.Space` or :class:`~texar.agents.Space`. """ from texar.agents.agent_utils import Space if isinstance(spc, Space): ...
5,291,048
def save_inventory( session: SessionABC, inventory: List[InventoryType], merge_samples: bool = False ) -> List[InventoryType]: """Saves a list of inventory items to the server. :param session: the AqSession instance :param inventory: list of inventory items :param merge_samples: if True, will merge...
5,291,049
def positional_encoding(max_position, d_model): """Return the tensor encoding the position of elements in a sequence Compute the positional encoding with a combination of sinusoidal functions as suggested in (Vaswani at al., "Attention is all you need", 2017) Note: When we add the positional e...
5,291,050
def get_namespace(element): """Extract the namespace using a regular expression.""" match = re.match(r"\{.*\}", element.tag) return match.group(0) if match else ""
5,291,051
def load_test_data(): """Load sample targets and any missing test data.""" # Step 1 - Load Customer customer_id = load_customer() # Step 2 - Load Sending Profile sending_profile_id = load_sending_profile() # Step 3 - Get templates templates = get_templates() # Step 4 - Load Subscripti...
5,291,052
def get_model_name(filename): """ >>> get_model_name("logs/0613/0613-q1-0000.train") '0613-q1-0000' """ return os.path.splitext(os.path.basename(filename))[0]
5,291,053
def test_custom_models(): """ Test the custom models. """ # Valid model model_a = maniphono.PhonoModel("A", TEST_DIR / "test_models" / "a") assert len(model_a.features) == 5 # Invalid feature name with pytest.raises(ValueError): maniphono.PhonoModel("B", TEST_DIR / "test_models...
5,291,054
def delete(context: GametaContext, name: str) -> None: """ Deletes a Gameta constant from the constant store Args: context (GametaContext): Gameta Context name (str): Name of the constant to be deleted Returns: None Examples: $ gameta const delete -n test # Delete...
5,291,055
def create_LOFAR_configuration(antfile: str, meta: dict = None, params={}): """ Define from the LOFAR configuration file :param antfile: :type str: :param name: :type str: :param meta: :type dict: :param params: Dictionary containing parameters :return...
5,291,056
def toggle_date_format(session, context, poll): """Toggle the visibility of the percentage bar.""" poll.european_date_format = not poll.european_date_format poll.user.european_date_format = poll.european_date_format update_poll_messages(session, context.bot, poll) send_settings_message(context)
5,291,057
def get_fittest_solution(solutions): """Return the fittest of the passed solutions, using tie-breaking criteria if there are ties and only using random tie-breaking as a last resort""" # ensure that there are solutions if not solutions: return None # a single solution is the fittest if l...
5,291,058
def get_subs_v2(request: Request) -> HTTPResponse: """根据域名模糊匹配手动指定并获取订阅,在 Debug 部署模式下请求的订阅不会被删除。 如:要获取订阅 https://www.modu.me/link?token=123, 传入 modu 或 mod 或订阅实例所对应的 action-alias 既可匹配 alive action-alias 通过 pool_status() 获知, alias 格式为 Action[Something]Cloud,如 ActionModuCloud :param request: ...
5,291,059
def sphere_plane(map, mapi) -> plt.Figure: """ Plots map from (3d) sphere to (2d) plane and its inverse. :param map: Map from sphere to plane. :param mapi: Map from plane to sphere. :return: Figure. """ # Init plot object: fig = plt.figure() ax = np.array([[fig.add_subplot(2, 2, 1, ...
5,291,060
def init_linear_regression_probe(ref, mref, conf, mconf): """linear_regression_probe - quantitative tapping Compute binary tapping from continuous valued scan. """ mref.alpha = 1e-2 if 'alpha' in mconf: mref.alpha = mconf['alpha'] mref.meas = 'mse' if 'meas' in mconf: mref....
5,291,061
def hash_config(configuration: dict) -> str: """Computes a SHA256 hash from a dictionnary. Args: configuration (dict): The configuration to hash Returns: str: _description_ """ stringified = json.dumps(configuration, sort_keys=True) return hashlib.sha256(stringified.encode("utf...
5,291,062
def parse_pileup(instream, min_coverage, max_coverage): """ Given a stream of the output of samtools mpileup, count the number of reads at each position supporting the reference allele and the number supporting a non-reference allele. Arguments: - instream: input file stream containing samt...
5,291,063
def get_bag_of_communities(network, partition): """ :param network: dictionary containing for each key (each node/page) a dictionary containing the page categories. :param partition: list of the community assignment :return: list of dictionaries, one dictionary per community. Each dictionary contains th...
5,291,064
def connect( stream_generator, user=None, database=None, password=None, loop=None, **kwargs): """Creates a connection to a PostgreSQL database. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_; however, the arguments of the function are not defined by t...
5,291,065
def importMaterialsIntoModuleNamespace(path, name, namespace, updateSource=None): """ Import all Material subclasses into the top subpackage This allows devs to use ``from armi.materials import HT9`` Disadvantage: pylint can't tell if the module is available here. This can be used in plugins for s...
5,291,066
def add_neighbor_count_features(edge_df, X_df, structures_df): """ edge_df must be symmetric. """ cnt_df = edge_df.groupby( ['molecule_name', 'atom_index_0']).size().to_frame('EF_neighbor_count') cnt_df.reset_index(inplace=True) cnt_df.rename({'atom_index_0': 'atom_index_zero'}, inplace=...
5,291,067
def _to_pascal_case(value: str) -> str: """Converts a snake_case string into a PascalCase one.""" value = value.replace("-", "_") if value.find("_") == -1: return value[0].upper() + value[1:] return "".join([v.capitalize() for v in value.split("_")])
5,291,068
def load(modelSpecFilename): """ Need the following items in the model spec file: costFn decisionFn stages specs :param modelSpecFilename: :return: """ with open(modelSpecFilename) as f: modelDict = yaml.load(f) for stageDict in modelDict['specs']: ...
5,291,069
def _replace_prefixed(text: Any, prefix: Union[str, Set[str]], value: str) -> Any: """ Replace all substrings starting with the prefix(es) with the value. """ if pd.isna(text): return text text = str(text) if isinstance(prefix, set): for pre in prefix: text = re.sub(...
5,291,070
def perma(mat,m): """ Permanent of the matrix """ if not mat.isSquare: return None if mat.isIdentity: return 1 if mat.dim[0]==2: return m[0][0]*m[1][1] + m[1][0]*m[0][1] if mat.dim[0]==3: return (m[0][0]*m[1][1]*m[2][2] + m[0][1...
5,291,071
def _check_tar(tar: tarfile.TarFile) -> None: """Check the tarfile to avoid potential security issues. Currently collections and packages have the following constraints: - Only regular files or directories - No paths starting with '/' or containing '..' """ for info in tar.getmembers(): ...
5,291,072
def realtime_to_gametime(secs=0, mins=0, hrs=0, days=1, weeks=1, months=1, yrs=0, format=False): """ This method calculates how much in-game time a real-world time interval would correspond to. This is usually a lot less interesting than the other way around. Keyword Args: times (int): The ...
5,291,073
def char_class_abbrev(cc_abbrev: str, **config): """ Constructs a char_class spec :param cc_abbrev: alternative type abbreviation i.e. ascii, cc-ascii, visible, cc-visible :param config: in **kwargs format :return: the char_class spec """ spec = { "type": 'char_class_abbrev' } ...
5,291,074
def load_command_extension(command, path): """Loads a command extension from the path passed as argument. Args: command (str): name of the command (contains ``-``, not ``_``). path (str): base path of the command extension Returns: A valid module if found and loadable; None if not ...
5,291,075
def trial_division(n): """Return a list of the prime factors for a natural number.""" if n < 2: return [] prime_factors_list = [] temp = primeGenerate(int(n**0.5) + 1) for p in temp: if p*p > n: break while n % p == 0: prime_factors_list.append(p) ...
5,291,076
def occlusion(net: Module, input_image: Tensor, n_top_classes: int = 3) -> Tensor: """Creates a attribution heatmap by occluding parts of the input image. Args: net: the network to visualize attribution for input_image: image tensor of dimensions (c, h, w) or (1, c, h, w) n_top_classes:...
5,291,077
def pull_commits_info_for_diff(self, repo_owner: str, repo_name: str, pr_id: int, page_token: str = None, simple: bool = True): """ ... """ graphql_query: dict = { "operationName": "PullCommitsForDiffSelector", "variables": { "ownerName": repo_owner, "repoName": repo_nam...
5,291,078
def log_pos(x): """Computes log with the assumption that x values are positive. """ return jnp.log(jnp.maximum(x, jnp.finfo(float).eps))
5,291,079
def install_script(conf_dir: str, group: str): """ Function copies script and config files to needed directories :param conf_dir: Path to config directory to create :type: str :param group: Group name to set chown root:group to config directory :type: str :return: True or False :rtype: ...
5,291,080
def import_tree_to_json_str(imports=List[Import]) -> str: """ Print the imported modules tree in json format. """ exclude_root = imports[0]["nested_imports"] return json.dumps(exclude_root, indent=2)
5,291,081
def place_targets_with_goal_distance_ratio( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, object_placements: np.ndarray, goal_distance_ratio: float, goal_distance_min: float, max_placement_trial_count: int, max_p...
5,291,082
def logTx(txReceipt: TxReceipt) -> None: """Given a tx receipt, print to screen the transaction details and its cost""" txLogger.debug(txReceipt) ethSpent = Web3.fromWei( txReceipt["effectiveGasPrice"] * txReceipt["gasUsed"], "ether" ) txLogger.debug("Spent " + str(ethSpent) + " ETH")
5,291,083
def predict(model, test_batch_generator, num_batches, device, label_map, class_weight): """ Main evaluation routine """ epoch_loss = 0 epoch_acc = 0 epoch_results = {} epoch_results_by_tag = {} epoch_CR = "" output_t_pred = None model.eval() with torch.no_grad(): fo...
5,291,084
def getDocument(html, css=None): """ returns a DOM of html, if css is given it is appended to html/body as pre.cssutils """ document = etree.HTML(html) if css: # prepare document (add css for debugging) e = etree.Element('pre', {'class': 'cssutils'}) e.text = cs...
5,291,085
def using_cumisc(handle=None): """Temporarily set chainer's CUBLAS handle to scikit-cuda. The usage is similar to :func:`using_device`. Args: handle: CUBLAS handle. If ``None`` is specified, it uses CUBLAS handle for the current device. Returns: CumiscUser: Misc user objec...
5,291,086
def Unregister(cfg): """ Unregister a vm with the given path. Throws an exception or returns. """ vm = FindCfg(cfg) if vm == None: raise Vmodl.Fault.ManagedObjectNotFound() vm.Unregister()
5,291,087
def remove_list_duplicates(my_list: list) -> list: """ Removes any duplicated values from a list. """ return list(dict.fromkeys(my_list))
5,291,088
def sql_from_binary_tree(X: Union[list, np.ndarray], children_left: Union[list, np.ndarray], children_right: Union[list, np.ndarray], feature: Union[list, np.ndarray], threshold: Union[list, np.ndarray], ...
5,291,089
def add_student_calculations(cfg, dfs, debug): """Creates some calculated columns in the roster table""" df = dfs["roster"].copy() df["subgroup"] = df[["Race/ Eth", "Gender"]].apply(_get_subgroup, axis=1) df["local_strategy"] = df[["GPA", "local_sat_max"]].apply( _get_strategies, axis=1, ar...
5,291,090
def target_id_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for choosing a target ID. """ click_option_function: Callable[ [Callable[..., None]], Callable[..., None], ] = click.option( '--target-id', type=str, help='The I...
5,291,091
def tdnsresp(**kwargs) -> dns.Message: """ Returns: mitmproxy.dns.Message """ default = dict( timestamp=946681201, id=42, query=False, op_code=dns.op_codes.QUERY, authoritative_answer=False, truncation=False, recursion_desired=True, ...
5,291,092
def complete_command(cmd, line, start, end, ctx): """ Returns a list of valid commands starting with the first argument """ space = ' ' out = {s + space for s in builtins.__xonsh_commands_cache__ if get_filter_function()(s, cmd)} if ON_WINDOWS: out |= {i ...
5,291,093
def __fetch_query_from_uuid(uuid: str) -> bigquery.BigQueryResult: """ Fetches a cached BigQuery result from its UUID. Args: uuid (str): The UUID of the query to be retrieved. Returns: (BigQueryResult): The corresponding BigQuery result object. """ # Fetch cached qu...
5,291,094
def _get_keys(response): """ return lists of strings that are the keys from a client.list_objects() response """ keys = [] if 'Contents' in response: objects_list = response['Contents'] keys = [obj['Key'] for obj in objects_list] return keys
5,291,095
def add_run_parser(subparsers): """Include parser for 'run' subcommand""" parser = subparsers.add_parser("run", help="run a compiled module") parser.set_defaults(func=drive_run) # TODO --device needs to be extended and tested to support other targets, # like 'webgpu', etc (@leandron) pars...
5,291,096
def dump_score(filename, score_lines): """Dump scores that were loaded using :py:func:`load_score` The number of columns is automatically detected. """ if len(score_lines.dtype) == 5: fmt = "%s %s %s %s %.9f" elif len(score_lines.dtype) == 4: fmt = "%s %s %s %.9f" else: ...
5,291,097
def round_updown_to_x(num_in, x, direction="up"): """ Rounds a given value (num_in) to the nearest multiple of x, in a given direction (up or down) :param num_in: Input value :param x: Value to round to a multiple of :param direction: Round up or down. Default: 'up' :return: Rounded number ...
5,291,098
async def player_stop(): """ Full route: /music/player/resume Request (JSON): None Stop (unload) the current song. """ # no json expected was_playing = await player.player_stop() if was_playing: return with_status(None, 200, StatusType.OK) else: return with_status...
5,291,099