Save a class that can't be stored as module global.

        This method is used to serialize classes that are defined inside
        functions, or that otherwise can't be serialized as attribute lookups
        from global modules.
553514
def save_dynamic_class(self, obj):
        
        clsdict = dict(obj.__dict__)  # copy dict proxy to a dict
        clsdict.pop('__weakref__', None)

        # For ABCMeta in python3.7+, remove _abc_impl as it is not picklable.
        # This is a fix which breaks the cache but this only makes the first
        # calls to issubclass slower.
        if "_abc_impl" in clsdict:
            import abc
            (registry, _, _, _) = abc._get_dump(obj)
            clsdict["_abc_impl"] = [subclass_weakref()
                                    for subclass_weakref in registry]

        # On PyPy, __doc__ is a readonly attribute, so we need to include it in
        # the initial skeleton class.  This is safe because we know that the
        # doc can't participate in a cycle with the original class.
        type_kwargs = {'__doc__': clsdict.pop('__doc__', None)}

        if hasattr(obj, "__slots__"):
            type_kwargs['__slots__'] = obj.__slots__
            # pickle string length optimization: member descriptors of obj are
            # created automatically from obj's __slots__ attribute, no need to
            # save them in obj's state
            if isinstance(obj.__slots__, string_types):
                clsdict.pop(obj.__slots__)
            else:
                for k in obj.__slots__:
                    clsdict.pop(k, None)

        # If type overrides __dict__ as a property, include it in the type kwargs.
        # In Python 2, we can't set this attribute after construction.
        __dict__ = clsdict.pop('__dict__', None)
        if isinstance(__dict__, property):
            type_kwargs['__dict__'] = __dict__

        save = self.save
        write = self.write

        # We write pickle instructions explicitly here to handle the
        # possibility that the type object participates in a cycle with its own
        # __dict__. We first write an empty "skeleton" version of the class and
        # memoize it before writing the class' __dict__ itself. We then write
        # instructions to "rehydrate" the skeleton class by restoring the
        # attributes from the __dict__.
        #
        # A type can appear in a cycle with its __dict__ if an instance of the
        # type appears in the type's __dict__ (which happens for the stdlib
        # Enum class), or if the type defines methods that close over the name
        # of the type, (which is common for Python 2-style super() calls).

        # Push the rehydration function.
        save(_rehydrate_skeleton_class)

        # Mark the start of the args tuple for the rehydration function.
        write(pickle.MARK)

        # Create and memoize an skeleton class with obj's name and bases.
        tp = type(obj)
        self.save_reduce(tp, (obj.__name__, obj.__bases__, type_kwargs), obj=obj)

        # Now save the rest of obj's __dict__. Any references to obj
        # encountered while saving will point to the skeleton class.
        save(clsdict)

        # Write a tuple of (skeleton_class, clsdict).
        write(pickle.TUPLE)

        # Call _rehydrate_skeleton_class(skeleton_class, clsdict)
        write(pickle.REDUCE)
1097596
def __store_any(self, o, method_name, member):
        
        if should_exclude( eval( "o." + method_name ), self.__exclusion_list ):
            self.__store__[ method_name ] = eval( "o." + method_name )
            return

        if hasattr( member, '__call__' ):
            self.__store_callable( o, method_name, member )
        elif inspect.isclass( member ):
            self.__store_class( o, method_name, member ) # Default ot lazy-loading classes here.
        elif not util.is_primitive( member ):
            self.__store_nonprimitive( o, method_name, member )
        else:
            self.__store_other( o, method_name, member )
87619
def save():
    
    from .models import ModuleInfo

    logger = logging.getLogger(__name__)
    logger.info("Saving changes")

    # Save + restart
    for module in modules():
        if module.enabled:
            if module.changed:
                module.save()
                module.restart()
                module.commit()
            else:
                logger.debug('Not saving unchanged module: %s' %
                             module.verbose_name)
        else:
            logger.debug('Not saving disabled module: %s' %
                         module.verbose_name)

    # Commit
    ModuleInfo.commit()

    logger.info("Changes saved")
497314
def save_intrinsic_alias(module):
    
    for v in module.values():
        if isinstance(v, dict):  # Submodules case
            save_intrinsic_alias(v)
        else:
            IntrinsicAliases[v] = frozenset((v,))
            if isinstance(v, Class):
                save_intrinsic_alias(v.fields)
547612
def save(self, obj):
        """"""
        if not obj.id:
            obj.id = uuid()

        stored_data = {
            'id': obj.id,
            'value': obj.to_data()
        }

        index_vals = obj.indexes() or {}
        for key in obj.__class__.index_names() or []:
            val = index_vals.get(key, '')
            stored_data[key] = DynamoMappings.map_index_val(val)

        table = self.get_class_table(obj.__class__)
        item = Item(table, data=stored_data)

        item.save(overwrite=True)
1060566
def save(self, *args, **kwargs):
        
        cls = self.__class__
        if self.pk:
            rows = cls.objects.filter(
                pk=self.pk, _change=self._change).update(
                _change=self._change + 1)
            if not rows:
                raise ConcurrentModificationError(cls.__name__, self.pk)
            self._change += 1

        count = 0
        max_retries=3
        while True:
            try:
                return super(BaseModel, self).save(*args, **kwargs)
            except django.db.utils.OperationalError:
                if count >= max_retries:
                    raise
                count += 1
70088
def writeObject(self, obj, is_proxy=False):
        
        if self.use_proxies and not is_proxy:
            self.writeProxy(obj)

            return

        self.stream.write(TYPE_OBJECT)

        ref = self.context.getObjectReference(obj)

        if ref != -1:
            self._writeInteger(ref << 1)

            return

        self.context.addObject(obj)

        # object is not referenced, serialise it
        kls = obj.__class__
        definition = self.context.getClass(kls)
        alias = None
        class_ref = False # if the class definition is a reference

        if definition:
            class_ref = True
            alias = definition.alias
        else:
            alias = self.context.getClassAlias(kls)
            definition = ClassDefinition(alias)

            self.context.addClass(definition, alias.klass)

        if class_ref:
            self.stream.write(definition.reference)
        else:
            ref = 0

            if definition.encoding != ObjectEncoding.EXTERNAL:
                ref += definition.attr_len << 4

            final_reference = encode_int(ref | definition.encoding << 2 |
                REFERENCE_BIT << 1 | REFERENCE_BIT)

            self.stream.write(final_reference)

            definition.reference = encode_int(
                definition.reference << 2 | REFERENCE_BIT)

            if alias.anonymous:
                self.stream.write('\x01')
            else:
                self.serialiseString(alias.alias)

            # work out what the final reference for the class will be.
            # this is okay because the next time an object of the same
            # class is encoded, class_ref will be True and never get here
            # again.

        if alias.external:
            obj.__writeamf__(DataOutput(self))

            return

        attrs = alias.getEncodableAttributes(obj, codec=self)

        if alias.static_attrs:
            if not class_ref:
                [self.serialiseString(attr) for attr in alias.static_attrs]

            for attr in alias.static_attrs:
                value = attrs.pop(attr)

                self.writeElement(value)

            if definition.encoding == ObjectEncoding.STATIC:
                return

        if definition.encoding == ObjectEncoding.DYNAMIC:
            if attrs:
                for attr, value in attrs.iteritems():
                    if type(attr) in python.int_types:
                        attr = str(attr)

                    self.serialiseString(attr)
                    self.writeElement(value)

            self.stream.write('\x01')
45345
def unwrap(self):
        
        if self.args_type == "MODULE_FUNCTION":
            setattr(self.obj, self.prop, self.orig_func)
        elif self.args_type == "MODULE":
            delattr(self.obj, "__SINONLOCK__")
        elif self.args_type == "FUNCTION":
            setattr(CPSCOPE, self.obj.__name__, self.orig_func)
        elif self.args_type == "PURE":
            setattr(self.pure, "func", self.orig_func)
202067
def save_to_file(self, filename: str) -> ConfigFile:
        
        newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0],
                              dump_hook=self.normal_class_hook[1], safe_load=self.safe_load)
        return newclass
339852
function createAbstractClass(params, constructor) {
        var def,
            savedMembers,
            key,
            value;

        // Handle abstract methods
        if (hasOwn(params, '$abstracts')) {
            savedMembers = params.$abstracts;
            delete params.$abstracts;
        }

        // Create the class definition
        def = Class.$create(params, constructor);
        def[$abstract] = true;

        // Grab binds
        if (savedMembers) {
            for (key in savedMembers) {
                value = savedMembers[key];

                if (value[$bound]) {
                    insert(def[$class].binds, key);
                }
            }
        }

        return def;
    }
1011304
def from_serializable(cls, object_dict):
        

        key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH)
        key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH)

        obj_class = object_dict.pop(key_class)
        obj_module = object_dict.pop(key_module) if key_module in object_dict else None

        obj = cls._from_class(obj_class, obj_module)
        obj.modify_object(object_dict)
        return obj
648612
def proxy_global(name, no_expand_macro=False, fname='func', args=()):
    
    if no_expand_macro:  # pragma: no cover
        # handle older ROOT versions without _ExpandMacroFunction wrapping
        @property
        def gSomething_no_func(self):
            glob = self(getattr(ROOT, name))
            # create a fake func() that just returns self
            def func():
                return glob
            glob.func = func
            return glob
        return gSomething_no_func

    @property
    def gSomething(self):
        obj_func = getattr(getattr(ROOT, name), fname)
        try:
            obj = obj_func(*args)
        except ReferenceError:  # null pointer
            return None
        # asrootpy
        return self(obj)

    return gSomething
528344
def serialize(cls, obj):
        

        cls._initialize()
        serializer = cls._get_serializer(type(obj))

        if serializer == cls:
            return cls._serialize_default(obj)
        else:
            return serializer.serialize(obj)
1263396
def _convert(cls, name, module, filter, source=None):
    
    # convert all constants from source (or module) that pass filter() to
    # a new Enum called name, and export the enum and its members back to
    # module;
    # also, replace the __reduce_ex__ method so unpickling works in
    # previous Python versions
    module_globals = vars(_sys.modules[module])
    if source:
        source = vars(source)
    else:
        source = module_globals
    members = dict((name, value) for name, value in source.items() if filter(name))
    cls = cls(name, members, module=module)
    cls.__reduce_ex__ = _reduce_ex_by_name
    module_globals.update(cls.__members__)
    module_globals[name] = cls
    return cls
1123151
def serialize(exc):
    

    return {
        'exc_type': type(exc).__name__,
        'exc_path': get_module_path(type(exc)),
        'exc_args': list(map(safe_for_serialization, exc.args)),
        'value': safe_for_serialization(exc),
    }
1237795
def save_module(self, obj):
        
        mod_name = obj.__name__
        # If module is successfully found then it is not a dynamically created module
        if hasattr(obj, '__file__'):
            is_dynamic = False
        else:
            try:
                _find_module(mod_name)
                is_dynamic = False
            except ImportError:
                is_dynamic = True

        self.modules.add(obj)
        if is_dynamic:
            self.save_reduce(dynamic_subimport, (obj.__name__, vars(obj)), obj=obj)
        else:
            self.save_reduce(subimport, (obj.__name__,), obj=obj)
1133162
def save_to_store(self):
        
        if not self._store:
            raise AttributeError('No datastore defined!')
        saved_data = self.save_to_data(in_place=True)
        data = Serializer.serialize(saved_data)
        self._store.store_blob(data, 'all_keys_with_undefined')