当前位置: 首页>>代码示例>>Python>>正文


Python typing.Tuple方法代码示例

本文整理汇总了Python中typing.Tuple方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Tuple方法的具体用法?Python typing.Tuple怎么用?Python typing.Tuple使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.Tuple方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: calculate_page_limit_and_offset

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def calculate_page_limit_and_offset(paginate: bool, page_size: int, page: int, result_length: int,
                                    offset: int, limit: int) -> Tuple[int, int]:
    """Calculate page limit and offset for pagination.
    :param paginate: Showing whether pagination is enable/disable.
    :param page_size: Number maximum elements showed in a page.
    :param page: page number.
    :param result_length: Length of the list containing desired elements.
    :param offset: offset value.
    :param limit: page limit.
    :return: page limit and offset.
    """
    if limit is not None:
        page_size = limit
    if paginate is True:
        if offset is None:
            offset = (page - 1) * page_size
        limit = page_size
    else:
        offset = 0
        limit = result_length

    return limit, offset 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:24,代码来源:crud_helpers.py

示例2: add_pagination_iri_mappings

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def add_pagination_iri_mappings(template: str,
                                template_mapping: List[IriTemplateMapping]
                                ) -> Tuple[str, List[IriTemplateMapping]]:
    """Add various pagination related to variable to the IRI template and also adds mappings for them.
    :param template: IriTemplate string.
    :param template_mapping: List of template mappings.
    :return: Final IriTemplate string and related list of mappings.
    """
    paginate_variables = ["pageIndex", "limit", "offset"]
    for i in range(len(paginate_variables)):
        # If final variable then do not add space and comma and add the final parentheses
        if i == len(paginate_variables) - 1:
            template += "{})".format(paginate_variables[i])
        else:
            template += "{}, ".format(paginate_variables[i])
        mapping = IriTemplateMapping(variable=paginate_variables[i], prop=paginate_variables[i])
        template_mapping.append(mapping)
    return template, template_mapping 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:20,代码来源:helpers.py

示例3: get_link_props_for_multiple_objects

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def get_link_props_for_multiple_objects(path: str,
                                        object_list: List[Dict[str, Any]]
                                        ) -> Tuple[List[Dict[str, Any]], bool]:
    """
    Get link_props of multiple objects.
    :param path: Path of the collection or non-collection class.
    :param object_list: List of objects being inserted.
    :return: List of link properties processed with the help of get_link_props.
    """
    link_prop_list = list()
    for object_ in object_list:
        link_props, type_check = get_link_props(path, object_)
        if type_check is True:
            link_prop_list.append(link_props)
        else:
            return [], False
    return link_prop_list, True 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:19,代码来源:helpers.py

示例4: filename_to_url

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def filename_to_url(filename: str, cache_dir: Union[str, Path] = None) -> Tuple[str, str]:
    """
    Return the url and etag (which may be ``None``) stored for `filename`.
    Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
    """
    if cache_dir is None:
        cache_dir = PYTORCH_PRETRAINED_BERT_CACHE
    if isinstance(cache_dir, Path):
        cache_dir = str(cache_dir)

    cache_path = os.path.join(cache_dir, filename)
    if not os.path.exists(cache_path):
        raise FileNotFoundError("file {} not found".format(cache_path))

    meta_path = cache_path + '.json'
    if not os.path.exists(meta_path):
        raise FileNotFoundError("file {} not found".format(meta_path))

    with open(meta_path) as meta_file:
        metadata = json.load(meta_file)
    url = metadata['url']
    etag = metadata['etag']

    return url, etag 
开发者ID:ymcui,项目名称:cmrc2019,代码行数:26,代码来源:file_utils.py

示例5: _empty_column_check

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def _empty_column_check(cards: dict) -> Tuple[bool, bool, bool, bool]:
    """检查是否周末和晚上有课,返回三个布尔值"""
    with tracer.trace('_empty_column_check'):
        # 空闲周末判断,考虑到大多数人周末都是没有课程的
        empty_sat = True
        for cls_time in range(1, 7):
            if (6, cls_time) in cards:
                empty_sat = False

        empty_sun = True
        for cls_time in range(1, 7):
            if (7, cls_time) in cards:
                empty_sun = False

        # 空闲课程判断,考虑到大多数人11-12节都是没有课程的
        empty_6 = True
        for cls_day in range(1, 8):
            if (cls_day, 6) in cards:
                empty_6 = False
        empty_5 = True
        for cls_day in range(1, 8):
            if (cls_day, 5) in cards:
                empty_5 = False
    return empty_5, empty_6, empty_sat, empty_sun 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:26,代码来源:views.py

示例6: get_semester_date

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def get_semester_date(date: datetime.date) -> Tuple[str, int, int]:
    """获取日期对应的学期、所属周次及星期(0表示周日,1表示周一...)

    >>> get_semester_date(datetime.date(2020, 2, 22))
    ('2019-2020-1', 26, 6)

    >>> get_semester_date(datetime.date(2020, 2, 23))
    ('2019-2020-2', 1, 0)
    """
    config = get_config()

    semesters = list(config.AVAILABLE_SEMESTERS.items())
    semesters.sort(key=lambda x: x[0], reverse=True)

    for sem in semesters:
        sem_start_date = datetime.date(*sem[1]["start"])
        if date >= sem_start_date:
            days_delta = (date - sem_start_date).days
            return "-".join([str(x) for x in sem[0]]), days_delta // 7 + 1, days_delta % 7
    raise ValueError("no applicable semester") 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:22,代码来源:domain.py

示例7: _precompute_exp_log

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def _precompute_exp_log() -> Tuple[List[int], List[int]]:
    exp = [0 for i in range(255)]
    log = [0 for i in range(256)]

    poly = 1
    for i in range(255):
        exp[i] = poly
        log[poly] = i

        # Multiply poly by the polynomial x + 1.
        poly = (poly << 1) ^ poly

        # Reduce poly by x^8 + x^4 + x^3 + x + 1.
        if poly & 0x100:
            poly ^= 0x11B

    return exp, log 
开发者ID:trezor,项目名称:python-shamir-mnemonic,代码行数:19,代码来源:shamir.py

示例8: apply

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def apply(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]:
        """
        Will run a terraform apply on a workspace & will pass all variables to the terraform apply as terraform
        variables

        Arguments:
            :param variables: the variables to pass to the terraform apply command
            :param parallelism: the number of parallel resource operations

        Returns:
            :return return_code: the return code of the terraform apply
            :return stdout: the stdout stream of the terraform apply
            :return stderr: the stderr stream of the terraform apply
        """
        if variables is None:
            variables = {}

        return_code, stdout, stderr = self.tf.apply(no_color=IsFlagged, var=variables, skip_plan=True,
                                                    parallelism=parallelism)
        return return_code, stdout, stderr 
开发者ID:naorlivne,项目名称:terraformize,代码行数:22,代码来源:terraformize_terraform_wrapper.py

示例9: destroy

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def destroy(self, variables: Optional[dict] = None, parallelism: int = 10) -> Tuple[str, str, str]:
        """

        Arguments:
            :param variables: the variables to pass to the terraform destroy command
            :param parallelism: the number of parallel resource operations

        Will run a terraform destroy on a workspace will pass all variables to the terraform destroy as terraform
        variables, not deleting the workspace as one might want to keep historical data or have multiple modules under
        the same workspace name

        Arguments:

        Returns:
            :return return_code: the return code of the terraform destroy
            :return stdout: the stdout stream of the terraform destroy
            :return stderr: the stderr stream of the terraform destroy
        """
        return_code, stdout, stderr = self.tf.destroy(no_color=IsFlagged, var=variables, auto_approve=True,
                                                      parallelism=parallelism)
        return return_code, stdout, stderr 
开发者ID:naorlivne,项目名称:terraformize,代码行数:23,代码来源:terraformize_terraform_wrapper.py

示例10: parse_arguments

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def parse_arguments() -> Tuple[argparse.Namespace, str]:
    """Parse command line arguments and return namespace

    :return: Namespace for arguments and help text as a tuple
    """
    parser = argparse.ArgumentParser(description='FireProx API Gateway Manager')
    parser.add_argument('--profile_name',
                        help='AWS Profile Name to store/retrieve credentials', type=str, default=None)
    parser.add_argument('--access_key',
                        help='AWS Access Key', type=str, default=None)
    parser.add_argument('--secret_access_key',
                        help='AWS Secret Access Key', type=str, default=None)
    parser.add_argument('--session_token',
                        help='AWS Session Token', type=str, default=None)
    parser.add_argument('--region',
                        help='AWS Region', type=str, default=None)
    parser.add_argument('--command',
                        help='Commands: list, create, delete, update', type=str, default=None)
    parser.add_argument('--api_id',
                        help='API ID', type=str, required=False)
    parser.add_argument('--url',
                        help='URL end-point', type=str, required=False)
    return parser.parse_args(), parser.format_help() 
开发者ID:ustayready,项目名称:fireprox,代码行数:25,代码来源:fire.py

示例11: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def __init__(self,
                 optimal_value: float,
                 optimal_parameters: numpy.ndarray,
                 num_evaluations: Optional[int]=None,
                 cost_spent: Optional[float]=None,
                 function_values: Optional[List[Tuple[
                     float, Optional[float], Optional[numpy.ndarray]
                     ]]]=None,
                 wait_times: Optional[List[float]]=None,
                 time: Optional[int]=None,
                 seed: Optional[int]=None,
                 status: Optional[int]=None,
                 message: Optional[str]=None) -> None:
        self.optimal_value = optimal_value
        self.optimal_parameters = optimal_parameters
        self.num_evaluations = num_evaluations
        self.cost_spent = cost_spent
        self.function_values = function_values
        self.wait_times = wait_times
        self.time = time
        self.seed = seed
        self.status = status
        self.message = message 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:25,代码来源:result.py

示例12: noise_bounds

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def noise_bounds(self,
                     cost: float,
                     confidence: Optional[float]=None
                     ) -> Tuple[float, float]:
        """Exact or approximate bounds on noise in the objective function.

        Returns a tuple (a, b) such that when `evaluate_with_cost` is called
        with the given cost and returns an approximate function value y, the
        true function value lies in the interval [y + a, y + b]. Thus, it should
        be the case that a <= 0 <= b.

        This function takes an optional `confidence` parameter which is a real
        number strictly between 0 and 1 that gives the confidence level in the
        bound. This is used for situations in which exact bounds on the noise
        cannot be guaranteed. The value can be interpreted as the probability
        that a repeated call to `evaluate_with_cost` with the same cost will
        return a value within the bounds.
        """
        return -numpy.inf, numpy.inf 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:21,代码来源:black_box.py

示例13: __init__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def __init__(self,
                 save_x_vals: bool=False,
                 **kwargs) -> None:
        """
        Args:
            save_x_vals: Whether to save all points (x values) that the
                black box was queried at. Setting this to True will cause the
                black box to consume a lot more memory. This does not affect
                whether the function values (y values) are saved (they are
                saved no matter what).
        """
        self.function_values = [] \
            # type: List[Tuple[float, Optional[float], Optional[numpy.ndarray]]]
        self.cost_spent = 0.0
        self.wait_times = []  # type: List[float]
        self._save_x_vals = save_x_vals
        self._time_of_last_query = None  # type: Optional[float]
        super().__init__(**kwargs) 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:20,代码来源:black_box.py

示例14: noise_bounds

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def noise_bounds(self,
                     cost: float,
                     confidence: Optional[float]=None
                     ) -> Tuple[float, float]:
        """Exact or approximate bounds on noise.

        Returns a tuple (a, b) such that when `noise` is called with the given
        cost, the returned value lies between a and b. It should be the case
        that a <= 0 <= b.

        This function takes an optional `confidence` parameter which is a real
        number strictly between 0 and 1 that gives the probability of the bounds
        being correct. This is used for situations in which exact bounds on the
        noise cannot be guaranteed.
        """
        return -numpy.inf, numpy.inf 
开发者ID:quantumlib,项目名称:OpenFermion-Cirq,代码行数:18,代码来源:objective.py

示例15: find_package

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Tuple [as 别名]
def find_package(name: str) -> Tuple[Optional[Path], Path]:
    """Finds packages install prefix (or None) and it's containing Folder
    """
    module = name.split(".")[0]
    loader = pkgutil.get_loader(module)
    if name == "__main__" or loader is None:
        package_path = Path.cwd()
    else:
        if hasattr(loader, "get_filename"):
            filename = loader.get_filename(module)  # type: ignore
        else:
            __import__(name)
            filename = sys.modules[name].__file__
        package_path = Path(filename).resolve().parent
        if hasattr(loader, "is_package"):
            is_package = loader.is_package(module)  # type: ignore
            if is_package:
                package_path = Path(package_path).resolve().parent
    sys_prefix = Path(sys.prefix).resolve()
    try:
        package_path.relative_to(sys_prefix)
    except ValueError:
        return None, package_path
    else:
        return sys_prefix, package_path 
开发者ID:pgjones,项目名称:quart,代码行数:27,代码来源:helpers.py


注:本文中的typing.Tuple方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。