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


Python inflection.underscore方法代码示例

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


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

示例1: main

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def main():
    args = make_args()
    config = configparser.ConfigParser()
    utils.load_config(config, args.config)
    for cmd in args.modify:
        utils.modify_config(config, cmd)
    with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
        logging.config.dictConfig(yaml.load(f))
    model_dir = utils.get_model_dir(config)
    path, step, epoch = utils.train.load_model(model_dir)
    state_dict = torch.load(path, map_location=lambda storage, loc: storage)
    mapper = [(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', __file__).load_module()) if inspect.isclass(member)]
    path = os.path.join(model_dir, os.path.basename(os.path.splitext(__file__)[0])) + '.xlsx'
    with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
        worksheet = workbook.add_worksheet(args.worksheet)
        for j, (key, m) in enumerate(mapper):
            worksheet.write(0, j, key)
            for i, (name, variable) in enumerate(state_dict.items()):
                value = m(name, variable)
                worksheet.write(1 + i, j, value)
            if hasattr(m, 'format'):
                m.format(workbook, worksheet, i, j)
        worksheet.autofilter(0, 0, i, len(mapper) - 1)
        worksheet.freeze_panes(1, 0)
    logging.info(path) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:27,代码来源:variable_stat.py

示例2: format_field_names

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def format_field_names(obj, format_type=None):
    """
    Takes a dict and returns it with formatted keys as set in `format_type`
    or `JSON_API_FORMAT_FIELD_NAMES`

    :format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
    """
    if format_type is None:
        format_type = json_api_settings.FORMAT_FIELD_NAMES

    if isinstance(obj, dict):
        formatted = OrderedDict()
        for key, value in obj.items():
            key = format_value(key, format_type)
            formatted[key] = value
        return formatted

    return obj 
开发者ID:django-json-api,项目名称:django-rest-framework-json-api,代码行数:20,代码来源:utils.py

示例3: create_template_entities

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def create_template_entities(self, namespace, entities):
        """Creates entities from openshift template.

        Since there is no methods in openshift/kubernetes rest api for app deployment from template,
        it is necessary to create template entities one by one using respective entity api.

        Args:
            namespace: (str) openshift namespace
            entities: (list) openshift entities

        Returns: None
        """
        self.logger.debug("passed template entities:\n %r", entities)
        kinds = set([e['kind'] for e in entities])
        entity_names = {e: inflection.underscore(e) for e in kinds}
        proc_names = {k: 'create_{e}'.format(e=p) for k, p in entity_names.items()}

        for entity in entities:
            if entity['kind'] in kinds:
                procedure = getattr(self, proc_names[entity['kind']], None)
                obtained_entity = procedure(namespace=namespace, **entity)
                self.logger.debug(obtained_entity)
            else:
                self.logger.error("some entity %s isn't present in entity creation list", entity) 
开发者ID:RedHatQE,项目名称:wrapanapi,代码行数:26,代码来源:rhopenshift.py

示例4: get_context

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def get_context(version, name, model, plural_name):
    name = inflection.underscore(inflection.singularize(name))
    model = model or name
    model_class_name = inflection.camelize(model)
    class_name = inflection.camelize(name)
    serializer_class_name = class_name + 'Serializer'
    viewset_class_name = class_name + 'ViewSet'
    plural_name = plural_name or inflection.pluralize(name)
    return {
        'version': version,
        'serializer_class_name': serializer_class_name,
        'viewset_class_name': viewset_class_name,
        'model_class_name': model_class_name,
        'name': name,
        'plural_name': plural_name
    } 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:18,代码来源:context.py

示例5: camel_case_translate

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def camel_case_translate(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        normalised_kwargs = {}
        for arg, value in kwargs.items():
            arg = _normalise_arg(arg)

            if not arg.isupper():
                snake_case_arg = inflection.underscore(arg)
                if snake_case_arg != arg:
                    if snake_case_arg in kwargs:
                        raise ValueError('{} and {} both specified'.format(arg, snake_case_arg))

                    normalised_kwargs[snake_case_arg] = value
                else:
                    normalised_kwargs[arg] = value
            else:
                normalised_kwargs[arg] = value

        return f(*args, **normalised_kwargs)

    return wrapper 
开发者ID:goldmansachs,项目名称:gs-quant,代码行数:24,代码来源:base.py

示例6: _get_installed_software

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def _get_installed_software(self, subkey_path):
        try:
            uninstall_sk = self.registry_hive.get_key(subkey_path)
        except RegistryKeyNotFoundException as ex:
            logger.error(ex)
            return

        for installed_program in uninstall_sk.iter_subkeys():
            values = {underscore(x.name): x.value for x in
                      installed_program.iter_values(as_json=self.as_json)} if installed_program.values_count else {}
            self.entries.append({
                'service_name': installed_program.name,
                'timestamp': convert_wintime(installed_program.header.last_modified, as_json=self.as_json),
                'registry_path': subkey_path,
                **values

            }) 
开发者ID:mkorman90,项目名称:regipy,代码行数:19,代码来源:installed_programs_ntuser.py

示例7: _normalize_parameters

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = underscore(key).lower()

            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected)
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
开发者ID:scottwernervt,项目名称:cloudstorage,代码行数:20,代码来源:microsoft.py

示例8: _normalize_parameters

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def _normalize_parameters(
        params: Dict[str, str], normalizers: Dict[str, str]
    ) -> Dict[str, str]:
        normalized = params.copy()

        for key, value in params.items():
            normalized.pop(key)
            if not value:
                continue

            key_inflected = camelize(underscore(key), uppercase_first_letter=True)
            # Only include parameters found in normalizers
            key_overrider = normalizers.get(key_inflected.lower())
            if key_overrider:
                normalized[key_overrider] = value

        return normalized 
开发者ID:scottwernervt,项目名称:cloudstorage,代码行数:19,代码来源:minio.py

示例9: get_mod

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def get_mod(mod_name):
    """Imports a mod from its name using `importlib`.

    Args:
        mod_name: The name of the mod (snake_case of CamelCase are accepted).

    Returns:
        The python class which corresponds to the modification.

    Raises:
        ImportError: The class was not found or it is not a subclass of `Mod`.

    Examples:
        >>> get_mod("DropOne")
        <class 'fragscapy.modifications.drop_one.DropOne'>
        >>> get_mod("drop_one")
        <class 'fragscapy.modifications.drop_one.DropOne'>
    """
    pkg_name = "{}.{}".format(MOD_PACKAGE, inflection.underscore(mod_name))
    mod_name = inflection.camelize(mod_name)

    pkg = importlib.import_module(pkg_name)
    try:
        mod = getattr(pkg, mod_name)
    except AttributeError:  # There is no class named correctly
        raise ImportError(
            "No class named {} in module {}"
            .format(mod_name, pkg_name)
        )

    if not issubclass(mod, Mod):
        raise ImportError(
            "{}.{} is not a subclass of `fragscapy.modifications.mod.Mod`"
            .format(pkg_name, mod_name)
        )

    return mod 
开发者ID:AMOSSYS,项目名称:Fragscapy,代码行数:39,代码来源:modgenerator.py

示例10: __init__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def __init__(self):
        name = inflection.underscore(type(self).__name__)
        self.fn = eval(name) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:5,代码来源:image.py

示例11: __init__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def __init__(self):
        self.fn = eval(inflection.underscore(type(self).__name__)) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:4,代码来源:label.py

示例12: __init__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def __init__(self, config):
        self.config = config
        self.fn = eval(inflection.underscore(type(self).__name__)) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:5,代码来源:augmentation.py

示例13: __init__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def __init__(self, config):
        name = inflection.underscore(type(self).__name__)
        self.adjust = tuple(map(int, config.get('augmentation', name).split())) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:5,代码来源:image.py

示例14: __init__

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def __init__(self, args, config):
        self.args = args
        self.config = config
        self.model_dir = utils.get_model_dir(config)
        self.cache_dir = utils.get_cache_dir(config)
        self.category = utils.get_category(config, self.cache_dir)
        self.draw_bbox = utils.visualize.DrawBBox(self.category)
        self.loader = self.get_loader()
        self.anchors = torch.from_numpy(utils.get_anchors(config)).contiguous()
        self.path, self.step, self.epoch = utils.train.load_model(self.model_dir)
        state_dict = torch.load(self.path, map_location=lambda storage, loc: storage)
        dnn = utils.parse_attr(config.get('model', 'dnn'))(model.ConfigChannels(config, state_dict), self.anchors, len(self.category))
        dnn.load_state_dict(state_dict)
        logging.info(humanize.naturalsize(sum(var.cpu().numpy().nbytes for var in dnn.state_dict().values())))
        self.inference = model.Inference(config, dnn, self.anchors)
        self.inference.eval()
        if torch.cuda.is_available():
            self.inference.cuda()
        path = self.model_dir + '.ini'
        if os.path.exists(path):
            self._config = configparser.ConfigParser()
            self._config.read(path)
        else:
            logging.warning('training config (%s) not found' % path)
        self.now = datetime.datetime.now()
        self.mapper = dict([(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', self.config.get('eval', 'mapper')).load_module()) if inspect.isclass(member)]) 
开发者ID:ruiminshen,项目名称:yolo2-pytorch,代码行数:28,代码来源:eval.py

示例15: inflect_column_name

# 需要导入模块: import inflection [as 别名]
# 或者: from inflection import underscore [as 别名]
def inflect_column_name(name):
    name = re.sub(r"([A-Z]+)_([A-Z][a-z])", r'\1__\2', name)
    name = re.sub(r"([a-z\d])_([A-Z])", r'\1__\2', name)
    return inflection.underscore(name) 
开发者ID:statsbotco,项目名称:target-postgres,代码行数:6,代码来源:db_sync.py


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