text:
using System;
using System.Runtime.InteropServices;
using System.Text;

namespace Assimp.Unmanaged
{
    /// <summary>
    /// Represents an aiScene struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiScene
    {
        /// <summary>
        /// unsigned int, flags about the state of the scene
        /// </summary>
        public SceneFlags Flags;

        /// <summary>
        /// aiNode*, root node of the scenegraph.
        /// </summary>
        public IntPtr RootNode;

        /// <summary>
        /// Number of meshes contained.
        /// </summary>
        public uint NumMeshes;

        /// <summary>
        /// aiMesh**, meshes in the scene.
        /// </summary>
        public IntPtr Meshes;

        /// <summary>
        /// Number of materials contained.
        /// </summary>
        public uint NumMaterials;

        /// <summary>
        /// aiMaterial**, materials in the scene.
        /// </summary>
        public IntPtr Materials;

        /// <summary>
        /// Number of animations contained.
        /// </summary>
        public uint NumAnimations;

        /// <summary>
        /// aiAnimation**, animations in the scene.
        /// </summary>
        public IntPtr Animations;

        /// <summary>
        /// Number of embedded textures contained.
        /// </summary>
        public uint NumTextures;

        /// <summary>
        /// aiTexture**, textures in the scene.
        /// </summary>
        public IntPtr Textures;

        /// <summary>
        /// Number of lights contained.
        /// </summary>
        public uint NumLights;

        /// <summary>
        /// aiLight**, lights in the scene.
        /// </summary>
        public IntPtr Lights;

        /// <summary>
        /// Number of cameras contained.
        /// </summary>
        public uint NumCameras;

        /// <summary>
        /// aiCamera**, cameras in the scene.
        /// </summary>
        public IntPtr Cameras;

        /// <summary>
        /// void*, Private data do not touch!
        /// </summary>
        public IntPtr PrivateData;
    }

    /// <summary>
    /// Represents an aiNode struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiNode
    {
        /// <summary>
        /// Name of the node.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Node's transform relative to its parent.
        /// </summary>
        public Matrix4x4 Transformation;

        /// <summary>
        /// aiNode*, node's parent.
        /// </summary>
        public IntPtr Parent;

        /// <summary>
        /// Number of children the node owns.
        /// </summary>
        public uint NumChildren;

        /// <summary>
        /// aiNode**, array of nodes this node owns.
        /// </summary>
        public IntPtr Children;

        /// <summary>
        /// Number of meshes referenced by this node.
        /// </summary>
        public uint NumMeshes;

        /// <summary>
        /// unsigned int*, array of mesh indices.
        /// </summary>
        public IntPtr Meshes;

        /// <summary>
        /// aiMetadata*, pointer to a metadata container. May be NULL, if an importer doesn't document metadata then it doesn't write any.
        /// </summary>
        public IntPtr MetaData;
    }

    /// <summary>
    /// Represents an aiMetadataEntry struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMetadataEntry
    {
        /// <summary>
        /// Type of metadata.
        /// </summary>
        public MetaDataType DataType;

        /// <summary>
        /// Pointer to data.
        /// </summary>
        public IntPtr Data;
    }

    /// <summary>
    /// Represents an aiMetadata struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMetadata
    {
        /// <summary>
        /// Length of the Keys and Values arrays.
        /// </summary>
        public uint NumProperties;

        /// <summary>
        /// aiString*, array of keys. May not be NULL. Each entry must exist.
        /// </summary>
        public IntPtr keys;

        /// <summary>
        /// aiMetadataEntry*, array of values. May not be NULL. Entries may be NULL if the corresponding property key has no assigned value.
        /// </summary>
        public IntPtr Values;
    }

    /// <summary>
    /// Represents an aiMesh struct. Note: This structure requires marshaling, due to the arrays of IntPtrs.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMesh
    {
        /// <summary>
        /// unsigned int, bitwise flag detailing types of primitives contained.
        /// </summary>
        public PrimitiveType PrimitiveTypes;

        /// <summary>
        /// Number of vertices in the mesh, denotes length of
        /// -all- per-vertex arrays.
        /// </summary>
        public uint NumVertices;

        /// <summary>
        /// Number of faces in the mesh.
        /// </summary>
        public uint NumFaces;

        /// <summary>
        /// aiVector3D*, array of positions.
        /// </summary>
        public IntPtr Vertices;

        /// <summary>
        /// aiVector3D*, array of normals.
        /// </summary>
        public IntPtr Normals;

        /// <summary>
        /// aiVector3D*, array of tangents.
        /// </summary>
        public IntPtr Tangents;

        /// <summary>
        /// aiVector3D*, array of bitangents.
        /// </summary>
        public IntPtr BiTangents;

        /// <summary>
        /// aiColor4D*[Max_Value], array of arrays of vertex colors. Max_Value is defined as <see cref="AiDefines.AI_MAX_NUMBER_OF_COLOR_SETS"/>.
        /// </summary>
        public AiMeshColorArray Colors;

        /// <summary>
        /// aiVector3D*[Max_Value], array of arrays of texture coordinates. Max_Value is defined as <see cref="AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS"/>.
        /// </summary>
        public AiMeshTextureCoordinateArray TextureCoords;

        /// <summary>
        /// unsigned int[Max_Value], array of ints denoting the number of components for each set of texture coordinates - UV (2), UVW (3) for example.
        /// Max_Value is defined as <see cref="AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS"/>.
        /// </summary>
        public AiMeshUVComponentArray NumUVComponents;

        /// <summary>
        /// aiFace*, array of faces.
        /// </summary>
        public IntPtr Faces;

        /// <summary>
        /// Number of bones in the mesh.
        /// </summary>
        public uint NumBones;

        /// <summary>
        /// aiBone**, array of bones.
        /// </summary>
        public IntPtr Bones;

        /// <summary>
        /// Material index referencing the material in the scene.
        /// </summary>
        public uint MaterialIndex;

        /// <summary>
        /// Optional name of the mesh.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Number of attachment meshes. NOT CURRENTLY IN USE.
        /// </summary>
        public uint NumAnimMeshes;

        /// <summary>
        /// aiAnimMesh**, array of attachment meshes for vertex-based animation. NOT CURRENTLY IN USE.
        /// </summary>
        public IntPtr AnimMeshes;
    }

    /// <summary>
    /// Represents an aiTexture struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public unsafe struct AiTexture
    {
        //Internal use only
        private static readonly char[] s_nullFormat = new char[] { '\0', '\0', '\0', '\0' };

        /// <summary>
        /// Width of the texture.
        /// </summary>
        public uint Width;

        /// <summary>
        /// Height of the texture.
        /// </summary>
        public uint Height;

        /// <summary>
        /// sbyte[4], format extension hint. Fixed size char is two bytes regardless of encoding. Unmanaged assimp uses a char that
        /// maps to one byte.
        /// </summary>
        public fixed sbyte FormatHint[4];

        /// <summary>
        /// aiTexel*, array of texel data.
        /// </summary>
        public IntPtr Data;

        /// <summary>
        /// Sets the format hint.
        /// </summary>
        /// <param name="formatHint">Format hint - must be 3 characters or less</param>
        public void SetFormatHint(String formatHint)
        {
            char[] hintChars = (String.IsNullOrEmpty(formatHint)) ? s_nullFormat : formatHint.ToLowerInvariant().ToCharArray();

            int count = hintChars.Length;

            fixed(sbyte* charPtr = FormatHint)
            {
                charPtr[0] = (sbyte) ((count > 0) ? hintChars[0] : '\0');
                charPtr[1] = (sbyte) ((count > 1) ? hintChars[1] : '\0');
                charPtr[2] = (sbyte) ((count > 2) ? hintChars[2] : '\0');
                charPtr[3] = (sbyte) '\0';
            }
        }

        /// <summary>
        /// Gets the format hint.
        /// </summary>
        /// <returns>The format hint</returns>
        public String GetFormatHint()
        {
            fixed(sbyte* charPtr = FormatHint)
            {
                return new String(charPtr);
            }
        }
    }

    /// <summary>
    /// Represents an aiFace struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiFace
    {
        /// <summary>
        /// Number of indices in the face.
        /// </summary>
        public uint NumIndices;

        /// <summary>
        /// unsigned int*, array of indices.
        /// </summary>
        public IntPtr Indices;
    }

    /// <summary>
    /// Represents an aiBone struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiBone
    {
        /// <summary>
        /// Name of the bone.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Number of weights.
        /// </summary>
        public uint NumWeights;

        /// <summary>
        /// VertexWeight*, array of vertex weights.
        /// </summary>
        public IntPtr Weights;

        /// <summary>
        /// Matrix that transforms the vertex from mesh to bone space in bind pose
        /// </summary>
        public Matrix4x4 OffsetMatrix;
    }

    /// <summary>
    /// Represents an aiMaterialProperty struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMaterialProperty
    {
        /// <summary>
        /// Name of the property (key).
        /// </summary>
        public AiString Key;

        /// <summary>
        /// Textures: Specifies texture usage. None texture properties
        /// have this zero (or None).
        /// </summary>
        public TextureType Semantic;

        /// <summary>
        /// Textures: Specifies the index of the texture. For non-texture properties
        /// this is always zero.
        /// </summary>
        public uint Index;

        /// <summary>
        /// Size of the buffer data in bytes. This value may not be zero.
        /// </summary>
        public uint DataLength;

        /// <summary>
        /// Type of value contained in the buffer.
        /// </summary>
        public PropertyType Type;

        /// <summary>
        /// char*, byte buffer to hold the property's value.
        /// </summary>
        public IntPtr Data;
    }

    /// <summary>
    /// Represents an aiMaterial struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMaterial
    {
        /// <summary>
        /// aiMaterialProperty**, array of material properties.
        /// </summary>
        public IntPtr Properties;

        /// <summary>
        /// Number of key-value properties.
        /// </summary>
        public uint NumProperties;

        /// <summary>
        /// Storage allocated for key-value properties.
        /// </summary>
        public uint NumAllocated;
    }

    /// <summary>
    /// Represents an aiNodeAnim struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiNodeAnim
    {
        /// <summary>
        /// Name of the node affected by the animation. The node must exist
        /// and be unique.
        /// </summary>
        public AiString NodeName;

        /// <summary>
        /// Number of position keys.
        /// </summary>
        public uint NumPositionKeys;

        /// <summary>
        /// VectorKey*, position keys of this animation channel. Positions
        /// are 3D vectors and are accompanied by at least one scaling and one rotation key.
        /// </summary>
        public IntPtr PositionKeys;

        /// <summary>
        /// The number of rotation keys.
        /// </summary>
        public uint NumRotationKeys;

        /// <summary>
        /// QuaternionKey*, rotation keys of this animation channel. Rotations are 4D vectors (quaternions).
        /// If there are rotation keys there will be at least one scaling and one position key.
        /// </summary>
        public IntPtr RotationKeys;

        /// <summary>
        /// Number of scaling keys.
        /// </summary>
        public uint NumScalingKeys;

        /// <summary>
        /// VectorKey*, scaling keys of this animation channel. Scalings are specified as a
        /// 3D vector, and if there are scaling keys, there will at least be one position
        /// and one rotation key.
        /// </summary>
        public IntPtr ScalingKeys;

        /// <summary>
        /// Defines how the animation behaves before the first key is encountered.
        /// </summary>
        public AnimationBehaviour Prestate;

        /// <summary>
        /// Defines how the animation behaves after the last key was processed.
        /// </summary>
        public AnimationBehaviour PostState;
    }

    /// <summary>
    /// Represents an aiMeshAnim struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMeshAnim
    {
        /// <summary>
        /// Name of the mesh to be animated. Empty string not allowed.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Number of keys, there is at least one.
        /// </summary>
        public uint NumKeys;

        /// <summary>
        /// aiMeshkey*, the key frames of the animation. There must exist at least one.
        /// </summary>
        public IntPtr Keys;
    }

    /// <summary>
    /// Represents an aiAnimation struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiAnimation
    {
        /// <summary>
        /// Name of the animation.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Duration of the animation in ticks.
        /// </summary>
        public double Duration;

        /// <summary>
        /// Ticks per second, 0 if not specified in imported file.
        /// </summary>
        public double TicksPerSecond;

        /// <summary>
        /// Number of bone animation channels, each channel affects a single node.
        /// </summary>
        public uint NumChannels;

        /// <summary>
        /// aiNodeAnim**, node animation channels. Each channel affects a single node.
        /// </summary>
        public IntPtr Channels;

        /// <summary>
        /// Number of mesh animation channels. Each channel affects a single mesh and defines
        /// vertex-based animation.
        /// </summary>
        public uint NumMeshChannels;

        /// <summary>
        /// aiMeshAnim**, mesh animation channels. Each channel affects a single mesh.
        /// </summary>
        public IntPtr MeshChannels;
    }

    /// <summary>
    /// Represents an aiLight struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiLight
    {
        /// <summary>
        /// Name of the light.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Type of light.
        /// </summary>
        public LightSourceType Type;

        /// <summary>
        /// Position of the light.
        /// </summary>
        public Vector3D Position;

        /// <summary>
        /// Direction of the spot/directional light.
        /// </summary>
        public Vector3D Direction;

        /// <summary>
        /// Attenuation constant value.
        /// </summary>
        public float AttenuationConstant;

        /// <summary>
        /// Attenuation linear value.
        /// </summary>
        public float AttenuationLinear;

        /// <summary>
        /// Attenuation quadratic value.
        /// </summary>
        public float AttenuationQuadratic;

        /// <summary>
        /// Diffuse color.
        /// </summary>
        public Color3D ColorDiffuse;

        /// <summary>
        /// Specular color.
        /// </summary>
        public Color3D ColorSpecular;

        /// <summary>
        /// Ambient color.
        /// </summary>
        public Color3D ColorAmbient;

        /// <summary>
        /// Spot light inner angle.
        /// </summary>
        public float AngleInnerCone;

        /// <summary>
        /// Spot light outer angle.
        /// </summary>
        public float AngleOuterCone;
    }

    /// <summary>
    /// Represents an aiCamera struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiCamera
    {
        /// <summary>
        /// Name of the camera.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// Position of the camera.
        /// </summary>
        public Vector3D Position;

        /// <summary>
        /// Up vector of the camera.
        /// </summary>
        public Vector3D Up;

        /// <summary>
        /// Viewing direction of the camera.
        /// </summary>
        public Vector3D LookAt;

        /// <summary>
        /// Field Of View of the camera.
        /// </summary>
        public float HorizontalFOV;

        /// <summary>
        /// Near clip plane distance.
        /// </summary>
        public float ClipPlaneNear;

        /// <summary>
        /// Far clip plane distance.
        /// </summary>
        public float ClipPlaneFar;

        /// <summary>
        /// The Aspect ratio.
        /// </summary>
        public float Aspect;
    }

    /// <summary>
    /// Represents an aiString struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public unsafe struct AiString
    {
        /// <summary>
        /// Byte length of the UTF-8 string.
        /// </summary>
        public UIntPtr Length;

        /// <summary>
        /// Actual string data.
        /// </summary>
        public fixed byte Data[AiDefines.MAX_LENGTH];

        /// <summary>
        /// Constructs a new instance of the <see cref="AiString"/> struct.
        /// </summary>
        /// <param name="data">The string data</param>
        public AiString(String data)
        {
            Length = UIntPtr.Zero;

            SetString(data);
        }

        /// <summary>
        /// Convienence method for getting the AiString string - if the length is not greater than zero, it returns
        /// an empty string rather than garbage.
        /// </summary>
        /// <returns>AiString string data</returns>
        public unsafe String GetString()
        {
            int length = (int) Length.ToUInt32();

            if(length > 0)
            {
                byte[] copy = new byte[length];

                fixed(byte* bytePtr = Data)
                {
                    MemoryHelper.Read<byte>(new IntPtr(bytePtr), copy, 0, length);
                }

                //Note: aiTypes.h specifies aiString is UTF-8 encoded string.
                return Encoding.UTF8.GetString(copy, 0, length);
            }
            else
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// Convienence method for setting the AiString string (and length).
        /// </summary>
        /// <param name="data">String data to set</param>
        /// <returns>True if the operation was successful, false otherwise.</returns>
        public unsafe bool SetString(String data)
        {
            if(String.IsNullOrEmpty(data))
            {
                Length = new UIntPtr(0);
                fixed(byte* bytePtr = Data)
                    MemoryHelper.ClearMemory(new IntPtr(bytePtr), 0, AiDefines.MAX_LENGTH);

                return true;
            }

            //Note: aiTypes.h specifies aiString is UTF-8 encoded string.
            if(Encoding.UTF8.GetByteCount(data) <= AiDefines.MAX_LENGTH)
            {
                byte[] copy = Encoding.UTF8.GetBytes(data);

                //Write bytes to data field
                if(copy.Length > 0)
                {
                    fixed(byte* bytePtr = Data)
                        MemoryHelper.Write<byte>(new IntPtr(bytePtr), copy, 0, copy.Length);
                }

                Length = new UIntPtr((uint) copy.Length);

                return true;
            }

            return false;
        }

        /// <summary>
        /// Returns the fully qualified type name of this instance.
        /// </summary>
        /// <returns>A <see cref="T:System.String" /> containing a fully qualified type name.</returns>
        public override String ToString()
        {
            return GetString();
        }
    }

    /// <summary>
    /// Represents a log stream, which receives all log messages and streams them somewhere.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiLogStream
    {
        /// <summary>
        /// Function pointer that gets called when a message is to be logged.
        /// </summary>
        public IntPtr Callback;

        /// <summary>
        /// char*, user defined opaque data.
        /// </summary>
        public IntPtr UserData;
    }

    /// <summary>
    /// Represents the memory requirements for the different components of an imported
    /// scene. All sizes in in bytes.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMemoryInfo
    {
        /// <summary>
        /// Size of the storage allocated for texture data, in bytes.
        /// </summary>
        public uint Textures;

        /// <summary>
        /// Size of the storage allocated for material data, in bytes.
        /// </summary>
        public uint Materials;

        /// <summary>
        /// Size of the storage allocated for mesh data, in bytes.
        /// </summary>
        public uint Meshes;

        /// <summary>
        /// Size of the storage allocated for node data, in bytes.
        /// </summary>
        public uint Nodes;

        /// <summary>
        /// Size of the storage allocated for animation data, in bytes.
        /// </summary>
        public uint Animations;

        /// <summary>
        /// Size of the storage allocated for camera data, in bytes.
        /// </summary>
        public uint Cameras;

        /// <summary>
        /// Size of the storage allocated for light data, in bytes.
        /// </summary>
        public uint Lights;

        /// <summary>
        /// Total storage allocated for the imported scene, in bytes.
        /// </summary>
        public uint Total;
    }

    /// <summary>
    /// Represents an aiAnimMesh struct. Note: This structure requires marshaling, due to the array of IntPtrs.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiAnimMesh
    {
        /// <summary>
        /// aiVector3D*, replacement position array.
        /// </summary>
        public IntPtr Vertices;

        /// <summary>
        /// aiVector3D*, replacement normal array.
        /// </summary>
        public IntPtr Normals;

        /// <summary>
        /// aiVector3D*, replacement tangent array.
        /// </summary>
        public IntPtr Tangents;

        /// <summary>
        /// aiVector3D*, replacement bitangent array.
        /// </summary>
        public IntPtr BiTangents;

        /// <summary>
        /// aiColor4D*[Max_Value], array of arrays of vertex colors. Max_Value is defined as <see cref="AiDefines.AI_MAX_NUMBER_OF_COLOR_SETS"/>.
        /// </summary>
        public AiMeshColorArray Colors;

        /// <summary>
        /// aiVector3D*[Max_Value], array of arrays of texture coordinates. Max_Value is defined as <see cref="AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS"/>.
        /// </summary>
        public AiMeshTextureCoordinateArray TextureCoords;

        /// <summary>
        /// unsigned int, number of vertices.
        /// </summary>
        public uint NumVertices;
    }

    /// <summary>
    /// Describes a file format which Assimp can export to.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiExportFormatDesc
    {
        /// <summary>
        /// char*, a short string ID to uniquely identify the export format. e.g. "collada" or "obj"
        /// </summary>
        public IntPtr FormatId;

        /// <summary>
        /// char*, a short description of the file format to present to users.
        /// </summary>
        public IntPtr Description;

        /// <summary>
        /// char*, a recommended file extension of the exported file in lower case.
        /// </summary>
        public IntPtr FileExtension;
    }

    /// <summary>
    /// Describes a blob of exported scene data. Blobs can be nested, the first blob always has an empty name. Nested
    /// blobs represent auxillary files produced by the exporter (e.g. material files) and are named accordingly.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiExportDataBlob
    {
        /// <summary>
        /// size_t, size of the data in bytes.
        /// </summary>
        public UIntPtr Size;

        /// <summary>
        /// void*, the data.
        /// </summary>
        public IntPtr Data;

        /// <summary>
        /// AiString, name of the blob.
        /// </summary>
        public AiString Name;

        /// <summary>
        /// aiExportDataBlob*, pointer to the next blob in the chain.
        /// </summary>
        public IntPtr NextBlob;
    }

    /// <summary>
    /// Contains callbacks to implement a custom file system to open and close files.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiFileIO
    {
        /// <summary>
        /// Function pointer to open a new file.
        /// </summary>
        public IntPtr OpenProc;

        /// <summary>
        /// Function pointer used to close an existing file.
        /// </summary>
        public IntPtr CloseProc;

        /// <summary>
        /// Char*, user defined opaque data.
        /// </summary>
        public IntPtr UserData;
    }

    /// <summary>
    /// Contains callbacks to read and write to a file opened by a custom file system.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiFile
    {
        /// <summary>
        /// Function pointer to read from a file.
        /// </summary>
        public IntPtr ReadProc;

        /// <summary>
        /// Function pointer to write to a file.
        /// </summary>
        public IntPtr WriteProc;

        /// <summary>
        /// Function pointer to retrieve the current position of the file cursor.
        /// </summary>
        public IntPtr TellProc;

        /// <summary>
        /// Function pointer to retrieve the size of the file.
        /// </summary>
        public IntPtr FileSizeProc;

        /// <summary>
        /// Function pointer to set the current position of the file cursor.
        /// </summary>
        public IntPtr SeekProc;

        /// <summary>
        /// Function pointer to flush the file contents.
        /// </summary>
        public IntPtr FlushProc;

        /// <summary>
        /// Char*, user defined opaque data.
        /// </summary>
        public IntPtr UserData;
    }

    #region Delegates

    /// <summary>
    /// Callback delegate for Assimp's LogStream.
    /// </summary>
    /// <param name="msg">Log message</param>
    /// <param name="userData">char* pointer to user data that is passed to the callback</param>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate void AiLogStreamCallback([In, MarshalAs(UnmanagedType.LPStr)] String msg, IntPtr userData);

    /// <summary>
    /// Callback delegate for a custom file system, to write to a file.
    /// </summary>
    /// <param name="file">Pointer to an AiFile instance</param>
    /// <param name="dataToWrite">Char* pointer to data to write (casted from a void*)</param>
    /// <param name="sizeOfElemInBytes">Size of a single element in bytes to write</param>
    /// <param name="numElements">Number of elements to write</param>
    /// <returns>Number of elements successfully written. Should be zero if either size or numElements is zero. May be less than numElements if an error occured.</returns>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate UIntPtr AiFileWriteProc(IntPtr file, IntPtr dataToWrite, UIntPtr sizeOfElemInBytes, UIntPtr numElements);

    /// <summary>
    /// Callback delegate for a custom file system, to read from a file.
    /// </summary>
    /// <param name="file">Pointer to an AiFile instance.</param>
    /// <param name="dataToRead">Char* pointer that will store the data read (casted from a void*)</param>
    /// <param name="sizeOfElemInBytes">Size of a single element in bytes to read</param>
    /// <param name="numElements">Number of elements to read</param>
    /// <returns>Number of elements succesfully read. Should be zero if either size or numElements is zero. May be less than numElements if end of file is encountered, or if an error occured.</returns>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate UIntPtr AiFileReadProc(IntPtr file, IntPtr dataToRead, UIntPtr sizeOfElemInBytes, UIntPtr numElements);

    /// <summary>
    /// Callback delegate for a custom file system, to tell offset/size information about the file.
    /// </summary>
    /// <param name="file">Pointer to an AiFile instance.</param>
    /// <returns>Returns the current file cursor or the file size in bytes. May be -1 if an error has occured.</returns>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate UIntPtr AiFileTellProc(IntPtr file);

    /// <summary>
    /// Callback delegate for a custom file system, to flush the contents of the file to the disk.
    /// </summary>
    /// <param name="file">Pointer to an AiFile instance.</param>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate void AiFileFlushProc(IntPtr file);

    /// <summary>
    /// Callback delegate for a custom file system, to set the current position of the file cursor.
    /// </summary>
    /// <param name="file">Pointer to An AiFile instance.</param>
    /// <param name="offset">Offset from the origin.</param>
    /// <param name="seekOrigin">Position used as a reference</param>
    /// <returns>Returns success, if successful</returns>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate ReturnCode AiFileSeek(IntPtr file, UIntPtr offset, Origin seekOrigin);

    /// <summary>
    /// Callback delegate for a custom file system, to open a given file and create a new AiFile instance.
    /// </summary>
    /// <param name="fileIO">Pointer to an AiFileIO instance.</param>
    /// <param name="pathToFile">Path to the target file</param>
    /// <param name="mode">Read-write permissions to request</param>
    /// <returns>Pointer to an AiFile instance.</returns>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate IntPtr AiFileOpenProc(IntPtr fileIO, [In, MarshalAs(UnmanagedType.LPStr)] String pathToFile, [In, MarshalAs(UnmanagedType.LPStr)] String mode);

    /// <summary>
    /// Callback delegate for a custom file system, to close a given file and free its memory.
    /// </summary>
    /// <param name="fileIO">Pointer to an AiFileIO instance.</param>
    /// <param name="file">Pointer to an AiFile instance that will be closed.</param>
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    [CLSCompliant(false)]
    public delegate void AiFileCloseProc(IntPtr fileIO, IntPtr file);

    #endregion

    #region Collections

    /// <summary>
    /// Fixed length array for representing the color channels of a mesh. Length is equal
    /// to <see cref="AiDefines.AI_MAX_NUMBER_OF_COLOR_SETS"/>.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public unsafe struct AiMeshColorArray
    {
        //No fixed size intptrs
        private IntPtr m_ptr0, m_ptr1, m_ptr2, m_ptr3, m_ptr4, m_ptr5, m_ptr6, m_ptr7;

        /// <summary>
        /// Gets the length of the array.
        /// </summary>
        public int Length
        {
            get
            {
                return AiDefines.AI_MAX_NUMBER_OF_COLOR_SETS;
            }
        }

        /// <summary>
        /// Gets or sets an array value at the specified index.
        /// </summary>
        /// <param name="index">Zero-based index.</param>
        public IntPtr this[int index]
        {
            get
            {
                switch(index)
                {
                    case 0:
                        return m_ptr0;
                    case 1:
                        return m_ptr1;
                    case 2:
                        return m_ptr2;
                    case 3:
                        return m_ptr3;
                    case 4:
                        return m_ptr4;
                    case 5:
                        return m_ptr5;
                    case 6:
                        return m_ptr6;
                    case 7:
                        return m_ptr7;
                    default:
                        return IntPtr.Zero;
                }
            }
            set
            {
                switch(index)
                {
                    case 0:
                        m_ptr0 = value;
                        break;
                    case 1:
                        m_ptr1 = value;
                        break;
                    case 2:
                        m_ptr2 = value;
                        break;
                    case 3:
                        m_ptr3 = value;
                        break;
                    case 4:
                        m_ptr4 = value;
                        break;
                    case 5:
                        m_ptr5 = value;
                        break;
                    case 6:
                        m_ptr6 = value;
                        break;
                    case 7:
                        m_ptr7 = value;
                        break;
                }
            }
        }
    }

    /// <summary>
    /// Fixed length array for representing the texture coordinate channels of a mesh. Length is equal
    /// to <see cref="AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS"/>.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public unsafe struct AiMeshTextureCoordinateArray
    {
        //No fixed size intptrs
        private IntPtr m_ptr0, m_ptr1, m_ptr2, m_ptr3, m_ptr4, m_ptr5, m_ptr6, m_ptr7;

        /// <summary>
        /// Gets the length of the array.
        /// </summary>
        public int Length
        {
            get
            {
                return AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS;
            }
        }

        /// <summary>
        /// Gets or sets an array value at the specified index.
        /// </summary>
        /// <param name="index">Zero-based index.</param>
        public IntPtr this[int index]
        {
            get
            {
                switch(index)
                {
                    case 0:
                        return m_ptr0;
                    case 1:
                        return m_ptr1;
                    case 2:
                        return m_ptr2;
                    case 3:
                        return m_ptr3;
                    case 4:
                        return m_ptr4;
                    case 5:
                        return m_ptr5;
                    case 6:
                        return m_ptr6;
                    case 7:
                        return m_ptr7;
                    default:
                        return IntPtr.Zero;
                }
            }
            set
            {
                switch(index)
                {
                    case 0:
                        m_ptr0 = value;
                        break;
                    case 1:
                        m_ptr1 = value;
                        break;
                    case 2:
                        m_ptr2 = value;
                        break;
                    case 3:
                        m_ptr3 = value;
                        break;
                    case 4:
                        m_ptr4 = value;
                        break;
                    case 5:
                        m_ptr5 = value;
                        break;
                    case 6:
                        m_ptr6 = value;
                        break;
                    case 7:
                        m_ptr7 = value;
                        break;
                }
            }
        }
    }

    /// <summary>
    /// Fixed length array for representing the number of UV components for each texture coordinate channel of a mesh. Length is equal
    /// to <see cref="AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS"/>.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    [CLSCompliant(false)]
    public struct AiMeshUVComponentArray
    {
        //Could use fixed size array here, but have an inkling that constantly fixing for each indexer operation might be burdensome
        private uint m_uvw0, m_uvw1, m_uvw2, m_uvw3, m_uvw4, m_uvw5, m_uvw6, m_uvw7;

        /// <summary>
        /// Gets the length of the array.
        /// </summary>
        public int Length
        {
            get
            {
                return AiDefines.AI_MAX_NUMBER_OF_TEXTURECOORDS;
            }
        }

        /// <summary>
        /// Gets or sets an array value at the specified index.
        /// </summary>
        /// <param name="index">Zero-based index.</param>
        public uint this[int index]
        {
            get
            {
                switch(index)
                {
                    case 0:
                        return m_uvw0;
                    case 1:
                        return m_uvw1;
                    case 2:
                        return m_uvw2;
                    case 3:
                        return m_uvw3;
                    case 4:
                        return m_uvw4;
                    case 5:
                        return m_uvw5;
                    case 6:
                        return m_uvw6;
                    case 7:
                        return m_uvw7;
                    default:
                        return 0;
                }
            }
            set
            {
                switch(index)
                {
                    case 0:
                        m_uvw0 = value;
                        break;
                    case 1:
                        m_uvw1 = value;
                        break;
                    case 2:
                        m_uvw2 = value;
                        break;
                    case 3:
                        m_uvw3 = value;
                        break;
                    case 4:
                        m_uvw4 = value;
                        break;
                    case 5:
                        m_uvw5 = value;
                        break;
                    case 6:
                        m_uvw6 = value;
                        break;
                    case 7:
                        m_uvw7 = value;
                        break;
                }
            }
        }
    }

    #endregion
}


text:
#include "Texture.hpp"
SDL_Renderer* Texture::sRenderer = NULL;
void Texture::RegisterRenderer(SDL_Renderer* theRenderer)
{
	if (theRenderer != NULL)
	{
		sRenderer = theRenderer;
	}
	else
		FLOG(GExL::StatusAppInitFailed) << "Null Renderer pointer passed to Texture::RegisterRenderer()" << std::endl;
}

Texture::Texture() : mTexture(NULL){}

bool Texture::LoadFromFile(std::string theFilename)
{
	bool anResult = false;
	if (theFilename.length() > 0)
	{
		SDL_Texture* anTexture = NULL;
		SDL_Surface* anLoadedSurface = IMG_Load(theFilename.c_str());
		if (anLoadedSurface != NULL)
		{
			//Color key image
			SDL_SetColorKey(anLoadedSurface, SDL_TRUE, SDL_MapRGB(anLoadedSurface->format, 0xFF, 0, 0xFF));
			anTexture = SDL_CreateTextureFromSurface(Texture::sRenderer, anLoadedSurface);
			if (anTexture != NULL)
			{
				mTexture = anTexture;
				SDL_FreeSurface(anLoadedSurface);
				anResult = true;
			}
		}
	}
	return anResult;
}

void Texture::Render(GExL::Vector2f thePosition, float theRotation, GExL::Vector2f theScale, GExL::IntRect theClipRect, GExL::Vector2f theOrigin, Color theColor)
{
	SDL_Rect anSrcRect, anDstRect;
	if (mTexture != NULL)
	{
		anSrcRect.x = theClipRect.x;
		anSrcRect.y = theClipRect.y;

		anDstRect.x = (GExL::Int32)thePosition.x;
		anDstRect.y = (GExL::Int32)thePosition.y;
		if (theClipRect.w == 0 || theClipRect.h == 0)
		{
			SDL_QueryTexture(mTexture, NULL, NULL, &anDstRect.w, &anDstRect.h);
		}
		else
		{
			anDstRect.w = theClipRect.w;
			anDstRect.h = theClipRect.h;
		}
		anSrcRect.w = anDstRect.w;
		anSrcRect.h = anDstRect.h;
		anDstRect.w *= theScale.x;
		anDstRect.h *= theScale.y;
		anDstRect.x -= (anDstRect.w*(GExL::Int32)theOrigin.x);
		anDstRect.y -= (anDstRect.h*(GExL::Int32)theOrigin.y);
		SDL_SetTextureColorMod(mTexture, theColor.r, theColor.g, theColor.b);
		SDL_RenderCopy(sRenderer, mTexture, &anSrcRect, &anDstRect);
	}
}
bool Texture::GenerateTilemapTexture(Texture& mTileset, tmxparser::TmxMap& theMap)
{
  Uint32 anPixelFormat;
  SDL_QueryTexture(mTileset.mTexture, &anPixelFormat, NULL, NULL, NULL);
  SDL_Texture *anTilemapTexture = SDL_CreateTexture(sRenderer, anPixelFormat, SDL_TEXTUREACCESS_TARGET, theMap.width*32, theMap.height * 32);
  SDL_SetRenderTarget(sRenderer, anTilemapTexture);
  GExL::Uint32 anTileIndex = 0;
  for (auto it = theMap.layerCollection.begin(); it != theMap.layerCollection.end(); ++it)
  {
    for (auto it2 = it->tiles.begin(); it2 != it->tiles.end(); ++it2)
    {
      GExL::Uint32 anTileGID = it2->gid - theMap.tilesetCollection.at(it2->tilesetIndex).firstgid;
      GExL::Uint32 anTilesetWidth = theMap.tilesetCollection.at(it2->tilesetIndex).colCount;
      GExL::Int32 anTileSourceX = anTileGID % anTilesetWidth;
      GExL::Int32 anTileSourceY = anTileGID / anTilesetWidth;
      GExL::Int32 anTileDestX = anTileIndex % theMap.width;
      GExL::Int32 anTileDestY = anTileIndex / theMap.width;

      SDL_Rect anSourceRect, anDestRect;
      anSourceRect.x = anTileSourceX * 32;
      anSourceRect.y = anTileSourceY * 32;
      anDestRect.x = anTileDestX * 32;
      anDestRect.y = anTileDestY * 32;
      anSourceRect.w = anDestRect.w = anSourceRect.h = anDestRect.h = 32;
      SDL_RenderCopy(sRenderer, mTileset.mTexture, &anSourceRect, &anDestRect);
      anTileIndex++;
    }
  }
  mTexture = anTilemapTexture;
  SDL_SetRenderTarget(sRenderer, NULL);
  return true;
}

redpajama_set_name: RedPajamaGithub


text:
package mem

import "github.com/sternix/gobsdinfo/util"

type Zone struct {
	Name     string `json:"name"`
	Size     int    `json:"size"`
	Limit    int    `json:"limit"`
	Used     int    `json:"used"`
	Free     int    `json:"free"`
	Requests int    `json:"requests"`
	Fail     int    `json:"fail"`
	Sleep    int    `json:"sleep"`
}

type jMemZone struct {
	Version    string `json:"__version"`
	Statistics struct {
		Zones []Zone `json:"zone"`
	} `json:"memory-zone-statistics"`
}

func Zones() ([]Zone, error) {
	var zone jMemZone
	if err := util.ExecAndParse(&zone, "/usr/bin/vmstat", "-z"); err != nil {
		return nil, err
	}

	return zone.Statistics.Zones, nil
}


text:
'use strict';
var expect = require('expect.js'),
    jsrules = require('../lib');

describe('jsrules', function() {
  it('is the namespace for a lightweight, forward-chaining inference engine that models Boolean logic', function(done) {
    expect(jsrules).to.be.ok();
    done();
  });
});


text:
update ACT_GE_PROPERTY set VALUE_ = '7.1.0.0' where NAME_ = 'schema.version';

alter table ACT_RE_DEPLOYMENT add VERSION_ INTEGER default 1;
alter table ACT_RE_DEPLOYMENT add PROJECT_RELEASE_VERSION_ NVARCHAR2(255);


text:
'use strict';
/**
 * This class represents a Row model
 */
export default class Row {
  /**
  * @constructor
  * @param {int} size - The row capacity
  * @param {array} items - (Optional) The values to initialize this row.
  */
  constructor(size, items) {
    this.capacity = size;
    this.items = items || [];
  }

  /**
  * Create a new box to this row and control the row capacity
  * @param {int} boxNumber - The new box number.
  * @param {int} afterNum - Place the new box after this box number.
  * @returns {int} Returns a box number in case of overflow and returns undefined when ok
  */
  createBox(boxNumber, afterNumber) {
  	// if afterNumber value was given
    if(afterNumber && afterNumber > 0) {
      // Insert the new boxNumber at the index position
      let index = this.items.indexOf(afterNumber);
      this.items.splice((index + 1), 0, boxNumber);
    } else {
      // Just insert at the begining
      this.items.unshift(boxNumber);
    }

    // Check if the row is over capacity
    if(this.items.length > this.capacity) {
      // I'm full, give this to another row please
      return this.items.pop();
    }
  }
}


text:
import json
import select
import socket

from .match import Match

def send_json(sock, data):
    sock.sendall((json.dumps(data)+'\n').encode())

class Supervisor():

    def __init__(self, host, port, known_games, silent=False):
        # Set up supervisor.
        self.known_games = known_games
        self.active_matches = {} # dict mapping socket => game object
        self.complete_matches = set()

        self.pending_sockets = [] # Sockets not yet connected to a game.

        self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.listen_sock.bind((host, port))
        self.listen_sock.listen(100)

        self.silent = silent

    def handle_new_connection(self):
        player_sock, _ = self.listen_sock.accept()
        self.pending_sockets.append(player_sock)

    def handle_game_request(self, player_sock):

        def ill_formed(msg):
            send_json(player_sock, {"log": msg })
            player_sock.close()
            self.pending_sockets.remove(player_sock)

        # Receive play request
        request = player_sock.recv(1028).decode()

        try:
            request_json = json.loads(request)
        except ValueError:
            return ill_formed("Game request is not json.")

        if 'game' not in request_json:
            return ill_formed("Please specify a game.")

        if request_json['game'] not in self.known_games:
            return ill_formed("We don't know that game.")

        game_string = request_json['game']

        eligible_matches = [e for e in self.active_matches.values() if e.is_waiting_for_player() and e.gname == game_string]
        if eligible_matches:
            match = eligible_matches[0]
        else:
            match = Match(game_string, self.known_games[game_string]())

        self.active_matches[player_sock] = match
        player_number = match.add_player(player_sock)

        self.pending_sockets.remove(player_sock)

        # build and send acknowledgment
        acknowledgment = {
            'name': game_string,
            'timelimit': 5,
            'player': player_number,
            }
        send_json(player_sock, acknowledgment)

        if match.is_ready():
            send_json(match.players[0], match.build_state())
            match.set_last_move_time()

    def handle_match_message(self, sock):
        match = self.active_matches[sock]

        move_msg = sock.recv(1028).decode()

        try:
            move = json.loads(move_msg)
            match.make_move(move)
        except ValueError:
            match.log("Player %s submitted ill-formed json" % match.game.current_player)
            match.result = 3 - match.game.current_player

        if self.silent is False:
            print(match.game.draw_board())

        if match.get_result() != 0:
            self.complete_matches.add(match)
            for i, player in enumerate(match.players, start=1):
                send_json(player, match.build_state(player=i))
        else:
            send_json(match.get_current_socket(), match.build_state())

    def supervise(self):
        while True:
            self.loop(5)

    def loop(self, timeout):

        current_sockets = [e.get_current_socket() for e in set(self.active_matches.values())]

        all_sockets = current_sockets + self.pending_sockets + [self.listen_sock]

        readable_sockets, _, _ = select.select(all_sockets, [], [], timeout)

        for sock in readable_sockets:
            if sock == self.listen_sock:
                self.handle_new_connection()
            elif sock in self.pending_sockets:
                self.handle_game_request(sock)
            else:
                self.handle_match_message(sock)

        # Clean up.
        self.active_matches = {s:g for (s, g) in self.active_matches.items() if g not in self.complete_matches}
        self.complete_matches = set()


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*++

Module Name:

    exception/signal.cpp

Abstract:

    Signal handler implementation (map signals to exceptions)

--*/

#include "pal/corunix.hpp"
#include "pal/handleapi.hpp"
#include "pal/thread.hpp"
#include "pal/threadinfo.hpp"
#include "pal/threadsusp.hpp"
#include "pal/seh.hpp"

#include "pal/palinternal.h"
#if !HAVE_MACH_EXCEPTIONS
#include "pal/dbgmsg.h"
#include "pal/init.h"
#include "pal/process.h"
#include "pal/debug.h"

#include <signal.h>
#include <errno.h>
#include <string.h>
#include <sys/ucontext.h>
#include <sys/utsname.h>
#include <unistd.h>

#include "pal/context.h"

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(EXCEPT);

/* local type definitions *****************************************************/

#if !HAVE_SIGINFO_T
/* This allows us to compile on platforms that don't have siginfo_t.
 * Exceptions will work poorly on those platforms. */
#warning Exceptions will work poorly on this platform
typedef void *siginfo_t;
#endif  /* !HAVE_SIGINFO_T */
typedef void (*SIGFUNC)(int, siginfo_t *, void *);

/* internal function declarations *********************************************/

static void sigill_handler(int code, siginfo_t *siginfo, void *context);
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context);
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context);
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context);
static void sigbus_handler(int code, siginfo_t *siginfo, void *context);
static void sigint_handler(int code, siginfo_t *siginfo, void *context);
static void sigquit_handler(int code, siginfo_t *siginfo, void *context);
#if USE_SIGNALS_FOR_THREAD_SUSPENSION
void CorUnix::suspend_handler(int code, siginfo_t *siginfo, void *context);
void CorUnix::resume_handler(int code, siginfo_t *siginfo, void *context);
#endif // USE_SIGNALS_FOR_THREAD_SUSPENSION

static void common_signal_handler(PEXCEPTION_POINTERS pointers, int code,
                                  native_context_t *ucontext);

static void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction);
static void restore_signal(int signal_id, struct sigaction *previousAction);

/* internal data declarations *********************************************/

struct sigaction g_previous_sigill;
struct sigaction g_previous_sigtrap;
struct sigaction g_previous_sigfpe;
struct sigaction g_previous_sigbus;
struct sigaction g_previous_sigsegv;
struct sigaction g_previous_sigint;
struct sigaction g_previous_sigquit;

#if USE_SIGNALS_FOR_THREAD_SUSPENSION
struct sigaction g_previous_sigusr1;
struct sigaction g_previous_sigusr2;
#endif // USE_SIGNALS_FOR_THREAD_SUSPENSION

// Pipe used for sending SIGINT / SIGQUIT signals notifications to a helper thread
// that invokes the actual handler.
int g_signalPipe[2] = { 0, 0 };

DWORD g_dwExternalSignalHandlerThreadId = 0;

/* public function definitions ************************************************/

/*++
Function :
    SEHInitializeSignals

    Set-up signal handlers to catch signals and translate them to exceptions

Parameters :
    None

Return :
    TRUE in case of a success, FALSE otherwise
--*/
BOOL SEHInitializeSignals()
{
    TRACE("Initializing signal handlers\n");

    /* we call handle signal for every possible signal, even
       if we don't provide a signal handler.

       handle_signal will set SA_RESTART flag for specified signal.
       Therefore, all signals will have SA_RESTART flag set, preventing
       slow Unix system calls from being interrupted. On systems without
       siginfo_t, SIGKILL and SIGSTOP can't be restarted, so we don't
       handle those signals. Both the Darwin and FreeBSD man pages say
       that SIGKILL and SIGSTOP can't be handled, but FreeBSD allows us
       to register a handler for them anyway. We don't do that.

       see sigaction man page for more details
       */
    handle_signal(SIGILL, sigill_handler, &g_previous_sigill);
    handle_signal(SIGTRAP, sigtrap_handler, &g_previous_sigtrap);
    handle_signal(SIGFPE, sigfpe_handler, &g_previous_sigfpe);
    handle_signal(SIGBUS, sigbus_handler, &g_previous_sigbus);
    handle_signal(SIGSEGV, sigsegv_handler, &g_previous_sigsegv);
#if USE_SIGNALS_FOR_THREAD_SUSPENSION
    handle_signal(SIGUSR1, suspend_handler, &g_previous_sigusr1);
    handle_signal(SIGUSR2, resume_handler, &g_previous_sigusr2);
#endif

    /* The default action for SIGPIPE is process termination.
       Since SIGPIPE can be signaled when trying to write on a socket for which
       the connection has been dropped, we need to tell the system we want
       to ignore this signal.

       Instead of terminating the process, the system call which would had
       issued a SIGPIPE will, instead, report an error and set errno to EPIPE.
    */
    signal(SIGPIPE, SIG_IGN);

    return TRUE;
}

/*++
Function :
    SEHCleanupSignals

    Restore default signal handlers

Parameters :
    None

    (no return value)

note :
reason for this function is that during PAL_Terminate, we reach a point where
SEH isn't possible anymore (handle manager is off, etc). Past that point,
we can't avoid crashing on a signal
--*/
void SEHCleanupSignals()
{
    TRACE("Restoring default signal handlers\n");

    // Do not remove handlers for SIGUSR1 and SIGUSR2. They must remain so threads can be suspended
    // during cleanup after this function has been called.
    restore_signal(SIGILL, &g_previous_sigill);
    restore_signal(SIGTRAP, &g_previous_sigtrap);
    restore_signal(SIGFPE, &g_previous_sigfpe);
    restore_signal(SIGBUS, &g_previous_sigbus);
    restore_signal(SIGSEGV, &g_previous_sigsegv);

    // Only restore these signals if the signal handler thread was started and
    // the previous handlers saved.
    if (g_dwExternalSignalHandlerThreadId != 0)
    {
        restore_signal(SIGINT, &g_previous_sigint);
        restore_signal(SIGQUIT, &g_previous_sigquit);
    }
}

/* internal function definitions **********************************************/

#if USE_SIGNALS_FOR_THREAD_SUSPENSION

void CorUnix::suspend_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        CPalThread *pThread = InternalGetCurrentThread();
        if (pThread->suspensionInfo.HandleSuspendSignal(pThread))
        {
            return;
        }
    }

    TRACE("SIGUSR1 signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigusr1.sa_sigaction != NULL)
    {
        g_previous_sigusr1.sa_sigaction(code, siginfo, context);
    }
}

void CorUnix::resume_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        CPalThread *pThread = InternalGetCurrentThread();
        if (pThread->suspensionInfo.HandleResumeSignal())
        {
            return;
        }
    }

    TRACE("SIGUSR2 signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigusr2.sa_sigaction != NULL)
    {
        g_previous_sigusr2.sa_sigaction(code, siginfo, context);
    }
}

#endif // USE_SIGNALS_FOR_THREAD_SUSPENSION

/*++
Function :
    sigill_handler

    handle SIGILL signal (EXCEPTION_ILLEGAL_INSTRUCTION, others?)

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigill_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        EXCEPTION_RECORD record;
        EXCEPTION_POINTERS pointers;
        native_context_t *ucontext;

        ucontext = (native_context_t *)context;

        record.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
        record.ExceptionFlags = EXCEPTION_IS_SIGNAL;
        record.ExceptionRecord = NULL;
        record.ExceptionAddress = CONTEXTGetPC(ucontext);
        record.NumberParameters = 0;

        pointers.ExceptionRecord = &record;

        common_signal_handler(&pointers, code, ucontext);
    }

    TRACE("SIGILL signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigill.sa_sigaction != NULL)
    {
        g_previous_sigill.sa_sigaction(code, siginfo, context);
    }
    else
    {
        // Restore the original or default handler and restart h/w exception
        restore_signal(code, &g_previous_sigill);
    }
}

/*++
Function :
    sigfpe_handler

    handle SIGFPE signal (division by zero, floating point exception)

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigfpe_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        EXCEPTION_RECORD record;
        EXCEPTION_POINTERS pointers;
        native_context_t *ucontext;

        ucontext = (native_context_t *)context;

        record.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
        record.ExceptionFlags = EXCEPTION_IS_SIGNAL;
        record.ExceptionRecord = NULL;
        record.ExceptionAddress = CONTEXTGetPC(ucontext);
        record.NumberParameters = 0;

        pointers.ExceptionRecord = &record;

        common_signal_handler(&pointers, code, ucontext);
    }

    TRACE("SIGFPE signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigfpe.sa_sigaction != NULL)
    {
        g_previous_sigfpe.sa_sigaction(code, siginfo, context);
    }
    else
    {
        // Restore the original or default handler and restart h/w exception
        restore_signal(code, &g_previous_sigfpe);
    }
}

/*++
Function :
    sigsegv_handler

    handle SIGSEGV signal (EXCEPTION_ACCESS_VIOLATION, others)

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigsegv_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        EXCEPTION_RECORD record;
        EXCEPTION_POINTERS pointers;
        native_context_t *ucontext;

        ucontext = (native_context_t *)context;

        record.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
        record.ExceptionFlags = EXCEPTION_IS_SIGNAL;
        record.ExceptionRecord = NULL;
        record.ExceptionAddress = CONTEXTGetPC(ucontext);
        record.NumberParameters = 2;

        // TODO: First parameter says whether a read (0) or write (non-0) caused the
        // fault. We must disassemble the instruction at record.ExceptionAddress
        // to correctly fill in this value.
        record.ExceptionInformation[0] = 0;

        // Second parameter is the address that caused the fault.
        record.ExceptionInformation[1] = (size_t)siginfo->si_addr;

        pointers.ExceptionRecord = &record;

        common_signal_handler(&pointers, code, ucontext);
    }

    TRACE("SIGSEGV signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigsegv.sa_sigaction != NULL)
    {
        g_previous_sigsegv.sa_sigaction(code, siginfo, context);
    }
    else
    {
        // Restore the original or default handler and restart h/w exception
        restore_signal(code, &g_previous_sigsegv);
    }
}

/*++
Function :
    sigtrap_handler

    handle SIGTRAP signal (EXCEPTION_SINGLE_STEP, EXCEPTION_BREAKPOINT)

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigtrap_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        EXCEPTION_RECORD record;
        EXCEPTION_POINTERS pointers;
        native_context_t *ucontext;

        ucontext = (native_context_t *)context;

        record.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
        record.ExceptionFlags = EXCEPTION_IS_SIGNAL;
        record.ExceptionRecord = NULL;
        record.ExceptionAddress = CONTEXTGetPC(ucontext);
        record.NumberParameters = 0;

        pointers.ExceptionRecord = &record;

        common_signal_handler(&pointers, code, ucontext);
    }

    TRACE("SIGTRAP signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigtrap.sa_sigaction != NULL)
    {
        g_previous_sigtrap.sa_sigaction(code, siginfo, context);
    }
    else
    {
        // We abort instead of restore the original or default handler and returning
        // because returning from a SIGTRAP handler continues execution past the trap.
        abort();
    }
}

/*++
Function :
    HandleExternalSignal

    Handle the SIGINT and SIGQUIT signals.

Parameters :
    signalCode - code of the external signal

    (no return value)
--*/
static void HandleExternalSignal(int signalCode)
{
    BYTE signalCodeByte = (BYTE)signalCode;
    ssize_t writtenBytes;
    do
    {
        writtenBytes = write(g_signalPipe[1], &signalCodeByte, 1);
    }
    while ((writtenBytes == -1) && (errno == EINTR));

    if (writtenBytes == -1)
    {
        // Fatal error
        abort();
    }
}

/*++
Function :
    sigint_handler

    handle SIGINT signal

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigint_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        HandleExternalSignal(code);
    }
    else
    {
        TRACE("SIGINT signal was unhandled; chaining to previous sigaction\n");

        if (g_previous_sigint.sa_sigaction != NULL)
        {
            g_previous_sigint.sa_sigaction(code, siginfo, context);
        }
    }
}

/*++
Function :
    sigquit_handler

    handle SIGQUIT signal

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigquit_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        HandleExternalSignal(code);
    }
    else
    {
        TRACE("SIGQUIT signal was unhandled; chaining to previous sigaction\n");

        if (g_previous_sigquit.sa_sigaction != NULL)
        {
            g_previous_sigquit.sa_sigaction(code, siginfo, context);
        }
    }
}

/*++
Function :
    sigbus_handler

    handle SIGBUS signal (EXCEPTION_ACCESS_VIOLATION?)

Parameters :
    POSIX signal handler parameter list ("man sigaction" for details)

    (no return value)
--*/
static void sigbus_handler(int code, siginfo_t *siginfo, void *context)
{
    if (PALIsInitialized())
    {
        EXCEPTION_RECORD record;
        EXCEPTION_POINTERS pointers;
        native_context_t *ucontext;

        ucontext = (native_context_t *)context;

        record.ExceptionCode = CONTEXTGetExceptionCodeForSignal(siginfo, ucontext);
        record.ExceptionFlags = EXCEPTION_IS_SIGNAL;
        record.ExceptionRecord = NULL;
        record.ExceptionAddress = CONTEXTGetPC(ucontext);
        record.NumberParameters = 2;

        // TODO: First parameter says whether a read (0) or write (non-0) caused the
        // fault. We must disassemble the instruction at record.ExceptionAddress
        // to correctly fill in this value.
        record.ExceptionInformation[0] = 0;

        // Second parameter is the address that caused the fault.
        record.ExceptionInformation[1] = (size_t)siginfo->si_addr;

        pointers.ExceptionRecord = &record;

        common_signal_handler(&pointers, code, ucontext);
    }

    TRACE("SIGBUS signal was unhandled; chaining to previous sigaction\n");

    if (g_previous_sigbus.sa_sigaction != NULL)
    {
        g_previous_sigbus.sa_sigaction(code, siginfo, context);
    }
    else
    {
        // Restore the original or default handler and restart h/w exception
        restore_signal(code, &g_previous_sigbus);
    }
}

/*++
Function :
    SEHSetSafeState

    specify whether the current thread is in a state where exception handling
    of signals can be done safely

Parameters:
    BOOL state : TRUE if the thread is safe, FALSE otherwise

(no return value)
--*/
void SEHSetSafeState(CPalThread *pthrCurrent, BOOL state)
{
    if (NULL == pthrCurrent)
    {
        ASSERT( "Unable to get the thread object.\n" );
        return;
    }
    pthrCurrent->sehInfo.safe_state = state;
}

/*++
Function :
    SEHGetSafeState

    determine whether the current thread is in a state where exception handling
    of signals can be done safely

    (no parameters)

Return value :
    TRUE if the thread is in a safe state, FALSE otherwise
--*/
BOOL SEHGetSafeState(CPalThread *pthrCurrent)
{
    if (NULL == pthrCurrent)
    {
        ASSERT( "Unable to get the thread object.\n" );
        return FALSE;
    }
    return pthrCurrent->sehInfo.safe_state;
}

/*++
Function :
    common_signal_handler

    common code for all signal handlers

Parameters :
    PEXCEPTION_POINTERS pointers : exception information
    native_context_t *ucontext : context structure given to signal handler
    int code : signal received

    (no return value)
Note:
    the "pointers" parameter should contain a valid exception record pointer,
    but the contextrecord pointer will be overwritten.
--*/
static void common_signal_handler(PEXCEPTION_POINTERS pointers, int code,
                                  native_context_t *ucontext)
{
    sigset_t signal_set;
    CONTEXT context;

    // Pre-populate context with data from current frame, because ucontext doesn't have some data (e.g. SS register)
    // which is required for restoring context
    RtlCaptureContext(&context);

    // Fill context record with required information. from pal.h :
    // On non-Win32 platforms, the CONTEXT pointer in the
    // PEXCEPTION_POINTERS will contain at least the CONTEXT_CONTROL registers.
    CONTEXTFromNativeContext(ucontext, &context, CONTEXT_CONTROL | CONTEXT_INTEGER);

    pointers->ContextRecord = &context;

    /* Unmask signal so we can receive it again */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, code);
    if(-1 == sigprocmask(SIG_UNBLOCK, &signal_set, NULL))
    {
        ASSERT("sigprocmask failed; error is %d (%s)\n", errno, strerror(errno));
    }

    SEHProcessException(pointers);
}

/*++
Function :
    handle_signal

    register handler for specified signal

Parameters :
    int signal_id : signal to handle
    SIGFUNC sigfunc : signal handler
    previousAction : previous sigaction struct

    (no return value)

note : if sigfunc is NULL, the default signal handler is restored
--*/
void handle_signal(int signal_id, SIGFUNC sigfunc, struct sigaction *previousAction)
{
    struct sigaction newAction;

    newAction.sa_flags = SA_RESTART;
#if HAVE_SIGINFO_T
    newAction.sa_handler = NULL;
    newAction.sa_sigaction = sigfunc;
    newAction.sa_flags |= SA_SIGINFO;
#else   /* HAVE_SIGINFO_T */
    newAction.sa_handler = SIG_DFL;
#endif  /* HAVE_SIGINFO_T */
    sigemptyset(&newAction.sa_mask);

    if (-1 == sigaction(signal_id, &newAction, previousAction))
    {
        ASSERT("handle_signal: sigaction() call failed with error code %d (%s)\n",
            errno, strerror(errno));
    }
}

/*++
Function :
    restore_signal

    restore handler for specified signal

Parameters :
    int signal_id : signal to handle
    previousAction : previous sigaction struct to restore

    (no return value)
--*/
void restore_signal(int signal_id, struct sigaction *previousAction)
{
    if (-1 == sigaction(signal_id, previousAction, NULL))
    {
        ASSERT("restore_signal: sigaction() call failed with error code %d (%s)\n",
            errno, strerror(errno));
    }
}

static
DWORD
PALAPI
ExternalSignalHandlerThreadRoutine(
    PVOID
    );

static
DWORD
PALAPI
ControlHandlerThreadRoutine(
    PVOID pvSignal
    );

PAL_ERROR
StartExternalSignalHandlerThread(
    CPalThread *pthr)
{
    PAL_ERROR palError = NO_ERROR;

#ifndef DO_NOT_USE_SIGNAL_HANDLING_THREAD
    HANDLE hThread;

    if (pipe(g_signalPipe) != 0)
    {
        palError = ERROR_CANNOT_MAKE;
        goto done;
    }

    palError = InternalCreateThread(
        pthr,
        NULL,
        0,
        ExternalSignalHandlerThreadRoutine,
        NULL,
        0,
        SignalHandlerThread, // Want no_suspend variant
        &g_dwExternalSignalHandlerThreadId,
        &hThread
        );

    if (NO_ERROR != palError)
    {
        ERROR("Failure creating external signal handler thread (%d)\n", palError);
        goto done;
    }

    InternalCloseHandle(pthr, hThread);

    handle_signal(SIGINT, sigint_handler, &g_previous_sigint);
    handle_signal(SIGQUIT, sigquit_handler, &g_previous_sigquit);
#endif // DO_NOT_USE_SIGNAL_HANDLING_THREAD

done:

    return palError;
}

static
DWORD
PALAPI
ExternalSignalHandlerThreadRoutine(
    PVOID
    )
{
    DWORD dwThreadId;
    bool fContinue = TRUE;
    HANDLE hThread;
    PAL_ERROR palError = NO_ERROR;
    CPalThread *pthr = InternalGetCurrentThread();

    //
    // Wait for a signal to occur
    //

    while (fContinue)
    {
        BYTE signalCode;
        ssize_t bytesRead;

        do
        {
            bytesRead = read(g_signalPipe[0], &signalCode, 1);
        }
        while ((bytesRead == -1) && (errno == EINTR));

        if (bytesRead == -1)
        {
            // Fatal error
            abort();
        }

        switch (signalCode)
        {
            case SIGINT:
            case SIGQUIT:
            {
                //
                // Spin up a new thread to run the console handlers. We want
                // to do this even if no handlers are installed, as in that
                // case we want to do a normal shutdown from the new thread
                // while still having this thread available to handle any
                // other incoming signals.
                //
                // The new thread is always spawned, even if there are already
                // currently console handlers running; this follows the
                // Windows behavior. Yes, this means that poorly written
                // console handler routines can make it impossible to kill
                // a process using Ctrl-C or Ctrl-Break. "kill -9" is
                // your friend.
                //
                // This thread must not be marked as a PalWorkerThread --
                // since it may run user code it needs to make
                // DLL_THREAD_ATTACH notifications.
                //

                PVOID pvCtrlCode = UintToPtr(
                    SIGINT == signalCode ? CTRL_C_EVENT : CTRL_BREAK_EVENT
                    );

                palError = InternalCreateThread(
                    pthr,
                    NULL,
                    0,
                    ControlHandlerThreadRoutine,
                    pvCtrlCode,
                    0,
                    UserCreatedThread,
                    &dwThreadId,
                    &hThread
                    );

                if (NO_ERROR != palError)
                {
                    if (!PALIsShuttingDown())
                    {
                        // If PAL is not shutting down, failure to create a thread is
                        // a fatal error.
                        abort();
                    }
                    fContinue = FALSE;
                    break;
                }

                InternalCloseHandle(pthr, hThread);
                break;
            }

            default:
                ASSERT("Unexpected signal %d in signal thread\n", signalCode);
                abort();
                break;
        }
    }

    //
    // Perform an immediate (non-graceful) shutdown
    //

    _exit(EXIT_FAILURE);

    return 0;
}

static
DWORD
PALAPI
ControlHandlerThreadRoutine(
    PVOID pvSignal
    )
{
    // Uint and DWORD are implicitly the same.
    SEHHandleControlEvent(PtrToUint(pvSignal), NULL);
    return 0;
}

#endif // !HAVE_MACH_EXCEPTIONS


text:
class AddTargetingModeToPluginsEmailTools < ActiveRecord::Migration[5.1]
  def change
    add_column :plugins_email_tools, :targeting_mode, :integer, default: 0
  end
end


text:
Just a simple play scala app template
=====================================

# Includes the following libraries

backend:
- Play
- Scala
- Neo4j
- Spring.data

frontend:
- bootstrap
- bootstrap.datetimepicker
- font.awesome
- jquery
- jquery.autogrowtextarea
- jquery.dataTables
- select2

functional features:
- Session with roles and rights
- User management
- Application logging and monitoring
- Virtual file system
- Form helper

# Installation
Just install java 7 and zip and run the setup/setup.sh script
restart your shell
activator run
browse http://localhost:9000


text:
class virtual_handle :
public std::enable_shared_from_this<virtual_handle> {
public:

    virtual ~virtual_handle() {
    }
};

template <class T>
class Handle : virtual public virtual_handle {
public:

    std::shared_ptr<T> shared_from_this() {
        return std::dynamic_pointer_cast<T>(virtual_handle::shared_from_this());
    }
};

#endif


text:
RSpec.describe Yaks::Mapper::Form::DynamicField do
  describe ".create" do
    it "take a block" do
      expect(described_class.create { :foo }.block.call).to equal :foo
    end

    it "should ignore any options hash given" do
      expect { described_class.create(foo: :bar) }.to_not raise_error
    end
  end

  describe "#to_resource_fields" do
    include_context "yaks context"
    let(:mapper) { Yaks::Mapper.new(yaks_context) }
    let(:field) {
      described_class.create do |obj|
        text :first_name, value: obj
        text :last_name
      end
    }

    it "should return an array of fields" do
      mapper.call("Arne")
      expect(field.to_resource_fields(mapper)).to eql [
        Yaks::Resource::Form::Field.new(name: :first_name, type: :text, value: "Arne"),
        Yaks::Resource::Form::Field.new(name: :last_name, type: :text)
      ]
    end
  end
end


text:
require File.expand_path '../../../test_config', __FILE__

describe City do
  before do
    @city = City.new(name: 'Test Cité',
                     coords: nil,
                     start_year: 2017,
                     country: 'Argentina',
                     country_state: 'San Luis')
    @city.generate_url_name
    @city.save
  end

  it "should return the right url" do
    assert_equal '/test-cite', @city.url
  end

  it "should set and return the right coords" do
    refute @city.coords

    @city.set_coords(-54.807222, -68.304444)
    @city.save

    assert @city.coords

    assert_equal [-68.30444, -54.80722], @city.geojson_coords
  end

  describe "url_name" do
    it "should have the right url_name" do
      assert_equal 'test-cite', @city.url_name
    end

    it "should set a country-dependant url_name if it already exists" do
      new_city = City.new(name: 'Test Cité',
                          coords: nil,
                          start_year: 2017,
                          country: 'Nuevo País',
                          country_state: 'Ille de France')

      new_city.generate_url_name

      assert_equal 'test-cite-nuevo-pais', new_city.url_name
    end
  end
end


text:
package androidx.recyclerview.widget;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;

import android.support.test.filters.LargeTest;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@LargeTest
@RunWith(Parameterized.class)
public class GridLayoutManagerSnappingTest extends BaseGridLayoutManagerTest {

    final Config mConfig;
    final boolean mReverseScroll;

    public GridLayoutManagerSnappingTest(Config config, boolean reverseScroll) {
        mConfig = config;
        mReverseScroll = reverseScroll;
    }

    @Parameterized.Parameters(name = "config:{0},reverseScroll:{1}")
    public static List<Object[]> getParams() {
        List<Object[]> result = new ArrayList<>();
        List<Config> configs = createBaseVariations();
        for (Config config : configs) {
            for (boolean reverseScroll : new boolean[] {true, false}) {
                result.add(new Object[]{config, reverseScroll});
            }
        }
        return result;
    }

    @Test
    public void snapOnScrollSameView() throws Throwable {
        final Config config = (Config) mConfig.clone();
        RecyclerView recyclerView = setupBasic(config);
        waitForFirstLayout(recyclerView);
        setupSnapHelper();

        // Record the current center view.
        View view = findCenterView(mGlm);
        assertCenterAligned(view);
        int scrollDistance = (getViewDimension(view) / 2) - 1;
        int scrollDist = mReverseScroll ? -scrollDistance : scrollDistance;
        mGlm.expectIdleState(2);
        smoothScrollBy(scrollDist);
        mGlm.waitForSnap(10);

        // Views have not changed
        View viewAfterFling = findCenterView(mGlm);
        assertSame("The view should have scrolled", view, viewAfterFling);
        assertCenterAligned(viewAfterFling);
    }

    @Test
    public void snapOnScrollNextItem() throws Throwable {
        final Config config = (Config) mConfig.clone();
        RecyclerView recyclerView = setupBasic(config);
        waitForFirstLayout(recyclerView);
        setupSnapHelper();

        // Record the current center view.
        View view = findCenterView(mGlm);
        assertCenterAligned(view);
        int scrollDistance = getViewDimension(view) + 1;
        int scrollDist = mReverseScroll ? -scrollDistance : scrollDistance;

        smoothScrollBy(scrollDist);
        waitForIdleScroll(mRecyclerView);
        waitForIdleScroll(mRecyclerView);

        View viewAfterScroll = findCenterView(mGlm);

        assertNotSame("The view should have scrolled", view, viewAfterScroll);
        assertCenterAligned(viewAfterScroll);
    }

    @Test
    public void snapOnFlingSameView() throws Throwable {
        final Config config = (Config) mConfig.clone();
        RecyclerView recyclerView = setupBasic(config);
        waitForFirstLayout(recyclerView);
        setupSnapHelper();

        // Record the current center view.
        View view = findCenterView(mGlm);
        assertCenterAligned(view);

        // Velocity small enough to not scroll to the next view.
        int velocity = (int) (1.000001 * mRecyclerView.getMinFlingVelocity());
        int velocityDir = mReverseScroll ? -velocity : velocity;
        mGlm.expectIdleState(2);
        assertTrue(fling(velocityDir, velocityDir));
        // Wait for two settling scrolls: the initial one and the corrective one.
        waitForIdleScroll(mRecyclerView);
        mGlm.waitForSnap(100);

        View viewAfterFling = findCenterView(mGlm);

        assertSame("The view should NOT have scrolled", view, viewAfterFling);
        assertCenterAligned(viewAfterFling);
    }

    @Test
    public void snapOnFlingNextView() throws Throwable {
        final Config config = (Config) mConfig.clone();
        RecyclerView recyclerView = setupBasic(config);
        waitForFirstLayout(recyclerView);
        setupSnapHelper();

        // Record the current center view.
        View view = findCenterView(mGlm);
        assertCenterAligned(view);

        // Velocity high enough to scroll beyond the current view.
        int velocity = (int) (0.25 * mRecyclerView.getMaxFlingVelocity());
        int velocityDir = mReverseScroll ? -velocity : velocity;

        mGlm.expectIdleState(1);
        assertTrue(fling(velocityDir, velocityDir));
        mGlm.waitForSnap(100);
        getInstrumentation().waitForIdleSync();

        View viewAfterFling = findCenterView(mGlm);

        assertNotSame("The view should have scrolled!",
                ((TextView) view).getText(),((TextView) viewAfterFling).getText());
        assertCenterAligned(viewAfterFling);
    }

    private void setupSnapHelper() throws Throwable {
        SnapHelper snapHelper = new LinearSnapHelper();
        mGlm.expectIdleState(1);
        snapHelper.attachToRecyclerView(mRecyclerView);
        mGlm.waitForSnap(10);

        mGlm.expectLayout(1);
        scrollToPosition(mConfig.mItemCount / 2);
        mGlm.waitForLayout(2);

        View view = findCenterView(mGlm);
        int scrollDistance = distFromCenter(view) / 2;
        if (scrollDistance == 0) {
            return;
        }

        int scrollDist = mReverseScroll ? -scrollDistance : scrollDistance;

        mGlm.expectIdleState(2);
        smoothScrollBy(scrollDist);
        mGlm.waitForSnap(10);
    }

    @Nullable View findCenterView(RecyclerView.LayoutManager layoutManager) {
        if (layoutManager.canScrollHorizontally()) {
            return mRecyclerView.findChildViewUnder(mRecyclerView.getWidth() / 2, 0);
        } else {
            return mRecyclerView.findChildViewUnder(0, mRecyclerView.getHeight() / 2);
        }
    }

    private int getViewDimension(View view) {
        OrientationHelper helper;
        if (mGlm.canScrollHorizontally()) {
            helper = OrientationHelper.createHorizontalHelper(mGlm);
        } else {
            helper = OrientationHelper.createVerticalHelper(mGlm);
        }
        return helper.getDecoratedMeasurement(view);
    }

    private void assertCenterAligned(View view) {
        if(mGlm.canScrollHorizontally()) {
            assertEquals("The child should align with the center of the parent",
                    mRecyclerView.getWidth() / 2,
                    mGlm.getDecoratedLeft(view) +
                            mGlm.getDecoratedMeasuredWidth(view) / 2, 1);
        } else {
            assertEquals("The child should align with the center of the parent",
                    mRecyclerView.getHeight() / 2,
                    mGlm.getDecoratedTop(view) +
                            mGlm.getDecoratedMeasuredHeight(view) / 2, 1);
        }
    }

    private int distFromCenter(View view) {
        if (mGlm.canScrollHorizontally()) {
            return Math.abs(mRecyclerView.getWidth() / 2 - mGlm.getViewBounds(view).centerX());
        } else {
            return Math.abs(mRecyclerView.getHeight() / 2 - mGlm.getViewBounds(view).centerY());
        }
    }

    private boolean fling(final int velocityX, final int velocityY)
            throws Throwable {
        final AtomicBoolean didStart = new AtomicBoolean(false);
        mActivityRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                boolean result = mRecyclerView.fling(velocityX, velocityY);
                didStart.set(result);
            }
        });
        if (!didStart.get()) {
            return false;
        }
        waitForIdleScroll(mRecyclerView);
        return true;
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.pholser</groupId>
    <artifactId>property-binder</artifactId>
    <version>5.0-alpha-4-SNAPSHOT</version>
  </parent>

  <artifactId>modular-user-tests</artifactId>
  <packaging>jar</packaging>

  <properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.pholser</groupId>
      <artifactId>com-pholser-util-properties-propertybinder</artifactId>
      <version>5.0-alpha-4-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>com.pholser</groupId>
      <artifactId>modular-user</artifactId>
      <version>5.0-alpha-4-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.junit.platform</groupId>
      <artifactId>junit-platform-launcher</artifactId>
      <version>1.7.1</version>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.assertj</groupId>
      <artifactId>assertj-core</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-deploy-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
*Author: @JensLincke*

```javascript

async function bar() {

  lively.notify("Zone 1: " +  Zone.current.id + ": " + Zone.current.foo)

  await fetch("https://lively-kernel.org/").then(async r => {
    lively.notify("Zone 2.1: " + Zone.current.id + ": " + Zone.current.foo)

    // Insight: "text()" returns uninstrumented promise that looses the ZONE
    // Q: How to deal with native promises?
    // Alt: how to remember and explicitly set a zone?
    var result = r.text() // (A)
    // var result = await Promise.resolve(r.text()) // SOLUTION: wrap it in a promise...
    lively.notify("Zone 2.2: " + Zone.current.id + ": " + Zone.current.foo)

    return result
  })

  // await lively.sleep(1000) // (B)
  lively.notify("Zone 3: " + Zone.current.id + ": " + Zone.current.foo)

}

runZoned(async () => {
    await bar()
  }, {
    zoneValues: {
      foo: "world",
    }
  })

```

Using #ContextJS

```javascript
import * as cop from "src/client/ContextJS/src/contextjs.js"

cop.layer(window, "ZonifyNativePromisesLayer").refineClass(Response, {
  text(...rest) {
    return Promise.resolve(cop.proceed(...rest))
  },

  json(...rest) {
    return Promise.resolve(cop.proceed(...rest))
  }
})

ZonifyNativePromisesLayer.beGlobal()
```


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Text;

namespace Zutatensuppe.DiabloInterface.Plugin.PipeServer.Server
{
    public class JsonStreamReader
    {
        BinaryReader reader;
        Encoding encoding;

        public JsonStreamReader(Stream stream, Encoding encoding)
        {
            reader = new BinaryReader(stream);
            this.encoding = encoding;
        }

        public string ReadJsonString()
        {
            int length = reader.ReadInt32();
            byte[] buffer = new byte[length];
            reader.Read(buffer, 0, length);
            return encoding.GetString(buffer);
        }
    }

    public class JsonStreamWriter
    {
        BinaryWriter writer;
        Encoding encoding;
        JsonConverter[] converters;

        public JsonStreamWriter(Stream stream, Encoding encoding, params JsonConverter[] converters)
        {
            writer = new BinaryWriter(stream);
            this.encoding = encoding;
            this.converters = converters;
        }

        public JsonStreamWriter(Stream stream) : this(stream, Encoding.UTF8, new IsoDateTimeConverter()) { }

        void WriteJsonString(string data)
        {
            var buffer = encoding.GetBytes(data);
            writer.Write(buffer.Length);
            writer.Write(buffer);
        }

        public void WriteJson(object json)
        {
            WriteJsonString(JsonConvert.SerializeObject(json, converters));
        }

        public void Flush()
        {
            writer.Flush();
        }
    }
}