text:
"""
View configurations for ELOs package in Common Repository project.
"""

from __future__ import absolute_import, unicode_literals

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.messages.views import SuccessMessageMixin
from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import CreateView, DetailView, ListView, UpdateView
from django.shortcuts import redirect, get_object_or_404

from actstream import action
from actstream import actions
from braces.views import LoginRequiredMixin, OrderableListMixin
from notifications.signals import notify

from commonrepo.users.models import User as User

from .models import ELO, ELOMetadata, ELOType, ReusabilityTreeNode
from .forms import ELOForm, ELOForkForm, ELOUpdateForm, ELOMetadataUpdateForm

__author__ = 'yrchen@ATCity.org (Xaver Y.R. Chen)'

class ELOsCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    """
    View of ``ELO`` creating actions. Render the "ELOs Create" page.

    * Requires authentication.
    """

    model = ELO
    form_class = ELOForm
    template_name = "elos/elos_create.html"
    success_message = "%(name)s was created successfully"

    def get_form_kwargs(self):
        kwargs = super(ELOsCreateView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def form_valid(self, form):
        # only staff can choose user
        if not self.request.user.is_staff:
            form.instance.author = self.request.user
            form.save()

        return super(ELOsCreateView, self).form_valid(form)

    def get_success_url(self):
        # send action to action stream
        action.send(self.request.user, verb='created', target=self.object)
        return super(ELOsCreateView, self).get_success_url()

class ELOsDetailView(DetailView):
    """
    View of ``ELO`` detail. Render the "ELOs Detail" page.

    * Requires no authentication for basic detail of ELO.
    """

    model = ELO
    query_pk_and_slug = True
    template_name = 'elos/elos_detail.html'

    def dispatch(self, request, *args, **kwargs):
        elo = get_object_or_404(ELO, pk=self.kwargs['pk'])

        # Check the ELO is public or not
        if not elo.is_public:
            if not elo.author == request.user and not request.user.is_staff:
                messages.error(
                    request, 'Permission denied. The target ELO is private.')
                return redirect('elos:elos-alllist')
            else:
                return super(ELOsDetailView, self).dispatch(request,
                                                            *args, **kwargs)
        else:
            return super(ELOsDetailView, self).dispatch(request,
                                                        *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ELOsDetailView, self).get_context_data(**kwargs)
        elo = get_object_or_404(ELO, id=self.kwargs['pk'])

        # Check Reusability Tree
        if not hasattr(elo, 'reusability_tree'):
            elo.reusability_tree_build()
        # Force to rebuild every time
        else:
            elo.reusability_tree_update()

        context['nodes'] = ReusabilityTreeNode.objects.filter(base_elo=elo)

        # Count Fork
        context['fork_count'] = ELO.objects.filter(
            parent_elo=self.kwargs['pk']).count()

        return context

class ELOsForkView(LoginRequiredMixin, CreateView):
    """
    View of ``ELO`` forking actions. Render the "ELOs Fork" page.

    * Requires authentication.
    """

    model = ELO
    form_class = ELOForkForm
    template_name = "elos/elos_fork.html"

    def get_form_kwargs(self):
        kwargs = super(ELOsForkView, self).get_form_kwargs()
        kwargs.update({'request_user': self.request.user})
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def form_valid(self, form):
        # clone metadata
        if form.instance.parent_elo.metadata:
            elo_new_metadata = form.instance.parent_elo.metadata
            elo_new_metadata.pk = None
            elo_new_metadata.save()

            form.instance.metadata = elo_new_metadata
            form.save()

        # if parent ELO in not public, send a warning message
        if not form.instance.parent_elo.is_public:
            messages.warning(
                self.request,
                'Please be careful, You forked an unpublic ELO!')

        return super(ELOsForkView, self).form_valid(form)

    def get_success_url(self):
        # send action to action stream only when parent ELO is public
        if self.object.parent_elo.is_public:
            action.send(self.request.user, verb='forked', target=self.object)

        return super(ELOsForkView, self).get_success_url()

class ELOsListView(OrderableListMixin, ListView):
    """
    View of ``ELO`` list actions. Render the "All ELOs List" page.

    * Requires authentication.
    """

    template_name = 'elos/elos_list.html'
    paginate_by = settings.ELOS_MAX_ITEMS_PER_PAGE
    orderable_columns = ("id", "create_update", "update_date")
    orderable_columns_default = "id"

    def get_queryset(self):
        """
        Returns the result based on the request.user's permission.
        Only the staff can check all ELOs even it's unpublic.
        """
        if self.request.user.is_staff:
            unordered_queryset = ELO.objects.all()
        else:
            unordered_queryset = ELO.objects.filter(is_public=1)

        # Use get_ordered_queryset from OrderableListMixin
        return self.get_ordered_queryset(unordered_queryset)

class ELOsMyListView(OrderableListMixin, LoginRequiredMixin, ListView):
    """
    View of user related ``ELO`` list actions. Render the "My ELOs List" page.

    * Requires authentication.
    """

    template_name = 'elos/elos_my_list.html'
    paginate_by = settings.ELOS_MAX_ITEMS_PER_PAGE
    orderable_columns = ("id", "create_update", "update_date")
    orderable_columns_default = "id"

    # Use get_ordered_queryset from OrderableListMixin
    def get_queryset(self):
        """
        Returns the result based on the request.user.
        Only list the request.user's own ELOs.
        """
        unordered_queryset = ELO.objects.filter(author=self.request.user)
        return self.get_ordered_queryset(unordered_queryset)

class ELOsFollowingListView(OrderableListMixin, LoginRequiredMixin, ListView):
    """
    View of ``ELO`` following list actions. Render the "ELOs Following List" page.

    * Requires authentication.
    """

    template_name = 'elos/elos_following_list.html'
    paginate_by = settings.ELOS_MAX_ITEMS_PER_PAGE
    orderable_columns = ("id", "create_update", "update_date")
    orderable_columns_default = "id"

    def get_queryset(self):
        """
        Returns the result based on the request.user's following list.
        Only list the public ELOs. Staffs can check all ELOs.
        """
        user = get_object_or_404(User, username=self.request.user.username)

        # Staff can access all ELOs
        if self.request.user.is_staff:
            unordered_queryset = user.userprofile.follow_elos.all()
        else:
            unordered_queryset = user.userprofile.follow_elos.filter(
                is_public=1)

        return self.get_ordered_queryset(unordered_queryset)

class ELOsNetworkView(LoginRequiredMixin, DetailView):
    """
    View of ``ELO`` relation network actions. Render the "ELOs Network" page.

    * Requires authentication.
    """

    model = ELO
    query_pk_and_slug = True
    template_name = 'elos/elos_network.html'

    def dispatch(self, request, *args, **kwargs):
        elo = get_object_or_404(ELO, pk=self.kwargs['pk'])

        # Check the ELO is public or not
        if not elo.is_public:
            if not elo.author == request.user and not request.user.is_staff:
                messages.error(
                    request, 'Permission denied. The target ELO is private.')
                return redirect('elos:elos-alllist')
            else:
                return super(ELOsNetworkView, self).dispatch(request,
                                                             *args, **kwargs)
        else:
            return super(ELOsNetworkView, self).dispatch(request,
                                                         *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ELOsNetworkView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        elo = get_object_or_404(ELO, id=self.kwargs['pk'])
        parent_elos = []

        if elo.parent_elo_id != settings.ELO_ROOT_ID:
            while elo.parent_elo_id != settings.ELO_ROOT_ID:
                parent_elo = get_object_or_404(ELO, id=elo.parent_elo_id)
                parent_elos.insert(0, parent_elo)
                elo = parent_elo

        context['parent_elos'] = parent_elos
        context['child_elos'] = ELO.objects.filter(
            parent_elo=self.kwargs['pk'])
        return context

class ELOsUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    View of ``ELO`` updating actions. Render the "ELO Update" page.

    * Requires authentication.
    * Requires permission of the specific ``ELO``.
    """

    model = ELO
    form_class = ELOUpdateForm
    query_pk_and_slug = True
    template_name = 'elos/elos_update.html'
    success_message = "%(name)s was updated successfully"

    def dispatch(self, request, *args, **kwargs):
        # Check the request.user has permission to update the specific ELO
        elo = get_object_or_404(ELO, pk=self.kwargs['pk'])

        if not elo.author == request.user and not request.user.is_staff:
            messages.error(request, 'Permission denied.')
            return redirect('elos:elos-alllist')
        else:
            return super(ELOsUpdateView, self).dispatch(request,
                                                        *args, **kwargs)

    def form_valid(self, form):
        # Bumped the version of the related ELO
        self.object.version += 1
        return super(ELOsUpdateView, self).form_valid(form)

    def get_form_kwargs(self):
        kwargs = super(ELOsUpdateView, self).get_form_kwargs()
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        # send action to action stream
        action.send(self.request.user, verb='updated', target=self.object)
        return reverse("elos:elos-detail",
                       kwargs={'pk': self.kwargs['pk']})

class ELOsMetadataUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
    """
    View of ``ELO Metadata`` updating actions. Render the "ELO Metadata Update" page.

    * Requires authentication.
    * Requires permission of the specific ``ELO``.
    """

    model = ELOMetadata
    form_class = ELOMetadataUpdateForm
    query_pk_and_slug = False
    template_name = 'elos/elos_metadata_update.html'
    success_message = "The Metadata was updated successfully"

    def dispatch(self, request, *args, **kwargs):
        # Check the request.user has permission to update the specific ELO
        elo = get_object_or_404(ELO, pk=self.kwargs['pk'])

        if not elo.author == request.user and not request.user.is_staff:
            messages.error(request, 'Permission denied.')
            return redirect('elos:elos-alllist')
        else:
            return super(ELOsMetadataUpdateView, self).dispatch(request,
                                                                *args, **kwargs)

    def form_valid(self, form):
        # Bumped the version of the related ELO
        self.object.elo.version += 1
        self.object.elo.save()
        return super(ELOsMetadataUpdateView, self).form_valid(form)

    def get_object(self):
        # Only get the Metadata record from the specific exist ELO
        elo = get_object_or_404(ELO, pk=self.kwargs['pk'])

        # If the Metadata of the ELO is not exist, create it and
        # set the relationship between the ELO and Metadata
        try:
            if not elo.metadata:
                raise ELOMetadata.DoesNotExist
            else:
                metadata = elo.metadata
        except ELOMetadata.DoesNotExist:
            metadata = ELOMetadata.objects.create()
            elo.metadata = metadata
            elo.save()

        return metadata

    def get_form_kwargs(self):
        kwargs = super(ELOsMetadataUpdateView, self).get_form_kwargs()
        kwargs.update(self.kwargs)  # self.kwargs contains all url conf params
        return kwargs

    def get_success_url(self):
        # send action to action stream
        action.send(self.request.user, verb='updated', target=self.object.elo)
        return reverse("elos:elos-detail",
                       kwargs={'pk': self.kwargs['pk']})

class ELOTypesDetailView(LoginRequiredMixin, DetailView):
    """
    View of ``ELO`` Type detail actions. Render the "ELO Type Detail" page.

    * Requires authentication.
    """

    model = ELOType
    query_pk_and_slug = True
    template_name = 'elos/elotypes_detail.html'

@login_required
@csrf_exempt
def publish_elo(request, pk):
    """
    Publish the ``ELO``

    * Requires authentication.
    * Requires permission of the specific ``ELO``.
    """
    elo = get_object_or_404(ELO, id=pk)

    # If request.user is author or staff
    if elo.author == request.user or request.user.is_staff:
        elo.is_public = 1
        elo.save()
        action.send(request.user, verb='published', target=elo)
        messages.success(request, 'Successed, the target ELO is public now.')
    else:
        messages.error(request, 'Permission denied.')

    return redirect('elos:elos-detail', pk)

@login_required
@csrf_exempt
def unpublish_elo(request, pk):
    """
    Unpublish the ``ELO``

    * Requires authentication.
    * Requires permission of the specific ``ELO``.
    """
    elo = get_object_or_404(ELO, id=pk)

    # If request.user is author or staff
    if elo.author == request.user or request.user.is_staff:
        elo.is_public = 0
        elo.save()
        messages.warning(request, 'Successed, the target ELO is private now.')
    else:
        messages.error(request, 'Permission denied.')

    return redirect('elos:elos-detail', pk)

@login_required
@csrf_exempt
def follow_elo(request, pk):
    """
    Creates the follow relationship between ``request.user`` and the ``ELO``

    * Requires authentication.
    """
    elo = get_object_or_404(ELO, id=pk)

    if elo.is_public or request.user.is_staff:
        actions.follow(request.user, elo, send_action=True)
        notify.send(
            request.user,
            recipient=elo.author,
            verb=u'has followed your ELO',
            level='success')
        request.user.userprofile.follow_elos.add(elo)
        messages.success(request, 'Successed, you are following this ELO.')
    else:
        messages.error(request, 'Permission denied.')

    return redirect('elos:elos-detail', pk)

@login_required
@csrf_exempt
def unfollow_elo(request, pk):
    """
    Deletes the follow relationship between ``request.user`` and the ``ELO``

    * Requires authentication.
    """
    elo = get_object_or_404(ELO, id=pk)

    actions.unfollow(request.user, elo, send_action=False)
    request.user.userprofile.follow_elos.remove(elo)
    messages.warning(
        request,
        'Successed, you are not follow this ELO anymore.')

    return redirect('elos:elos-detail', pk)


text:
#include "VoxelData/VoxelSave.h"
#include "VoxelUtilities/VoxelSerializationUtilities.inl"
#include "VoxelUtilities/VoxelMathUtilities.h"
#include "VoxelMessages.h"
#include "Misc/ScopeExit.h"

DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelUncompressedSavesMemory);
DEFINE_VOXEL_MEMORY_STAT(STAT_VoxelCompressedSavesMemory);

struct FVoxelChunkSave32Bits
{
	FIntVector Position;
	int32 ValuesIndex = -1;
	int32 MaterialsIndex = -1;
	int32 FoliageIndex = -1;

	friend FArchive& operator<<(FArchive& Ar, FVoxelChunkSave32Bits& Save)
	{
		Ar << Save.Position;
		Ar << Save.ValuesIndex;
		Ar << Save.MaterialsIndex;
		Ar << Save.FoliageIndex;
		return Ar;
	}
};

struct FVoxelChunkSaveWithoutFoliage
{
	FIntVector Position;
	int32 ValuesIndex;
	int32 MaterialsIndex;

	FORCEINLINE friend FArchive& operator<<(FArchive& Ar, FVoxelChunkSaveWithoutFoliage& Save)
	{
		Ar << Save.Position;
		Ar << Save.ValuesIndex;
		Ar << Save.MaterialsIndex;

		return Ar;
	}

	FORCEINLINE operator FVoxelChunkSave32Bits() const
	{
		return { Position, ValuesIndex, MaterialsIndex, -1 };
	}
};

struct FVoxelFoliage
{
	uint8 R;
	uint8 G;
	uint8 B;
	uint8 A;

	inline friend FArchive& operator<<(FArchive& Ar, FVoxelFoliage& Foliage)
	{
		Ar << Foliage.R;
		Ar << Foliage.G;
		Ar << Foliage.B;
		Ar << Foliage.A;
		return Ar;
	}
};

void FVoxelUncompressedWorldSaveImpl::UpdateAllocatedSize() const
{
	DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelUncompressedSavesMemory, AllocatedSize);
	AllocatedSize =
		Chunks64.GetAllocatedSize() +
		ValueBuffers64.GetAllocatedSize() +
		MaterialBuffers64.GetAllocatedSize() +
		PlaceableItems64.GetAllocatedSize();
	INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelUncompressedSavesMemory, AllocatedSize);
}

bool FVoxelUncompressedWorldSaveImpl::Serialize(FArchive& Ar)
{
	if ((Ar.IsLoading() || Ar.IsSaving()) && !Ar.IsTransacting())
	{
		if (Ar.IsSaving())
		{
			Version = FVoxelSaveVersion::LatestVersion;
		}

		// Serialize version & depth
		{
			int32 Dummy = 42;
			Ar << Dummy;
			if (Dummy == 42) // Trick to know the version, as Depth is always smaller than 42
			{
				Ar << Version;
				Ar << Depth;
			}
			else
			{
				Version = FVoxelSaveVersion::BeforeCustomVersionWasAdded;
				Depth = Dummy;
			}
		}

		const auto SerializationVersion =
			Version >= FVoxelSaveVersion::ValueConfigFlagAndSaveGUIDs
			? FVoxelSerializationVersion::ValueConfigFlagAndSaveGUIDs
			: Version >= FVoxelSaveVersion::RemoveEnableVoxelSpawnedActorsEnableVoxelGrass
			? FVoxelSerializationVersion::RemoveEnableVoxelSpawnedActorsEnableVoxelGrass
			: FVoxelSerializationVersion::BeforeCustomVersionWasAdded;

		static_assert(FVoxelSerializationVersion::LatestVersion == FVoxelSerializationVersion::SHARED_StoreMaterialChannelsIndividuallyAndRemoveFoliage, "Need to add a new FVoxelSaveVersion");

		// Serialize GUID
		if (Version >= FVoxelSaveVersion::ValueConfigFlagAndSaveGUIDs)
		{
			Ar << Guid;
		}
		else
		{
			Guid = FGuid::NewGuid();
		}

		// Serialize UserFlags
		if (Version >= FVoxelSaveVersion::AddUserFlagsToSaves)
		{
			Ar << UserFlags;
		}
		else
		{
			UserFlags = 0;
		}

		// Serialize value config
		uint32 ValueConfigFlag = GVoxelValueConfigFlag;
		if (Version >= FVoxelSaveVersion::ValueConfigFlagAndSaveGUIDs)
		{
			Ar << ValueConfigFlag;
		}

		// Serialize material config
		uint32 MaterialConfigFlag = GVoxelMaterialConfigFlag;
		Ar << MaterialConfigFlag;

		if (Version >= FVoxelSaveVersion::Use64BitArrays)
		{
			// Serialize value buffers
			FVoxelSerializationUtilities::SerializeValues(Ar, ValueBuffers64, ValueConfigFlag, SerializationVersion);
			FVoxelSerializationUtilities::SerializeValues(Ar, SingleValues64, ValueConfigFlag, SerializationVersion);

			// Serialize material buffers
			FVoxelSerializationUtilities::SerializeMaterials(Ar, MaterialsIndices64, MaterialConfigFlag);
			MaterialBuffers64.BulkSerialize(Ar);
			SingleMaterials64.BulkSerialize(Ar);

			// Serialize chunks indices
			// Note: make sure to not use BulkSerialize as data isn't aligned
			Ar << Chunks64;

			// Serialize placeable items
			Ar << PlaceableItems64;
		}
		else
		{
			FVoxelValueArray ValueBuffers;
			FVoxelValueArray SingleValues;

			TNoGrowArray<TVoxelMaterialStorage<uint32>> MaterialsIndices;
			TNoGrowArray<uint8> MaterialBuffers;
			TNoGrowArray<uint8> SingleMaterials;

			TNoGrowArray<FVoxelChunkSave> Chunks;

			TArray<uint8> PlaceableItems;

			ON_SCOPE_EXIT
			{
				ValueBuffers64 = ValueBuffers;
				SingleValues64 = SingleValues;

				MaterialsIndices64 = MoveTemp(MaterialsIndices);
				MaterialBuffers64 = MoveTemp(MaterialBuffers);
				SingleMaterials64 = MoveTemp(SingleMaterials);

				Chunks64 = MoveTemp(Chunks);

				PlaceableItems64 = MoveTemp(PlaceableItems);
			};

			if (Version >= FVoxelSaveVersion::StoreMaterialChannelsIndividuallyAndRemoveFoliage)
			{
				// Serialize value buffers
				FVoxelSerializationUtilities::SerializeValues(Ar, ValueBuffers, ValueConfigFlag, SerializationVersion);
				FVoxelSerializationUtilities::SerializeValues(Ar, SingleValues, ValueConfigFlag, SerializationVersion);

				// Serialize material buffers
				FVoxelSerializationUtilities::SerializeMaterials(Ar, MaterialsIndices, MaterialConfigFlag);
				MaterialBuffers.BulkSerialize(Ar);
				SingleMaterials.BulkSerialize(Ar);

				// Serialize chunks indices
				// Note: make sure to not use BulkSerialize as data isn't aligned
				Ar << Chunks;
			}
			else
			{
				TNoGrowArray<FVoxelMaterial> OldMaterialBuffers;
				TNoGrowArray<FVoxelMaterial> OldSingleMaterials;

				// Serialize value buffers
				FVoxelSerializationUtilities::SerializeValues(Ar, ValueBuffers, ValueConfigFlag, SerializationVersion);

				// Serialize material buffers
				FVoxelSerializationUtilities::SerializeMaterials(Ar, OldMaterialBuffers, MaterialConfigFlag, SerializationVersion);

				// Serialize foliage buffers
				if (Version >= FVoxelSaveVersion::FoliagePaint)
				{
					TArray<FVoxelFoliage> FoliageBuffers;
					FoliageBuffers.BulkSerialize(Ar);
				}

				// Serialize single values buffers
				if (Version >= FVoxelSaveVersion::SingleValues)
				{
					FVoxelSerializationUtilities::SerializeValues(Ar, SingleValues, ValueConfigFlag, SerializationVersion);
					FVoxelSerializationUtilities::SerializeMaterials(Ar, OldSingleMaterials, MaterialConfigFlag, SerializationVersion);

					TArray<FVoxelFoliage> SingleFoliage;
					SingleFoliage.BulkSerialize(Ar);
				}

				// Serialize chunks indices
				struct FVoxelChunkSaveWithSingleMaterial
				{
					FIntVector Position;

					int32 ValuesIndex = -1;
					int32 MaterialsIndex = -1;

					bool bSingleValue = false;
					// Makes life easier when loading legacy files
					bool bSingleMaterial_Unused = false;
				};
				TNoGrowArray<FVoxelChunkSaveWithSingleMaterial> NewChunks;
				{
					TArray<FVoxelChunkSave32Bits> OldChunks;
					if (Version < FVoxelSaveVersion::FoliagePaint)
					{
						TArray<FVoxelChunkSaveWithoutFoliage> ChunksWithoutFoliage;
						if (Version == FVoxelSaveVersion::BeforeCustomVersionWasAdded)
						{
							Ar << ChunksWithoutFoliage;
						}
						else
						{
							ChunksWithoutFoliage.BulkSerialize(Ar);
						}
						OldChunks = TArray<FVoxelChunkSave32Bits>(ChunksWithoutFoliage);
					}
					else
					{
						OldChunks.BulkSerialize(Ar);
					}

					NewChunks.Empty(OldChunks.Num());
					for (auto& OldChunk : OldChunks)
					{
						constexpr int32 SingleValueIndexFlag = 1 << 30;

						FVoxelChunkSaveWithSingleMaterial& NewChunk = NewChunks.Emplace_GetRef();

						NewChunk.Position = OldChunk.Position;

						if (OldChunk.ValuesIndex != -1)
						{
							NewChunk.ValuesIndex = OldChunk.ValuesIndex & (~SingleValueIndexFlag);
							NewChunk.bSingleValue = OldChunk.ValuesIndex & SingleValueIndexFlag;
						}
						if (OldChunk.MaterialsIndex != -1)
						{
							NewChunk.MaterialsIndex = OldChunk.MaterialsIndex & (~SingleValueIndexFlag);
							NewChunk.bSingleMaterial_Unused = OldChunk.MaterialsIndex & SingleValueIndexFlag;
						}
					}
					ensureVoxelSlow(NewChunks.GetSlack() == 0);
				}

				// Fixup material indices, as they are now referencing the MaterialsIndices array and not MaterialBuffers/SingleMaterials
				{
					check(OldMaterialBuffers.Num() % VOXELS_PER_DATA_CHUNK == 0);

					MaterialsIndices.Empty(OldMaterialBuffers.Num() / VOXELS_PER_DATA_CHUNK + OldSingleMaterials.Num());
					MaterialBuffers.Empty(OldMaterialBuffers.Num() * FVoxelMaterial::NumChannels);
					SingleMaterials.Empty(OldSingleMaterials.Num() * FVoxelMaterial::NumChannels);

					Chunks.Empty(NewChunks.Num());

					// Fixup chunks
					for (auto& Chunk : NewChunks)
					{
						if (Chunk.MaterialsIndex != -1)
						{
							if (Chunk.bSingleMaterial_Unused)
							{
								const int32 OldIndex = Chunk.MaterialsIndex;

								Chunk.MaterialsIndex = MaterialsIndices.AddUninitialized(1);
								auto& MaterialIndices = MaterialsIndices[Chunk.MaterialsIndex];

								const FVoxelMaterial& Material = OldSingleMaterials[OldIndex];

								for (int32 Channel = 0; Channel < FVoxelMaterial::NumChannels; Channel++)
								{
									MaterialIndices.GetRaw(Channel) = SingleMaterials.Add(Material.GetRaw(Channel)) | MaterialIndexSingleValueFlag;
								}
							}
							else
							{
								check(Chunk.MaterialsIndex % VOXELS_PER_DATA_CHUNK == 0);

								const int32 OldIndex = Chunk.MaterialsIndex;

								Chunk.MaterialsIndex = MaterialsIndices.AddUninitialized(1);
								auto& MaterialIndices = MaterialsIndices[Chunk.MaterialsIndex];

								for (int32 Channel = 0; Channel < FVoxelMaterial::NumChannels; Channel++)
								{
									MaterialIndices.GetRaw(Channel) = MaterialBuffers.AddUninitialized(VOXELS_PER_DATA_CHUNK);
								}

								for (int32 Index = 0; Index < VOXELS_PER_DATA_CHUNK; Index++)
								{
									const FVoxelMaterial& Material = OldMaterialBuffers[OldIndex + Index];

									for (int32 Channel = 0; Channel < FVoxelMaterial::NumChannels; Channel++)
									{
										MaterialBuffers[MaterialIndices.GetRaw(Channel) + Index] = Material.GetRaw(Channel);
									}
								}
							}
						}
						FVoxelChunkSave NewChunk;
						NewChunk.Position = Chunk.Position;
						NewChunk.ValuesIndex = Chunk.ValuesIndex;
						NewChunk.MaterialsIndex = Chunk.MaterialsIndex;
						NewChunk.bSingleValue = Chunk.bSingleValue;
						Chunks.Add(NewChunk);
					}

					ensureVoxelSlow(MaterialsIndices.GetSlack() == 0);
					ensureVoxelSlow(MaterialBuffers.GetSlack() == 0);
					ensureVoxelSlow(SingleMaterials.GetSlack() == 0);
					ensureVoxelSlow(Chunks.GetSlack() == 0);
				}
			}

			// Serialize placeable items
			if (Version >= FVoxelSaveVersion::PlaceableItemsInSave)
			{
				Ar << PlaceableItems;
			}
		}

		if (Ar.IsLoading() && Ar.IsError())
		{
			FVoxelMessages::Error("VoxelSave: Serialization failed, data is corrupted");
			*this = FVoxelUncompressedWorldSaveImpl();
		}

		UpdateAllocatedSize();
	}

	return true;
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

FVoxelCompressedWorldSaveImpl::~FVoxelCompressedWorldSaveImpl()
{
	DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelCompressedSavesMemory, AllocatedSize);
}

bool FVoxelCompressedWorldSaveImpl::Serialize(FArchive& Ar)
{
	if ((Ar.IsLoading() || Ar.IsSaving()) && !Ar.IsTransacting())
	{
		if (Ar.IsSaving())
		{
			Version = FVoxelSaveVersion::LatestVersion;
		}

		Ar << Depth;
		Ar << Version;
		if (Version < FVoxelSaveVersion::ValueConfigFlagAndSaveGUIDs)
		{
			uint32 ConfigFlags;
			Ar << ConfigFlags;
			Guid = FGuid::NewGuid();
		}
		else
		{
			Ar << Guid;
		}
		Ar << CompressedData;

		UpdateAllocatedSize();
	}

	return true;
}

void FVoxelCompressedWorldSaveImpl::UpdateAllocatedSize() const
{
	DEC_VOXEL_MEMORY_STAT_BY(STAT_VoxelCompressedSavesMemory, AllocatedSize);
	AllocatedSize = CompressedData.GetAllocatedSize();
	INC_VOXEL_MEMORY_STAT_BY(STAT_VoxelCompressedSavesMemory, AllocatedSize);
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

void UVoxelWorldSaveObject::PostLoad()
{
	Super::PostLoad();
	CopyDepthFromSave();
}

void UVoxelWorldSaveObject::CopyDepthFromSave()
{
	Depth = Save.Const().GetDepth();
}

redpajama_set_name: RedPajamaGithub


text:
/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */

/**
 * @license
 * Copyright (c) 2015 The ExpandJS authors. All rights reserved.
 * This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
 * The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
 * The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
 */
(function () {
    "use strict";

    var lodash = require('lodash');

    /**
     * Checks if `value` is a native function.
     *
     * ```js
     * XP.isNative(Array.prototype.push);
     * // => true
     *
     * XP.isNative(XP.push);
     * // => false
     * ```
     *
     * @function isNative
     * @param {*} value The value to check.
     * @returns {boolean} Returns `true` or `false` accordingly to the check.
     */
    module.exports = function isNative(value) {
        return lodash.isNative(value);
    };

}());


text:
namespace chrono {
namespace vehicle {

/// @addtogroup vehicle_tracked_suspension
/// @{

/// Torsion-bar suspension system using linear dampers constructed with data from
/// file (JSON format)
class CH_VEHICLE_API RotationalDamperRWAssembly : public ChRotationalDamperRWAssembly {
  public:
    RotationalDamperRWAssembly(const std::string& filename, bool has_shock);
    RotationalDamperRWAssembly(const rapidjson::Document& d, bool has_shock);
    ~RotationalDamperRWAssembly();

    /// Return the mass of the arm body.
    virtual double GetArmMass() const override { return m_arm_mass; }
    /// Return the moments of inertia of the arm body.
    virtual const ChVector<>& GetArmInertia() const override { return m_arm_inertia; }
    /// Return a visualization radius for the arm body.
    virtual double GetArmVisRadius() const override { return m_arm_radius; }

    /// Return the functor object for the torsional spring torque.
    virtual ChLinkRotSpringCB::TorqueFunctor* GetSpringTorqueFunctor() const override { return m_spring_torqueCB; }

    /// Return the functor object for the torsional shock force.
    virtual ChLinkRotSpringCB::TorqueFunctor* GetShockTorqueCallback() const override { return m_shock_torqueCB; }

  private:
    virtual const ChVector<> GetLocation(PointId which) override { return m_points[which]; }

    virtual void Create(const rapidjson::Document& d) override;

    void LoadRoadWheel(const std::string& filename);

    ChLinkRotSpringCB::TorqueFunctor* m_spring_torqueCB;
    ChLinkRotSpringCB::TorqueFunctor* m_shock_torqueCB;

    ChVector<> m_points[NUM_POINTS];

    double m_arm_mass;
    ChVector<> m_arm_inertia;
    double m_arm_radius;
};

/// @} vehicle_tracked_suspension

}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
/* */
"format cjs";
  var ControlledObservable = (function (__super__) {

    inherits(ControlledObservable, __super__);

    function subscribe (observer) {
      return this.source.subscribe(observer);
    }

    function ControlledObservable (source, enableQueue, scheduler) {
      __super__.call(this, subscribe, source);
      this.subject = new ControlledSubject(enableQueue, scheduler);
      this.source = source.multicast(this.subject).refCount();
    }

    ControlledObservable.prototype.request = function (numberOfItems) {
      return this.subject.request(numberOfItems == null ? -1 : numberOfItems);
    };

    return ControlledObservable;

  }(Observable));

  var ControlledSubject = (function (__super__) {

    function subscribe (observer) {
      return this.subject.subscribe(observer);
    }

    inherits(ControlledSubject, __super__);

    function ControlledSubject(enableQueue, scheduler) {
      enableQueue == null && (enableQueue = true);

      __super__.call(this, subscribe);
      this.subject = new Subject();
      this.enableQueue = enableQueue;
      this.queue = enableQueue ? [] : null;
      this.requestedCount = 0;
      this.requestedDisposable = disposableEmpty;
      this.error = null;
      this.hasFailed = false;
      this.hasCompleted = false;
      this.scheduler = scheduler || currentThreadScheduler;
    }

    addProperties(ControlledSubject.prototype, Observer, {
      onCompleted: function () {
        this.hasCompleted = true;
        if (!this.enableQueue || this.queue.length === 0) {
          this.subject.onCompleted();
        } else {
          this.queue.push(Notification.createOnCompleted());
        }
      },
      onError: function (error) {
        this.hasFailed = true;
        this.error = error;
        if (!this.enableQueue || this.queue.length === 0) {
          this.subject.onError(error);
        } else {
          this.queue.push(Notification.createOnError(error));
        }
      },
      onNext: function (value) {
        var hasRequested = false;

        if (this.requestedCount === 0) {
          this.enableQueue && this.queue.push(Notification.createOnNext(value));
        } else {
          (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
          hasRequested = true;
        }
        hasRequested && this.subject.onNext(value);
      },
      _processRequest: function (numberOfItems) {
        if (this.enableQueue) {
          while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
          (this.queue.length > 0 && this.queue[0].kind !== 'N')) {
            var first = this.queue.shift();
            first.accept(this.subject);
            if (first.kind === 'N') {
              numberOfItems--;
            } else {
              this.disposeCurrentRequest();
              this.queue = [];
            }
          }

          return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
        }

        return { numberOfItems: numberOfItems, returnValue: false };
      },
      request: function (number) {
        this.disposeCurrentRequest();
        var self = this;

        this.requestedDisposable = this.scheduler.scheduleWithState(number,
        function(s, i) {
          var r = self._processRequest(i), remaining = r.numberOfItems;
          if (!r.returnValue) {
            self.requestedCount = remaining;
            self.requestedDisposable = disposableCreate(function () {
              self.requestedCount = 0;
            });
          }
        });

        return this.requestedDisposable;
      },
      disposeCurrentRequest: function () {
        this.requestedDisposable.dispose();
        this.requestedDisposable = disposableEmpty;
      }
    });

    return ControlledSubject;
  }(Observable));

  /**
   * Attaches a controller to the observable sequence with the ability to queue.
   * @example
   * var source = Rx.Observable.interval(100).controlled();
   * source.request(3); // Reads 3 values
   * @param {bool} enableQueue truthy value to determine if values should be queued pending the next request
   * @param {Scheduler} scheduler determines how the requests will be scheduled
   * @returns {Observable} The observable sequence which only propagates values on request.
   */
  observableProto.controlled = function (enableQueue, scheduler) {

    if (enableQueue && isScheduler(enableQueue)) {
        scheduler = enableQueue;
        enableQueue = true;
    }

    if (enableQueue == null) {  enableQueue = true; }
    return new ControlledObservable(this, enableQueue, scheduler);
  };