LLamafactory用作Formatter的方法Qwen/lib/python3.12/abc.py

LLamafactory用作Formatter的方法Qwen/lib/python3.12/abc.py

Qwen/lib/python3.12/abc.py

class abstractstaticmethod(staticmethod):
    """A decorator indicating abstract staticmethods.

    Deprecated, use 'staticmethod' with 'abstractmethod' instead:

        class C(ABC):
            @staticmethod
            @abstractmethod
            def my_abstract_staticmethod(...):
                ...

    """

    __isabstractmethod__ = True

    def __init__(self, callable):
        callable.__isabstractmethod__ = True
        super().__init__(callable)


class abstractproperty(property):
    """A decorator indicating abstract properties.

    Deprecated, use 'property' with 'abstractmethod' instead:

        class C(ABC):
            @property
            @abstractmethod
            def my_abstract_property(self):
                ...

    """

    __isabstractmethod__ = True


try:
    from _abc import (get_cache_token, _abc_init, _abc_register,
                      _abc_instancecheck, _abc_subclasscheck, _get_dump,
                      _reset_registry, _reset_caches)
except ImportError:
    from _py_abc import ABCMeta, get_cache_token
    ABCMeta.__module__ = 'abc'
else:
    class ABCMeta(type):
        """Metaclass for defining Abstract Base Classes (ABCs).

        Use this metaclass to create an ABC.  An ABC can be subclassed
        directly, and then acts as a mix-in class.  You can also register
        unrelated concrete classes (even built-in classes) and unrelated
        ABCs as 'virtual subclasses' -- these and their descendants will
        be considered subclasses of the registering ABC by the built-in
        issubclass() function, but the registering ABC won't show up in
        their MRO (Method Resolution Order) nor will method
        implementations defined by the registering ABC be callable (not
        even via super()).
        """
        def __new__(mcls, name, bases, namespace, /, **kwargs):
            cls = super().__new__(mcls, name, bases, namespace, **kwargs)
            _abc_init(cls)
            return cls

        def register(cls, subclass):
            """Register a virtual subclass of an ABC.

            Returns the subclass, to allow usage as a class decorator.
            """
            return _abc_register(cls, subclass)

        def __instancecheck__(cls, instance):
            """Override for isinstance(instance, cls)."""
            return _abc_instancecheck(cls, instance)

        def __subclasscheck__(cls, subclass):
            """Override for issubclass(subclass, cls)."""
            return _abc_subclasscheck(cls, subclass)

        def _dump_registry(cls, file=None):
            """Debug helper to print the ABC registry."""
            print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
            print(f"Inv. counter: {get_cache_token()}", file=file)
            (_abc_registry, _abc_cache, _abc_negative_cache,
             _abc_negative_cache_version) = _get_dump(cls)
            print(f"_abc_registry: {_abc_registry!r}", file=file)
            print(f"_abc_cache: {_abc_cache!r}", file=file)
            print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file)
            print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}",
                  file=file)

        def _abc_registry_clear(cls):
            """Clear the registry (for debugging or testing)."""
            _reset_registry(cls)

        def _abc_caches_clear(cls):
            """Clear the caches (for debugging or testing)."""
            _reset_caches(cls)


def update_abstractmethods(cls):
    """Recalculate the set of abstract methods of an abstract class.

    If a class has had one of its abstract methods implemented after the
    class was created, the method will not be considered implemented until
    this function is called. Alternatively, if a new abstract method has been
    added to the class, it will only be considered an abstract method of the
    class after this function is called.

    This function should be called before any use is made of the class,
    usually in class decorators that add methods to the subject class.

    Returns cls, to allow usage as a class decorator.

    If cls is not an instance of ABCMeta, does nothing.
    """
    if not hasattr(cls, '__abstractmethods__'):
        # We check for __abstractmethods__ here because cls might by a C
        # implementation or a python implementation (especially during
        # testing), and we want to handle both cases.
        return cls

    abstracts = set()
    # Check the existing abstract methods of the parents, keep only the ones
    # that are not implemented.
    for scls in cls.__bases__:
        for name in getattr(scls, '__abstractmethods__', ()):
            value = getattr(cls, name, None)
            if getattr(value, "__isabstractmethod__", False):
                abstracts.add(name)
    # Also add any other newly added abstract methods.
    for name, value in cls.__dict__.items():
        if getattr(value, "__isabstractmethod__", False):
            abstracts.add(name)
    cls.__abstractmethods__ = frozenset(abstracts)
    return cls


class ABC(metaclass=ABCMeta):
    """Helper class that provides a standard way to create an ABC using
    inheritance.
    """
    __slots__ = ()

abc.py 是 Python 的标准库模块之一,用于定义抽象基类(Abstract Base Classes,简称 ABCs)。抽象基类提供了一种机制,可以定义接口并强制子类实现这些接口。下面是代码的逐行解释:

abstractstaticmethod

python

复制

class abstractstaticmethod(staticmethod):
    """A decorator indicating abstract staticmethods.

    Deprecated, use 'staticmethod' with 'abstractmethod' instead:

        class C(ABC):
            @staticmethod
            @abstractmethod
            def my_abstract_staticmethod(...):
                ...

    """
  • 这是一个装饰器类,用于指示抽象静态方法。
  • 已废弃,建议使用 staticmethodabstractmethod 组合代替。

python

复制

    __isabstractmethod__ = True
  • 设置一个类属性,表明这是一个抽象方法。

python

复制

    def __init__(self, callable):
        callable.__isabstractmethod__ = True
        super().__init__(callable)
  • 初始化方法,接受一个可调用对象,并将其标记为抽象方法。

abstractproperty

python

复制

class abstractproperty(property):
    """A decorator indicating abstract properties.

    Deprecated, use 'property' with 'abstractmethod' instead:

        class C(ABC):
            @property
            @abstractmethod
            def my_abstract_property(self):
                ...

    """
  • 这是一个装饰器类,用于指示抽象属性。
  • 已废弃,建议使用 propertyabstractmethod 组合代替。

python

复制

    __isabstractmethod__ = True
  • 设置一个类属性,表明这是一个抽象方法。

导入 _abc 模块

python

复制

try:
    from _abc import (get_cache_token, _abc_init, _abc_register,
                      _abc_instancecheck, _abc_subclasscheck, _get_dump,
                      _reset_registry, _reset_caches)
except ImportError:
    from _py_abc import ABCMeta, get_cache_token
    ABCMeta.__module__ = 'abc'
  • 尝试导入 _abc 模块中的各种方法。
  • 如果导入失败,回退到 _py_abc 模块,并导入 ABCMetaget_cache_token

ABCMeta

python

复制

else:
    class ABCMeta(type):
        """Metaclass for defining Abstract Base Classes (ABCs).

        Use this metaclass to create an ABC.  An ABC can be subclassed
        directly, and then acts as a mix-in class.  You can also register
        unrelated concrete classes (even built-in classes) and unrelated
        ABCs as 'virtual subclasses' -- these and their descendants will
        be considered subclasses of the registering ABC by the built-in
        issubclass() function, but the registering ABC won't show up in
        their MRO (Method Resolution Order) nor will method
        implementations defined by the registering ABC be callable (not
        even via super()).
        """
  • ABCMeta 是一个元类,用于定义抽象基类。
  • 使用这个元类可以创建一个 ABC,可以直接子类化或作为混入类使用。

python

复制

        def __new__(mcls, name, bases, namespace, /, **kwargs):
            cls = super().__new__(mcls, name, bases, namespace, **kwargs)
            _abc_init(cls)
            return cls
  • __new__ 方法用于创建类对象,并初始化 ABC 相关属性。

python

复制

        def register(cls, subclass):
            """Register a virtual subclass of an ABC.

            Returns the subclass, to allow usage as a class decorator.
            """
            return _abc_register(cls, subclass)
  • register 方法用于注册虚拟子类。

python

复制

        def __instancecheck__(cls, instance):
            """Override for isinstance(instance, cls)."""
            return _abc_instancecheck(cls, instance)
  • __instancecheck__ 方法用于重载 isinstance 检查。

python

复制

        def __subclasscheck__(cls, subclass):
            """Override for issubclass(subclass, cls)."""
            return _abc_subclasscheck(cls, subclass)
  • __subclasscheck__ 方法用于重载 issubclass 检查。

python

复制

        def _dump_registry(cls, file=None):
            """Debug helper to print the ABC registry."""
            print(f"Class: {cls.__module__}.{cls.__qualname__}", file=file)
            print(f"Inv. counter: {get_cache_token()}", file=file)
            (_abc_registry, _abc_cache, _abc_negative_cache,
             _abc_negative_cache_version) = _get_dump(cls)
            print(f"_abc_registry: {_abc_registry!r}", file=file)
            print(f"_abc_cache: {_abc_cache!r}", file=file)
            print(f"_abc_negative_cache: {_abc_negative_cache!r}", file=file)
            print(f"_abc_negative_cache_version: {_abc_negative_cache_version!r}",
                  file=file)
  • _dump_registry 方法用于打印 ABC 注册表,帮助调试。

python

复制

        def _abc_registry_clear(cls):
            """Clear the registry (for debugging or testing)."""
            _reset_registry(cls)
  • _abc_registry_clear 方法用于清除注册表。

python

复制

        def _abc_caches_clear(cls):
            """Clear the caches (for debugging or testing)."""
            _reset_caches(cls)
  • _abc_caches_clear 方法用于清除缓存。

update_abstractmethods 方法

python

复制

def update_abstractmethods(cls):
    """Recalculate the set of abstract methods of an abstract class.

    If a class has had one of its abstract methods implemented after the
    class was created, the method will not be considered implemented until
    this function is called. Alternatively, if a new abstract method has been
    added to the class, it will only be considered an abstract method of the
    class after this function is called.

    This function should be called before any use is made of the class,
    usually in class decorators that add methods to the subject class.

    Returns cls, to allow usage as a class decorator.

    If cls is not an instance of ABCMeta, does nothing.
    """
  • update_abstractmethods 函数用于重新计算抽象类的抽象方法集合。

python

复制

    if not hasattr(cls, '__abstractmethods__'):
        # We check for __abstractmethods__ here because cls might by a C
        # implementation or a python implementation (especially during
        # testing), and we want to handle both cases.
        return cls
  • 检查类是否具有 __abstractmethods__ 属性,如果没有,则返回类本身。

python

复制

    abstracts = set()
    # Check the existing abstract methods of the parents, keep only the ones
    # that are not implemented.
    for scls in cls.__bases__:
        for name in getattr(scls, '__abstractmethods__', ()):
            value = getattr(cls, name, None)
            if getattr(value, "__isabstractmethod__", False):
                abstracts.add(name)
    # Also add any other newly added abstract methods.
    for name, value in cls.__dict__.items():
        if getattr(value, "__isabstractmethod__", False):
            abstracts.add(name)
    cls.__abstractmethods__ = frozenset(abstracts)
    return cls
  • 检查父类的抽象方法,将未实现的方法保留在集合中。
  • 检查当前类的新抽象方法,并将其添加到集合中。
  • 更新类的 __abstractmethods__ 属性并返回类。

ABC

python

复制

class ABC(metaclass=ABCMeta):
    """Helper class that provides a standard way to create an ABC using
    inheritance.
    """
    __slots__ = ()
  • ABC 类是一个帮助类,提供了一种标准方式来创建 ABC。
  • 使用 ABCMeta 作为元类。
  • __slots__ 属性为空,表示该类不允许动态添加属性。

ABC 类(续)

python

复制

class ABC(metaclass=ABCMeta):
    """Helper class that provides a standard way to create an ABC using
    inheritance.
    """
    __slots__ = ()
  • ABC 类是一个帮助类,提供了一种标准方式来创建抽象基类。
  • 使用 ABCMeta 作为元类。
  • __slots__ 属性为空,表示该类不允许动态添加属性。

总结

这个 abc.py 模块主要用于定义和管理抽象基类(ABCs)和抽象方法。以下是各部分的功能总结:

abstractstaticmethodabstractproperty

  • 这两个类是装饰器,用于标记静态方法和属性为抽象的。这些装饰器已经被废弃,建议改用 staticmethodabstractmethod 的组合。

ABCMeta 元类

  • 这个元类用于定义抽象基类。使用这个元类创建的类可以包含抽象方法,强制子类实现这些方法。
  • 包含一些用于管理和调试的方法,如 register__instancecheck____subclasscheck___dump_registry_abc_registry_clear_abc_caches_clear

update_abstractmethods 函数

  • 这个函数用于重新计算抽象类的抽象方法集合。如果类在创建后实现了一个抽象方法,或者添加了新的抽象方法,需要调用这个函数来更新抽象方法集合。

ABC

  • 这是一个帮助类,用于创建抽象基类。使用 ABCMeta 作为其元类,并且通过 __slots__ 属性限制动态属性的添加。

通过这些工具,abc.py 模块提供了一种标准化的方式来定义和管理抽象基类及其方法,从而增强了代码的结构性和可维护性。

Read more

使用 Prometheus 和 Grafana 监控 Spring Boot 应用程序

使用 Prometheus 和 Grafana 监控 Spring Boot 应用程序

手把手教你如何使用 Prometheus 和  监控 Spring Boot 应用程序的过程。 在本文中,我们将研究如何使用 Grafana 监控 Spring Boot 应用程序。我们将研究整个设置并创建一个简单的仪表板来查看一些指标。 部署在生产环境中的每个应用程序都需要某种监控来了解应用程序的执行情况。这将使您了解应用程序是否按方面执行,或者您是否需要采取一些措施以获得所需的性能水平。在现代世界中,这些数据称为应用程序性能指标 (APM)。现在已经有相当多的商业工具如Newrelic、Datadog APM等,都是提供这种能力的SAAS服务。 今天我们将研究两个开源工具,称为Grafana和Prometheus。Prometheus 以时间序列格式收集和存储指标数据,而 Grafana 使用 Prometheus 作为数据源在仪表板上可视化数据。 有了这个,让我们首先创建一个应用程序并使用 Grafana 对其进行监控。 创建一个 Spring Boot 应用程序 让我们访问https://start.spring.io并创建一个具有以下依赖项的简单应用程序。

By Ne0inhk
2022 年值得了解的基础设施即代码工具清单

2022 年值得了解的基础设施即代码工具清单

云计算的出现彻底改变了每个 IT 领域。不排除 IT 基础设施。管理员不得不手动配置资源并管理大型 Excel 表格中的数据的日子已经一去不复返了。在当今动态变化的网络需求下,人工维护 IT 基础设施的想法非常可怕。这就是基础设施即代码工具的用武之地。 简单地说,IaC 是关于使用代码的基础设施自动化。在 IaC 环境中,管理员编写和部署机器可读的配置文件,用于自动配置 IT 基础架构并将基础架构始终保持在所需状态。使用 IaC 配置文件,您可以自动部署网络、虚拟机、服务器、数据库等。 主要分享低代码、微服务、容器化、SAAS‬、系统架构方面的的‬内容‬‬,希望‬大家‬点赞‬,评论,关注‬。 对基础设施即代码工具的需求 最初,IT 管理员手动放置服务器,并在这些服务器上配置和部署应用程序。配置详细信息由网络团队手动存储和管理。这个过程是重复的和耗时的。此外,

By Ne0inhk
Spring经典的面试题,你值得拥有!!

Spring经典的面试题,你值得拥有!!

一、什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合、广泛的基础性支持的Java平台。Spring帮助开发者解决了开发中基础性的问题,使得开发人员可以专注于应用程序的开发。 Spring框架本身亦是按照设计模式精心打造,这使得我们可以在开发环境中安心的集成Spring框架,不必担心Spring是如何在后台进行工作的。 Spring框架至今已集成了20多个模块。这些模块主要被分如下图所示的核心容器、数据访问/集成,、Web、AOP(面向切面编程)、工具、消息和测试模块。 二、使用Spring框架能带来哪些好处? 下面列举了一些使用Spring框架带来的主要好处: 1、Dependency Injection(DI) 方法使得构造器和JavaBean properties文件中的依赖关系一目了然。 2、与EJB容器相比较,IoC容器更加趋向于轻量级。这样一来IoC容器在有限的内存和CPU资源的情况下进行应用程序的开发和发布就变得十分有利。 3、Spring并没有闭门造车,Spring利用了已有的技术比如ORM

By Ne0inhk
金三银四面试季,程序员常见的14个Java面试题,必须得收藏!!!

金三银四面试季,程序员常见的14个Java面试题,必须得收藏!!!

跳槽不算频繁,但参加过不少面试(电话面试、face to face面试),面过大/小公司、互联网/传统软件公司,面糊过(眼高手低,缺乏实战经验,挂掉),也面过人,所幸未因失败而气馁,在此过程中不断查缺补漏,养成了踏实、追本溯源、持续改进的习惯,特此将自己经历过、构思过的一些面试题记录下来,如果答案有问题,欢迎拍砖讨论,希望能对找工作或者感兴趣的同学有所帮助,陆续整理中。 1. synchronized和reentrantlock异同 相同点 都实现了多线程同步和内存可见性语义 都是可重入锁 不同点 实现机制不同 synchronized通过java对象头锁标记和Monitor对象实现 reentrantlock通过CAS、ASQ(AbstractQueuedSynchronizer)和locksupport(用于阻塞和解除阻塞)实现 synchronized依赖jvm内存模型保证包含共享变量的多线程内存可见性 reentrantlock通过ASQ的volatile state保证包含共享变量的多线程内存可见性 使用方式不同 synchronized可以修饰实例方法(锁住实例对象

By Ne0inhk