Adds a `__nonzero__()` method to classes that define a `__bool__()` method,
    so boolean conversion works in Python 2. Has no effect in Python 3.

    :param klass: The class to modify. Must define `__bool__()`.
    :return: The possibly patched class.
485748
def python_2_nonzero_compatible(klass):
    
    if six.PY2:
        if '__bool__' not in klass.__dict__:
            raise ValueError(
                '@python_2_nonzero_compatible cannot be applied to {0} because '
                'it doesn\'t define __bool__().'.format(klass.__name__))
        klass.__nonzero__ = klass.__bool__
    return klass
1321506
def get_class_meta(klass):
    
    if not isinstance(klass, python.class_types) or klass is object:
        raise TypeError('klass must be a class object, got %r' % type(klass))

    meta = {
        'static_attrs': None,
        'exclude_attrs': None,
        'readonly_attrs': None,
        'proxy_attrs': None,
        'amf3': None,
        'dynamic': None,
        'alias': None,
        'external': None,
        'synonym_attrs': None
    }

    if not hasattr(klass, '__amf__'):
        return meta

    a = klass.__amf__

    if type(a) is dict:
        in_func = lambda x: x in a
        get_func = a.__getitem__
    else:
        in_func = lambda x: hasattr(a, x)
        get_func = lambda x: getattr(a, x)

    for prop in ['alias', 'amf3', 'dynamic', 'external']:
        if in_func(prop):
            meta[prop] = get_func(prop)

    for prop in ['static', 'exclude', 'readonly', 'proxy', 'synonym']:
        if in_func(prop):
            meta[prop + '_attrs'] = get_func(prop)

    return meta
331187
def superclass(self, klass):
        """"""
        return bool(lib.EnvSuperclassP(self._env, self._cls, klass._cls))
561186
def add_methods(source_class, blacklist=()):
    

    def wrap(wrapped_fx):
        """Wrap a GAPIC method; preserve its name and docstring."""
        # If this is a static or class method, then we need to *not*
        # send self as the first argument.
        #
        # Similarly, for instance methods, we need to send self.api rather
        # than self, since that is where the actual methods were declared.
        instance_method = True

        # If this is a bound method it's a classmethod.
        self = getattr(wrapped_fx, "__self__", None)
        if issubclass(type(self), type):
            instance_method = False

        # Okay, we have figured out what kind of method this is; send
        # down the correct wrapper function.
        if instance_method:
            fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw)  # noqa
            return functools.wraps(wrapped_fx)(fx)

        fx = lambda *a, **kw: wrapped_fx(*a, **kw)  # noqa
        return staticmethod(functools.wraps(wrapped_fx)(fx))

    def actual_decorator(cls):
        # Reflectively iterate over most of the methods on the source class
        # (the GAPIC) and make wrapped versions available on this client.
        for name in dir(source_class):
            # Ignore all private and magic methods.
            if name.startswith("_"):
                continue

            # Ignore anything on our blacklist.
            if name in blacklist:
                continue

            # Retrieve the attribute, and ignore it if it is not callable.
            attr = getattr(source_class, name)
            if not callable(attr):
                continue

            # Add a wrapper method to this object.
            fx = wrap(getattr(source_class, name))
            setattr(cls, name, fx)

        # Return the augmented class.
        return cls

    # Simply return the actual decorator; this is returned from this method
    # and actually used to decorate the class.
    return actual_decorator
305592
def import_class(name):
    

    module, _, klass = name.rpartition('.')
    mod = import_module(module)
    return getattr(mod, klass)
1257195
def add_metaclass(metaclass):
    """"""
    def wrapper(cls):
        orig_vars = cls.__dict__.copy()
        orig_vars.pop('__dict__', None)
        orig_vars.pop('__weakref__', None)
        return metaclass(cls.__name__, cls.__bases__, orig_vars)
    return wrapper
866804
def boolean(description, **kwargs) -> typing.Type:
    
    kwargs['description'] = description
    return type('Boolean', (Boolean,), kwargs)
171916
def Bool(value: "__builtins__.bool", annotations: Annotations = None) -> bool.Bool:
        
        raw = z3.BoolVal(value)
        return Bool(raw, annotations)
1141359
def is_strict_subclass (value, klass):
    
    return (isinstance (value, type) and
            issubclass (value, klass) and
            value is not klass)
39752
def python_2_div_compatible(klass):
    
    if six.PY2:
        if '__floordiv__' not in klass.__dict__:
            raise ValueError(
                '@python_2_div_compatible cannot be applied to {0} because it '
                'doesn\'t define __floordiv__().'.format(klass.__name__))
        klass.__div__ = klass.__floordiv__
    return klass
185376
def add_method(self, pattern):
        """"""
        def wrap(f):
            def frozen_function(class_instance, f):
                def _(pattern, *args, **kwargs):
                    return f(class_instance, pattern, *args, **kwargs)

                return _

            self.functions.append((frozen_function(self, f), pattern))
            return f

        return wrap
568560
def module_methods_in(klass)
      klass.included_modules.each_with_object([]) do |mod, accumulator|
        if mod.to_s =~ /#{klass}/
          mod.instance_methods(false).each do |method|
            accumulator << method
          end
        end
        accumulator
      end
    end
1054749
def is_direct_subclass(class_, of):
    
    ensure_class(class_)
    ensure_class(of)  # TODO(xion): support predicates in addition to classes

    return of in class_.__bases__
918873
def restore_original_new_method(klass)
      klass.define_singleton_method :new do |*args, &block|
        Throttling.original_new_method(klass).bind(klass).call *args, &block
      end
    end
986774
def method_missing(*args)
      method = args[0].to_s
      case args.length
        when 2
          k, v = method.delete('=').to_sym, args[1]
          add_attribute k, v
      end
    end
1283535
def _add_numeric_methods_binary(cls):
        

        def _make_evaluate_binop(op, step=False):
            """
            Parameters
            ----------
            op : callable that accepts 2 parms
                perform the binary op
            step : callable, optional, default to False
                op to apply to the step parm if not None
                if False, use the existing step
            """

            def _evaluate_numeric_binop(self, other):
                if isinstance(other, (ABCSeries, ABCDataFrame)):
                    return NotImplemented
                elif isinstance(other, ABCTimedeltaIndex):
                    # Defer to TimedeltaIndex implementation
                    return NotImplemented
                elif isinstance(other, (timedelta, np.timedelta64)):
                    # GH#19333 is_integer evaluated True on timedelta64,
                    # so we need to catch these explicitly
                    return op(self._int64index, other)
                elif is_timedelta64_dtype(other):
                    # Must be an np.ndarray; GH#22390
                    return op(self._int64index, other)

                other = self._validate_for_numeric_binop(other, op)
                attrs = self._get_attributes_dict()
                attrs = self._maybe_update_attributes(attrs)

                left, right = self, other

                try:
                    # apply if we have an override
                    if step:
                        with np.errstate(all='ignore'):
                            rstep = step(left._step, right)

                        # we don't have a representable op
                        # so return a base index
                        if not is_integer(rstep) or not rstep:
                            raise ValueError

                    else:
                        rstep = left._step

                    with np.errstate(all='ignore'):
                        rstart = op(left._start, right)
                        rstop = op(left._stop, right)

                    result = RangeIndex(rstart,
                                        rstop,
                                        rstep,
                                        **attrs)

                    # for compat with numpy / Int64Index
                    # even if we can represent as a RangeIndex, return
                    # as a Float64Index if we have float-like descriptors
                    if not all(is_integer(x) for x in
                               [rstart, rstop, rstep]):
                        result = result.astype('float64')

                    return result

                except (ValueError, TypeError, ZeroDivisionError):
                    # Defer to Int64Index implementation
                    return op(self._int64index, other)
                    # TODO: Do attrs get handled reliably?

            name = '__{name}__'.format(name=op.__name__)
            return compat.set_function_name(_evaluate_numeric_binop, name, cls)

        cls.__add__ = _make_evaluate_binop(operator.add)
        cls.__radd__ = _make_evaluate_binop(ops.radd)
        cls.__sub__ = _make_evaluate_binop(operator.sub)
        cls.__rsub__ = _make_evaluate_binop(ops.rsub)
        cls.__mul__ = _make_evaluate_binop(operator.mul, step=operator.mul)
        cls.__rmul__ = _make_evaluate_binop(ops.rmul, step=ops.rmul)
        cls.__truediv__ = _make_evaluate_binop(operator.truediv,
                                               step=operator.truediv)
        cls.__rtruediv__ = _make_evaluate_binop(ops.rtruediv,
                                                step=ops.rtruediv)
1271837
def get_object_or_none(klass, *args, **kwargs):
    
    queryset = _get_queryset(klass)
    try:
        return queryset.get(*args, **kwargs)
    except:  # noqa: E722
        return None