text:
package com.amazonaws.services.workmail.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListMailDomainsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The WorkMail organization for which to list domains.
     *

     */
    private String organizationId;
    /**
     *

     * The maximum number of results to return in a single call.
     *

     */
    private Integer maxResults;
    /**
     *

     * The token to use to retrieve the next page of results. The first call does not require a token.
     *

     */
    private String nextToken;

    /**
     *

     * The WorkMail organization for which to list domains.
     *

     *
     * @param organizationId
     *        The WorkMail organization for which to list domains.
     */

    public void setOrganizationId(String organizationId) {
        this.organizationId = organizationId;
    }

    /**
     *

     * The WorkMail organization for which to list domains.
     *

     *
     * @return The WorkMail organization for which to list domains.
     */

    public String getOrganizationId() {
        return this.organizationId;
    }

    /**
     *

     * The WorkMail organization for which to list domains.
     *

     *
     * @param organizationId
     *        The WorkMail organization for which to list domains.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListMailDomainsRequest withOrganizationId(String organizationId) {
        setOrganizationId(organizationId);
        return this;
    }

    /**
     *

     * The maximum number of results to return in a single call.
     *

     *
     * @param maxResults
     *        The maximum number of results to return in a single call.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of results to return in a single call.
     *

     *
     * @return The maximum number of results to return in a single call.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of results to return in a single call.
     *

     *
     * @param maxResults
     *        The maximum number of results to return in a single call.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListMailDomainsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * The token to use to retrieve the next page of results. The first call does not require a token.
     *

     *
     * @param nextToken
     *        The token to use to retrieve the next page of results. The first call does not require a token.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The token to use to retrieve the next page of results. The first call does not require a token.
     *

     *
     * @return The token to use to retrieve the next page of results. The first call does not require a token.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The token to use to retrieve the next page of results. The first call does not require a token.
     *

     *
     * @param nextToken
     *        The token to use to retrieve the next page of results. The first call does not require a token.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListMailDomainsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getOrganizationId() != null)
            sb.append("OrganizationId: ").append(getOrganizationId()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ListMailDomainsRequest == false)
            return false;
        ListMailDomainsRequest other = (ListMailDomainsRequest) obj;
        if (other.getOrganizationId() == null ^ this.getOrganizationId() == null)
            return false;
        if (other.getOrganizationId() != null && other.getOrganizationId().equals(this.getOrganizationId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getOrganizationId() == null) ? 0 : getOrganizationId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public ListMailDomainsRequest clone() {
        return (ListMailDomainsRequest) super.clone();
    }

}


text:
using System;
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;

namespace UnityEditor.Experimental.Rendering.HDPipeline
{
    public enum MaterialId
    {
        LitSSS = 0,
        LitStandard = 1,
        LitAniso = 2,
        LitIridescence = 3,
        LitSpecular = 4,
        LitTranslucent = 5
    };

    // A Material can be authored from the shader graph or by hand. When written by hand we need to provide an inspector.
    // Such a Material will share some properties between it various variant (shader graph variant or hand authored variant).
    // This is the purpose of BaseLitGUI. It contain all properties that are common to all Material based on Lit template.
    // For the default hand written Lit material see LitUI.cs that contain specific properties for our default implementation.
    abstract class BaseLitGUI : BaseUnlitGUI
    {
        protected static class StylesBaseLit
        {
            public static GUIContent doubleSidedNormalModeText = new GUIContent("Normal Mode", "Specifies the method HDRP uses to modify the normal base.\nMirror: Mirrors the normals with the vertex normal plane.\nFlip: Flips the normal.");
            public static GUIContent depthOffsetEnableText = new GUIContent("Depth Offset", "When enabled, HDRP uses the Height Map to calculate the depth offset for this Material.");

            // Displacement mapping (POM, tessellation, per vertex)
            //public static GUIContent enablePerPixelDisplacementText = new GUIContent("Per Pixel Displacement", "");

            public static GUIContent displacementModeText = new GUIContent("Displacement Mode", "Specifies the method HDRP uses to apply height map displacement to the selected element: Vertex, pixel, or tessellated vertex.\n You must use flat surfaces for Pixel displacement.");
            public static GUIContent lockWithObjectScaleText = new GUIContent("Lock With Object Scale", "When enabled, displacement mapping takes the absolute value of the scale of the object into account.");
            public static GUIContent lockWithTilingRateText = new GUIContent("Lock With Height Map Tiling Rate", "When enabled, displacement mapping takes the absolute value of the tiling rate of the height map into account.");

            // Material ID
            public static GUIContent materialIDText = new GUIContent("Material Type", "Specifies additional feature for this Material. Customize you Material with different settings depending on which Material Type you select.");
            public static GUIContent transmissionEnableText = new GUIContent("Transmission", "When enabled HDRP processes the transmission effect for subsurface scattering. Simulates the translucency of the object.");

            // Per pixel displacement
            public static GUIContent ppdMinSamplesText = new GUIContent("Minimum Steps", "Controls the minimum number of steps HDRP uses for per pixel displacement mapping.");
            public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum Steps", "Controls the maximum number of steps HDRP uses for per pixel displacement mapping.");
            public static GUIContent ppdLodThresholdText = new GUIContent("Fading Mip Level Start", "Controls the Height Map mip level where the parallax occlusion mapping effect begins to disappear.");
            public static GUIContent ppdPrimitiveLength = new GUIContent("Primitive Length", "Sets the length of the primitive (with the scale of 1) to which HDRP applies per-pixel displacement mapping. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters.");
            public static GUIContent ppdPrimitiveWidth = new GUIContent("Primitive Width", "Sets the width of the primitive (with the scale of 1) to which HDRP applies per-pixel displacement mapping. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters.");

            // Tessellation
            public static string tessellationModeStr = "Tessellation Mode";
            public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode));

            public static GUIContent tessellationText = new GUIContent("Tessellation Options", "Tessellation options");
            public static GUIContent tessellationFactorText = new GUIContent("Tessellation Factor", "Controls the strength of the tessellation effect. Higher values result in more tessellation. Maximum tessellation factor is 15 on the Xbox One and PS4");
            public static GUIContent tessellationFactorMinDistanceText = new GUIContent("Start Fade Distance", "Sets the distance (in meters) at which tessellation begins to fade out.");
            public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("End Fade Distance", "Sets the maximum distance (in meters) to the Camera where HDRP tessellates triangle.");
            public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle Size", "Sets the desired screen space size of triangles (in pixels). Smaller values result in smaller triangle.");
            public static GUIContent tessellationShapeFactorText = new GUIContent("Shape Factor", "Controls the strength of Phong tessellation shape (lerp factor).");
            public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle Culling Epsilon", "Controls triangle culling. A value of -1.0 disables back face culling for tessellation, higher values produce more aggressive culling and better performance.");

            // Vertex animation
            public static string vertexAnimation = "Vertex Animation";

            // Wind
            public static GUIContent windText = new GUIContent("Wind");
            public static GUIContent windInitialBendText = new GUIContent("Initial Bend");
            public static GUIContent windStiffnessText = new GUIContent("Stiffness");
            public static GUIContent windDragText = new GUIContent("Drag");
            public static GUIContent windShiverDragText = new GUIContent("Shiver Drag");
            public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality");

            public static GUIContent supportDecalsText = new GUIContent("Receive Decals", "Enable to allow Materials to receive decals.");

            public static GUIContent enableGeometricSpecularAAText = new GUIContent("Geometric Specular AA", "When enabled, HDRP reduces specular aliasing on high density meshes (particularly useful when the not using a normal map).");
            public static GUIContent specularAAScreenSpaceVarianceText = new GUIContent("Screen space variance", "Controls the strength of the Specular AA reduction. Higher values give a more blurry result and less aliasing.");
            public static GUIContent specularAAThresholdText = new GUIContent("Threshold", "Controls the effect of Specular AA reduction. A values of 0 does not apply reduction, higher values allow higher reduction.");

            // SSR
            public static GUIContent receivesSSRText = new GUIContent("Receive SSR", "When enabled, this Material can receive screen space reflections.");

        }

        public enum DoubleSidedNormalMode
        {
            Flip,
            Mirror,
            None
        }

        public enum TessellationMode
        {
            None,
            Phong
        }

        public enum DisplacementMode
        {
            None,
            Vertex,
            Pixel,
            Tessellation
        }

        public enum HeightmapParametrization
        {
            MinMax = 0,
            Amplitude = 1
        }

        protected MaterialProperty doubleSidedNormalMode = null;
        protected const string kDoubleSidedNormalMode = "_DoubleSidedNormalMode";
        protected MaterialProperty depthOffsetEnable = null;
        protected const string kDepthOffsetEnable = "_DepthOffsetEnable";

        // Properties
        // Material ID
        protected MaterialProperty materialID  = null;
        protected const string kMaterialID = "_MaterialID";
        protected MaterialProperty transmissionEnable = null;
        protected const string kTransmissionEnable = "_TransmissionEnable";

        protected const string kStencilRef = "_StencilRef";
        protected const string kStencilWriteMask = "_StencilWriteMask";
        protected const string kStencilRefDepth = "_StencilRefDepth";
        protected const string kStencilWriteMaskDepth = "_StencilWriteMaskDepth";
        protected const string kStencilRefGBuffer = "_StencilRefGBuffer";
        protected const string kStencilWriteMaskGBuffer = "_StencilWriteMaskGBuffer";
        protected const string kStencilRefMV = "_StencilRefMV";
        protected const string kStencilWriteMaskMV = "_StencilWriteMaskMV";
        protected const string kStencilRefDistortionVec = "_StencilRefDistortionVec";
        protected const string kStencilWriteMaskDistortionVec = "_StencilWriteMaskDistortionVec";

        protected MaterialProperty displacementMode = null;
        protected const string kDisplacementMode = "_DisplacementMode";
        protected MaterialProperty displacementLockObjectScale = null;
        protected const string kDisplacementLockObjectScale = "_DisplacementLockObjectScale";
        protected MaterialProperty displacementLockTilingScale = null;
        protected const string kDisplacementLockTilingScale = "_DisplacementLockTilingScale";

        // Per pixel displacement params
        protected MaterialProperty ppdMinSamples = null;
        protected const string kPpdMinSamples = "_PPDMinSamples";
        protected MaterialProperty ppdMaxSamples = null;
        protected const string kPpdMaxSamples = "_PPDMaxSamples";
        protected MaterialProperty ppdLodThreshold = null;
        protected const string kPpdLodThreshold = "_PPDLodThreshold";
        protected MaterialProperty ppdPrimitiveLength = null;
        protected const string kPpdPrimitiveLength = "_PPDPrimitiveLength";
        protected MaterialProperty ppdPrimitiveWidth = null;
        protected const string kPpdPrimitiveWidth = "_PPDPrimitiveWidth";
        protected MaterialProperty invPrimScale = null;
        protected const string kInvPrimScale = "_InvPrimScale";

        // Wind
        protected MaterialProperty windEnable = null;
        protected const string kWindEnabled = "_EnableWind";
        protected MaterialProperty windInitialBend = null;
        protected const string kWindInitialBend = "_InitialBend";
        protected MaterialProperty windStiffness = null;
        protected const string kWindStiffness = "_Stiffness";
        protected MaterialProperty windDrag = null;
        protected const string kWindDrag = "_Drag";
        protected MaterialProperty windShiverDrag = null;
        protected const string kWindShiverDrag = "_ShiverDrag";
        protected MaterialProperty windShiverDirectionality = null;
        protected const string kWindShiverDirectionality = "_ShiverDirectionality";

        // tessellation params
        protected MaterialProperty tessellationMode = null;
        protected const string kTessellationMode = "_TessellationMode";
        protected MaterialProperty tessellationFactor = null;
        protected const string kTessellationFactor = "_TessellationFactor";
        protected MaterialProperty tessellationFactorMinDistance = null;
        protected const string kTessellationFactorMinDistance = "_TessellationFactorMinDistance";
        protected MaterialProperty tessellationFactorMaxDistance = null;
        protected const string kTessellationFactorMaxDistance = "_TessellationFactorMaxDistance";
        protected MaterialProperty tessellationFactorTriangleSize = null;
        protected const string kTessellationFactorTriangleSize = "_TessellationFactorTriangleSize";
        protected MaterialProperty tessellationShapeFactor = null;
        protected const string kTessellationShapeFactor = "_TessellationShapeFactor";
        protected MaterialProperty tessellationBackFaceCullEpsilon = null;
        protected const string kTessellationBackFaceCullEpsilon = "_TessellationBackFaceCullEpsilon";

        // Decal
        protected MaterialProperty supportDecals = null;
        protected const string kSupportDecals = "_SupportDecals";
        protected MaterialProperty enableGeometricSpecularAA = null;
        protected const string kEnableGeometricSpecularAA = "_EnableGeometricSpecularAA";
        protected MaterialProperty specularAAScreenSpaceVariance = null;
        protected const string kSpecularAAScreenSpaceVariance = "_SpecularAAScreenSpaceVariance";
        protected MaterialProperty specularAAThreshold = null;
        protected const string kSpecularAAThreshold = "_SpecularAAThreshold";

        // SSR
        protected MaterialProperty receivesSSR = null;
        protected const string kReceivesSSR = "_ReceivesSSR";

        protected override void FindBaseMaterialProperties(MaterialProperty[] props)
        {
            base.FindBaseMaterialProperties(props);

            doubleSidedNormalMode = FindProperty(kDoubleSidedNormalMode, props, false);
            depthOffsetEnable = FindProperty(kDepthOffsetEnable, props, false);

            // MaterialID
            materialID = FindProperty(kMaterialID, props, false);
            transmissionEnable = FindProperty(kTransmissionEnable, props, false);

            displacementMode = FindProperty(kDisplacementMode, props, false);
            displacementLockObjectScale = FindProperty(kDisplacementLockObjectScale, props, false);
            displacementLockTilingScale = FindProperty(kDisplacementLockTilingScale, props, false);

            // Per pixel displacement
            ppdMinSamples = FindProperty(kPpdMinSamples, props, false);
            ppdMaxSamples = FindProperty(kPpdMaxSamples, props, false);
            ppdLodThreshold = FindProperty(kPpdLodThreshold, props, false);
            ppdPrimitiveLength = FindProperty(kPpdPrimitiveLength, props, false);
            ppdPrimitiveWidth  = FindProperty(kPpdPrimitiveWidth, props, false);
            invPrimScale = FindProperty(kInvPrimScale, props, false);

            // tessellation specific, silent if not found
            tessellationMode = FindProperty(kTessellationMode, props, false);
            tessellationFactor = FindProperty(kTessellationFactor, props, false);
            tessellationFactorMinDistance = FindProperty(kTessellationFactorMinDistance, props, false);
            tessellationFactorMaxDistance = FindProperty(kTessellationFactorMaxDistance, props, false);
            tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false);
            tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false);
            tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false);

            // Wind
            windEnable = FindProperty(kWindEnabled, props, false);
            windInitialBend = FindProperty(kWindInitialBend, props, false);
            windStiffness = FindProperty(kWindStiffness, props, false);
            windDrag = FindProperty(kWindDrag, props, false);
            windShiverDrag = FindProperty(kWindShiverDrag, props, false);
            windShiverDirectionality = FindProperty(kWindShiverDirectionality, props, false);

            // Decal
            supportDecals = FindProperty(kSupportDecals, props, false);

            // specular AA
            enableGeometricSpecularAA = FindProperty(kEnableGeometricSpecularAA, props, false);
            specularAAScreenSpaceVariance = FindProperty(kSpecularAAScreenSpaceVariance, props, false);
            specularAAThreshold = FindProperty(kSpecularAAThreshold, props, false);

            // SSR
            receivesSSR = FindProperty(kReceivesSSR, props, false);
        }

        void TessellationModePopup()
        {
            EditorGUI.showMixedValue = tessellationMode.hasMixedValue;
            var mode = (TessellationMode)tessellationMode.floatValue;

            EditorGUI.BeginChangeCheck();
            mode = (TessellationMode)EditorGUILayout.Popup(StylesBaseLit.tessellationModeStr, (int)mode, StylesBaseLit.tessellationModeNames);
            if (EditorGUI.EndChangeCheck())
            {
                m_MaterialEditor.RegisterPropertyChangeUndo("Tessellation Mode");
                tessellationMode.floatValue = (float)mode;
            }

            EditorGUI.showMixedValue = false;
        }

        protected virtual void UpdateDisplacement() {}

        protected override void BaseMaterialPropertiesGUI()
        {
            base.BaseMaterialPropertiesGUI();

            // This follow double sided option
            if (doubleSidedEnable != null && doubleSidedEnable.floatValue > 0.0f)
            {
                EditorGUI.indentLevel++;
                m_MaterialEditor.ShaderProperty(doubleSidedNormalMode, StylesBaseLit.doubleSidedNormalModeText);
                EditorGUI.indentLevel--;
            }

            if (materialID != null)
            {
                m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText);

                if ((int)materialID.floatValue == (int)MaterialId.LitSSS)
                {
                    EditorGUI.indentLevel++;
                    m_MaterialEditor.ShaderProperty(transmissionEnable, StylesBaseLit.transmissionEnableText);
                    EditorGUI.indentLevel--;
                }
            }

            if (supportDecals != null)
            {
                m_MaterialEditor.ShaderProperty(supportDecals, StylesBaseLit.supportDecalsText);
            }

            if (receivesSSR != null)
            {
                m_MaterialEditor.ShaderProperty(receivesSSR, StylesBaseLit.receivesSSRText);
            }

            if (enableGeometricSpecularAA != null)
            {
                m_MaterialEditor.ShaderProperty(enableGeometricSpecularAA, StylesBaseLit.enableGeometricSpecularAAText);

                if (enableGeometricSpecularAA.floatValue > 0.0)
                {
                    EditorGUI.indentLevel++;
                    m_MaterialEditor.ShaderProperty(specularAAScreenSpaceVariance, StylesBaseLit.specularAAScreenSpaceVarianceText);
                    m_MaterialEditor.ShaderProperty(specularAAThreshold, StylesBaseLit.specularAAThresholdText);
                    EditorGUI.indentLevel--;
                }
            }

            if (displacementMode != null)
            {
                EditorGUI.BeginChangeCheck();
                FilterDisplacementMode();
                m_MaterialEditor.ShaderProperty(displacementMode, StylesBaseLit.displacementModeText);
                if (EditorGUI.EndChangeCheck())
                {
                    UpdateDisplacement();
                }

                if ((DisplacementMode)displacementMode.floatValue != DisplacementMode.None)
                {
                    EditorGUI.indentLevel++;
                    m_MaterialEditor.ShaderProperty(displacementLockObjectScale, StylesBaseLit.lockWithObjectScaleText);
                    m_MaterialEditor.ShaderProperty(displacementLockTilingScale, StylesBaseLit.lockWithTilingRateText);
                    EditorGUI.indentLevel--;
                }

                if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel)
                {
                    EditorGUILayout.Space();
                    EditorGUI.indentLevel++;
                    m_MaterialEditor.ShaderProperty(ppdMinSamples, StylesBaseLit.ppdMinSamplesText);
                    m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText);
                    ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue);
                    m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText);
                    m_MaterialEditor.ShaderProperty(ppdPrimitiveLength, StylesBaseLit.ppdPrimitiveLength);
                    ppdPrimitiveLength.floatValue = Mathf.Max(0.01f, ppdPrimitiveLength.floatValue);
                    m_MaterialEditor.ShaderProperty(ppdPrimitiveWidth, StylesBaseLit.ppdPrimitiveWidth);
                    ppdPrimitiveWidth.floatValue = Mathf.Max(0.01f, ppdPrimitiveWidth.floatValue);
                    invPrimScale.vectorValue = new Vector4(1.0f / ppdPrimitiveLength.floatValue, 1.0f / ppdPrimitiveWidth.floatValue); // Precompute
                    m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText);
                    EditorGUI.indentLevel--;
                }
            }
        }

        protected void FilterDisplacementMode()
        {
            if(tessellationMode == null)
            {
                if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Tessellation)
                    displacementMode.floatValue = (float)DisplacementMode.None;
            }
            else
            {
                if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel || (DisplacementMode)displacementMode.floatValue == DisplacementMode.Vertex)
                    displacementMode.floatValue = (float)DisplacementMode.None;
            }
        }

        private void DrawDelayedFloatProperty(MaterialProperty prop, GUIContent content)
        {
            Rect position = EditorGUILayout.GetControlRect();
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = prop.hasMixedValue;
            float newValue = EditorGUI.DelayedFloatField(position, content, prop.floatValue);
            EditorGUI.showMixedValue = false;
            if (EditorGUI.EndChangeCheck())
                prop.floatValue = newValue;
        }

        protected virtual void MaterialTesselationPropertiesGUI()
        {
            // Display tessellation option if it exist
            if (tessellationMode != null)
            {
                using (var header = new HeaderScope(StylesBaseLit.tessellationText.text, (uint)Expandable.Tesselation, this))
                {
                    if (header.expanded)
                    {
                        TessellationModePopup();
                        m_MaterialEditor.ShaderProperty(tessellationFactor, StylesBaseLit.tessellationFactorText);
                        DrawDelayedFloatProperty(tessellationFactorMinDistance, StylesBaseLit.tessellationFactorMinDistanceText);
                        DrawDelayedFloatProperty(tessellationFactorMaxDistance, StylesBaseLit.tessellationFactorMaxDistanceText);
                        // clamp min distance to be below max distance
                        tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue);
                        m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, StylesBaseLit.tessellationFactorTriangleSizeText);
                        if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong)
                        {
                            m_MaterialEditor.ShaderProperty(tessellationShapeFactor, StylesBaseLit.tessellationShapeFactorText);
                        }
                        if (doubleSidedEnable.floatValue == 0.0)
                        {
                            m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, StylesBaseLit.tessellationBackFaceCullEpsilonText);
                        }
                    }
                }
            }
        }

        //override for adding Tesselation
        public override void ShaderPropertiesGUI(Material material)
        {
            // Use default labelWidth
            EditorGUIUtility.labelWidth = 0f;

            // Detect any changes to the material
            EditorGUI.BeginChangeCheck();
            {
                using (var header = new HeaderScope(StylesBaseUnlit.optionText, (uint)Expandable.Base, this))
                {
                    if (header.expanded)
                        BaseMaterialPropertiesGUI();
                }
                MaterialTesselationPropertiesGUI();
                VertexAnimationPropertiesGUI();
                MaterialPropertiesGUI(material);
                using (var header = new HeaderScope(StylesBaseUnlit.advancedText, (uint)Expandable.Advance, this))
                {
                    if (header.expanded)
                    {
                        m_MaterialEditor.EnableInstancingField();
                        MaterialPropertiesAdvanceGUI(material);
                    }
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                foreach (var obj in m_MaterialEditor.targets)
                    SetupMaterialKeywordsAndPassInternal((Material)obj);
            }
        }

        protected override void VertexAnimationPropertiesGUI()
        {
            if (windEnable == null && enableMotionVectorForVertexAnimation == null)
                return;

            using (var header = new HeaderScope(StylesBaseLit.vertexAnimation, (uint)Expandable.VertexAnimation, this))
            {
                if (header.expanded)
                {
                    if (windEnable != null)
                    {
                        // Hide wind option. Wind is deprecated and will be remove in the future. Use shader graph instead
                        /*
                        m_MaterialEditor.ShaderProperty(windEnable, StylesBaseLit.windText);
                        if (!windEnable.hasMixedValue && windEnable.floatValue > 0.0f)
                        {
                            EditorGUI.indentLevel++;
                            m_MaterialEditor.ShaderProperty(windInitialBend, StylesBaseLit.windInitialBendText);
                            m_MaterialEditor.ShaderProperty(windStiffness, StylesBaseLit.windStiffnessText);
                            m_MaterialEditor.ShaderProperty(windDrag, StylesBaseLit.windDragText);
                            m_MaterialEditor.ShaderProperty(windShiverDrag, StylesBaseLit.windShiverDragText);
                            m_MaterialEditor.ShaderProperty(windShiverDirectionality, StylesBaseLit.windShiverDirectionalityText);
                            EditorGUI.indentLevel--;
                        }
                        */
                    }

                    if (enableMotionVectorForVertexAnimation != null)
                        m_MaterialEditor.ShaderProperty(enableMotionVectorForVertexAnimation, StylesBaseUnlit.enableMotionVectorForVertexAnimationText);
                }
            }
        }

        // All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
        static public void SetupBaseLitKeywords(Material material)
        {
            SetupBaseUnlitKeywords(material);

            bool doubleSidedEnable = material.HasProperty(kDoubleSidedEnable) ? material.GetFloat(kDoubleSidedEnable) > 0.0f : false;
            if (doubleSidedEnable)
            {
                DoubleSidedNormalMode doubleSidedNormalMode = (DoubleSidedNormalMode)material.GetFloat(kDoubleSidedNormalMode);
                switch (doubleSidedNormalMode)
                {
                    case DoubleSidedNormalMode.Mirror: // Mirror mode (in tangent space)
                        material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, -1.0f, 0.0f));
                        break;

                    case DoubleSidedNormalMode.Flip: // Flip mode (in tangent space)
                        material.SetVector("_DoubleSidedConstants", new Vector4(-1.0f, -1.0f, -1.0f, 0.0f));
                        break;

                    case DoubleSidedNormalMode.None: // None mode (in tangent space)
                        material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, 1.0f, 0.0f));
                        break;
                }
            }

            // Stencil usage rules:
            // DoesntReceiveSSR and DecalsForwardOutputNormalBuffer need to be tagged during depth prepass
            // LightingMask need to be tagged during either GBuffer or Forward pass
            // ObjectMotionVectors need to be tagged in velocity pass.
            // As motion vectors pass can be use as a replacement of depth prepass it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer
            // As GBuffer pass can have no depth prepass, it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer
            // Object motion vectors is always render after a full depth buffer (if there is no depth prepass for GBuffer all object motion vectors are render after GBuffer)
            // so we have a guarantee than when we write object motion vectors no other object will be draw on top (and so would have require to overwrite motion vectors).
            // Final combination is:
            // Prepass: DoesntReceiveSSR,  DecalsForwardOutputNormalBuffer
            // Motion vectors: DoesntReceiveSSR,  DecalsForwardOutputNormalBuffer, ObjectVelocity
            // GBuffer: LightingMask, DecalsForwardOutputNormalBuffer, ObjectVelocity
            // Forward: LightingMask

            int stencilRef = (int)StencilLightingUsage.RegularLighting; // Forward case
            int stencilWriteMask = (int)HDRenderPipeline.StencilBitMask.LightingMask;
            int stencilRefDepth = 0;
            int stencilWriteMaskDepth = 0;
            int stencilRefGBuffer = (int)StencilLightingUsage.RegularLighting;
            int stencilWriteMaskGBuffer = (int)HDRenderPipeline.StencilBitMask.LightingMask;
            int stencilRefMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors;
            int stencilWriteMaskMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors;

            if (material.HasProperty(kMaterialID) && (int)material.GetFloat(kMaterialID) == (int)MaterialId.LitSSS)
            {
                stencilRefGBuffer = stencilRef = (int)StencilLightingUsage.SplitLighting;
            }

            if (material.HasProperty(kReceivesSSR) && material.GetInt(kReceivesSSR) == 0)
            {
                stencilRefDepth |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR;
                stencilRefGBuffer |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR;
                stencilRefMV |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR;
            }

            stencilWriteMaskDepth |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer;
            stencilWriteMaskGBuffer |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer;
            stencilWriteMaskMV |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer;

            // As we tag both during motion vector pass and Gbuffer pass we need a separate state and we need to use the write mask
            material.SetInt(kStencilRef, stencilRef);
            material.SetInt(kStencilWriteMask, stencilWriteMask);
            material.SetInt(kStencilRefDepth, stencilRefDepth);
            material.SetInt(kStencilWriteMaskDepth, stencilWriteMaskDepth);
            material.SetInt(kStencilRefGBuffer, stencilRefGBuffer);
            material.SetInt(kStencilWriteMaskGBuffer, stencilWriteMaskGBuffer);
            material.SetInt(kStencilRefMV, stencilRefMV);
            material.SetInt(kStencilWriteMaskMV, stencilWriteMaskMV);
            material.SetInt(kStencilRefDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors);
            material.SetInt(kStencilWriteMaskDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors);

            if (material.HasProperty(kDisplacementMode))
            {
                bool enableDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) != DisplacementMode.None;
                bool enableVertexDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Vertex;
                bool enablePixelDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Pixel;
                bool enableTessellationDisplacement = ((DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Tessellation) && material.HasProperty(kTessellationMode);

                CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement);
                CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT", enablePixelDisplacement);
                // Only set if tessellation exist
                CoreUtils.SetKeyword(material, "_TESSELLATION_DISPLACEMENT", enableTessellationDisplacement);

                bool displacementLockObjectScale = material.GetFloat(kDisplacementLockObjectScale) > 0.0;
                bool displacementLockTilingScale = material.GetFloat(kDisplacementLockTilingScale) > 0.0;
                // Tessellation reuse vertex flag.
                CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && (enableVertexDisplacement || enableTessellationDisplacement));
                CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && enablePixelDisplacement);
                CoreUtils.SetKeyword(material, "_DISPLACEMENT_LOCK_TILING_SCALE", displacementLockTilingScale && enableDisplacement);

                // Depth offset is only enabled if per pixel displacement is
                bool depthOffsetEnable = (material.GetFloat(kDepthOffsetEnable) > 0.0f) && enablePixelDisplacement;
                CoreUtils.SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable);
            }

            bool windEnabled = material.HasProperty(kWindEnabled) && material.GetFloat(kWindEnabled) > 0.0f;
            CoreUtils.SetKeyword(material, "_VERTEX_WIND", windEnabled);

            if (material.HasProperty(kTessellationMode))
            {
                TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode);
                CoreUtils.SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong);
            }

            SetupMainTexForAlphaTestGI("_BaseColorMap", "_BaseColor", material);

            // Use negation so we don't create keyword by default
            CoreUtils.SetKeyword(material, "_DISABLE_DECALS", material.HasProperty(kSupportDecals) && material.GetFloat(kSupportDecals) == 0.0);
            CoreUtils.SetKeyword(material, "_DISABLE_SSR", material.HasProperty(kReceivesSSR) && material.GetFloat(kReceivesSSR) == 0.0);
            CoreUtils.SetKeyword(material, "_ENABLE_GEOMETRIC_SPECULAR_AA", material.HasProperty(kEnableGeometricSpecularAA) && material.GetFloat(kEnableGeometricSpecularAA) == 1.0);
        }

        static public void SetupBaseLitMaterialPass(Material material)
        {
            SetupBaseUnlitMaterialPass(material);
        }
    }
} // namespace UnityEditor

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Email;

use Nette\Application\UI\ITemplateFactory;
use Nette\Mail\IMailer;
use Nette\Object;

/**
 * Base class for emails.
 *
 * @author Tomáš Markacz <tomas@markacz.com>
 */
abstract class BaseEmail extends Object
{

	/** @var ITemplateFactory */
	protected $templateFactory;

	/** @var IMailer */
	protected $mailer;

	/**
	 * @param ITemplateFactory $templateFactory
	 * @param IMailer $mailer
	 */
	public function __construct(ITemplateFactory $templateFactory, IMailer $mailer)
	{
		$this->templateFactory = $templateFactory;
		$this->mailer          = $mailer;
	}

}


text:
<phpunit bootstrap="../vendor/autoload.php" colors="true">
    <testsuites>
        <testsuite name="Unit-Tests">
            <directory>./</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory>../src/Spl</directory>
        </whitelist>
    </filter>

    <logging>
        <log
            type="coverage-html"
            target="./coverage"
            charset="UTF-8"
            yui="true"
            lowUpperBound="35"
            highLowerBound="70"
            showUncoveredFiles="true"
        />
    </logging>
</phpunit>


text:
import com.azure.identity.DeviceCodeCredential;
import com.azure.identity.DeviceCodeCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.httpcore.HttpClients;
import okhttp3.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class DeviceCodeFlowMain {

    //Replace CLIENT_ID with your own client id from an app that is configured according to the requirements below
    //for requirements visit:
    //https://github.com/Azure/azure-sdk-for-java/wiki/Set-up-Your-Environment-for-Authentication#enable-applications-for-device-code-flow
    private final static String CLIENT_ID = "<your client/app id>";

    //Set the scopes for your ms-graph request
    private final static List<String> SCOPES = Arrays.asList("User.ReadBasic.All", "User.Read");

    public static void main(String[] args) throws Exception {
        final DeviceCodeCredential deviceCodeCred = new DeviceCodeCredentialBuilder()
                .clientId(CLIENT_ID)
                .challengeConsumer(challenge -> System.out.println(challenge.getMessage()))
                .build();

        final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, deviceCodeCred);
        final OkHttpClient httpClient = HttpClients.createDefault(tokenCredAuthProvider);

        final Request request = new Request.Builder().url("https://graph.microsoft.com/v1.0/me/").build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
        });
    }
}


text:
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using TerribleWebApi.Models;
using UnityEngine;
using UnityEngine.Assertions;

public class IntegrationTests : MonoBehaviour
{
    private const string BaseUrl = "http://turds.azurewebsites.net/api/";
    //private const string BaseUrl = "http://localhost:63752/api/";

    IEnumerator Start()
    {
        //return Get();
        return Post();
    }

    IEnumerator Get()
    {
        var www = new WWW(BaseUrl + "turd/1");
        yield return www;

        var turd = JsonConvert.DeserializeObject<Turd>(www.text);
        Assert.IsNotNull(turd);
    }

    IEnumerator Post()
    {
        var turd = new Turd
        {
            Id = 555,
            SmellCoefficient = 23525,
            NumberOfCornKernels = 222,
        };
        string json = JsonConvert.SerializeObject(turd);

        var www = new WWW(BaseUrl + "turd/" + turd.Id, Encoding.Default.GetBytes(json), new Dictionary<string, string>
        {
            { "Content-Type", "application/json" }
        });
        yield return www;

        Debug.Log("Error: " + www.error);
    }

    //For later, keep safe
    //void test()
    //{
    //    var www = new WWW(BaseUrl + "turd/1");

    //    using (var memory = new MemoryStream(www.bytes))
    //    using (var gzip = new GZipStream(memory, CompressionMode.Decompress))
    //    using (var reader = new StreamReader(gzip))
    //    {
    //        string json = reader.ReadToEnd();
    //    }
    //}
}


text:
require 'ovirtsdk4'
require 'yaml'

module ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Strategies
  class V4
    include Vmdb::Logging

    attr_reader :ext_management_system

    VERSION_HASH = {:version => 4}.freeze

    def initialize(args)
      @ext_management_system = args[:ems]
    end

    def username_by_href(href)
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        user = connection.system_service.users_service.user_service(uuid_from_href(href)).get
        "#{user.name}@#{user.domain.name}"
      end
    end

    def cluster_name_href(href)
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        cluster_proxy_from_href(href, connection).name
      end
    end

    # Provisioning
    def get_host_proxy(host, connection)
      connection.system_service.hosts_service.host_service(host.uid_ems)
    end

    def clone_completed?(args)
      source = args[:source]
      phase_context = args[:phase_context]
      logger = args[:logger]

      if source.template?
        vm_clone_completed?(logger, phase_context, source)
      else
        template_clone_completed?(logger, phase_context, source)
      end
    end

    def vm_clone_completed?(logger, phase_context, source)
      source.with_provider_connection(VERSION_HASH) do |connection|
        vm = vm_service_by_href(phase_context[:new_vm_ems_ref], connection).get
        status = vm.status
        logger.info("The Vm being cloned is #{status}")
        status == OvirtSDK4::VmStatus::DOWN
      end
    end

    def template_clone_completed?(logger, phase_context, source)
      source.with_provider_connection(VERSION_HASH) do |connection|
        template = template_service_by_href(phase_context[:new_vm_ems_ref], connection).get
        status = template.status
        logger.info("The status of the template being cloned is #{status}")
        status == OvirtSDK4::TemplateStatus::OK
      end
    end

    def destination_image_locked?(vm)
      vm.with_provider_object(VERSION_HASH) do |vm_proxy|
        vm_proxy.get.status == OvirtSDK4::VmStatus::IMAGE_LOCKED
      end
    end

    def exists_on_provider?(vm)
      vm.with_provider_object(VERSION_HASH) do |vm_proxy|
        vm_proxy.get
        true
      end
    rescue OvirtSDK4::Error
      false
    end

    def populate_phase_context(phase_context, vm)
      phase_context[:new_vm_ems_ref] = ManageIQ::Providers::Redhat::InfraManager.make_ems_ref(vm.href)
    end

    def nics_for_vm(vm)
      vm.with_provider_connection(VERSION_HASH) do |connection|
        vm_proxy = connection.system_service.vms_service.vm_service(vm.uid_ems).get
        connection.follow_link(vm_proxy.nics)
      end
    end

    def cluster_find_network_by_name(href, network_name)
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        cluster_service = connection.system_service.clusters_service.cluster_service(uuid_from_href(href))
        networks = cluster_service.networks_service.list
        networks.detect { |n| n.name == network_name }
      end
    end

    def configure_vnics(requested_vnics, destination_vnics, destination_cluster, destination_vm)
      destination_vm.with_provider_connection(VERSION_HASH) do |connection|
        nics_service = connection.system_service.vms_service.vm_service(destination_vm.uid_ems).nics_service

        requested_vnics.stretch!(destination_vnics).each_with_index do |requested_vnic, idx|
          if requested_vnic.nil?
            nics_service.nic_service(destination_vnics[idx].id).remove
          else
            configure_vnic_with_requested_data("nic#{idx + 1}", requested_vnic, destination_vnics[idx], nics_service, destination_cluster)
          end
        end
      end
    end

    def load_allowed_networks(_hosts, vlans, workflow)
      private_load_allowed_networks(vlans, VmOrTemplate.find(workflow.get_source_vm.id).ems_cluster.uid_ems)
    end

    def filter_allowed_hosts(_workflow, all_hosts)
      all_hosts
    end

    def powered_off_in_provider?(vm)
      vm.with_provider_object(VERSION_HASH) { |vm_service| vm_service.get.status } == OvirtSDK4::VmStatus::DOWN
    end

    def powered_on_in_provider?(vm)
      vm.with_provider_object(VERSION_HASH) { |vm_service| vm_service.get.status } == OvirtSDK4::VmStatus::UP
    end

    def vm_boot_from_cdrom(operation, name)
      operation.destination.with_provider_object(VERSION_HASH) do |vm_service|
        vm_service.start(
          :vm => {
            :os     => {
              :boot => {
                :devices => [OvirtSDK4::BootDevice::CDROM]
              }
            },
            :cdroms => [
              {
                :file => {
                  :id => name
                }
              }
            ]
          }
        )
      end
    rescue OvirtSDK4::Error
      raise ManageIQ::Providers::Redhat::InfraManager::OvirtServices::VmNotReadyToBoot
    end

    def detach_floppy(operation)
      operation.destination.with_provider_object(VERSION_HASH) do |vm_service|
        vm_service.update(:payloads => [])
      end
    end

    def vm_boot_from_network(operation)
      operation.destination.with_provider_object(VERSION_HASH) do |vm_service|
        vm_service.start(
          :vm => {
            :os => {
              :boot => {
                :devices => [
                  OvirtSDK4::BootDevice::NETWORK
                ]
              }
            }
          }
        )
      end
    rescue OvirtSDK4::Error
      raise ManageIQ::Providers::Redhat::InfraManager::OvirtServices::VmNotReadyToBoot
    end

    def remote_console_acquire_ticket(vm, userid, originating_server)
      ticket = nil
      rhevm_vm = nil
      vm.with_provider_object do |vm_service|
        ticket = vm_service.ticket
        rhevm_vm = vm_service.get
      end

      SystemConsole.force_vm_invalid_token(vm.id)
      console_args = {
        :user       => User.find_by(:userid => userid),
        :vm_id      => vm.id,
        :protocol   => rhevm_vm.display.type,
        :secret     => ticket.value,
        :url_secret => SecureRandom.hex,
        :ssl        => rhevm_vm.display.secure_port.present?
      }
      host_address = rhevm_vm.display.address
      host_port    = rhevm_vm.display.secure_port || rhevm_vm.display.port

      SystemConsole.launch_proxy_if_not_local(console_args, originating_server, host_address, host_port)
    end

    def get_template_proxy(template, connection)
      TemplateProxyDecorator.new(
        connection.system_service.templates_service.template_service(template.uid_ems),
        connection,
        self
      )
    end

    def get_vm_proxy(vm, connection)
      VmProxyDecorator.new(connection.system_service.vms_service.vm_service(vm.uid_ems), connection, self)
    end

    def collect_disks_by_hrefs(disks)
      vm_disks = []
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        disks.each do |disk|
          parts = URI(disk).path.split('/')
          begin
            vm_disks << connection.system_service.storage_domains_service.storage_domain_service(parts[2]).disks_service.disk_service(parts[4]).get
          rescue OvirtSDK4::Error
            nil
          end
        end
      end
      vm_disks
    end

    def shutdown_guest(operation)
      operation.with_provider_object(VERSION_HASH, &:shutdown)
    rescue OvirtSDK4::Error
    end

    def reboot_guest(operation)
      operation.with_provider_object(VERSION_HASH, &:reboot)
    rescue OvirtSDK4::Error
    end

    def start_clone(source, clone_options, phase_context)
      source.with_provider_object(VERSION_HASH) do |rhevm_template|
        vm = rhevm_template.create_vm(clone_options)
        populate_phase_context(phase_context, vm)
      end
    end

    def make_template(source, clone_options, phase_context)
      source.with_provider_object(VERSION_HASH) do |rhevm_vm|
        template = rhevm_vm.make_template(clone_options)
        populate_phase_context(phase_context, template)
      end
    end

    def vm_start(vm, opts = {})
      vm.with_provider_object(VERSION_HASH) do |rhevm_vm|
        rhevm_vm.start(opts)
      end
    rescue OvirtSDK4::Error
    end

    def vm_stop(vm)
      vm.with_provider_object(VERSION_HASH, &:stop)
    rescue OvirtSDK4::Error
    end

    def vm_suspend(vm)
      vm.with_provider_object(VERSION_HASH, &:suspend)
    end

    def vm_reconfigure(vm, options = {})
      log_header = "EMS: [#{ext_management_system.name}] #{vm.class.name}: id [#{vm.id}], name [#{vm.name}], ems_ref [#{vm.ems_ref}]"
      spec = options[:spec]

      _log.info("#{log_header} Started...")

      vm.with_provider_object(VERSION_HASH) do |vm_service|
        # Retrieve the current representation of the virtual machine:
        # TODO: no need to retreive vm here, only if memory is updated
        vm = vm_service.get

        # Update the memory:
        memory = spec['memoryMB']
        update_vm_memory(vm, vm_service, memory.megabytes) if memory

        # Update the CPU:
        cpu_total = spec['numCPUs']
        cpu_cores = spec['numCoresPerSocket']
        cpu_sockets = cpu_total / (cpu_cores || vm.cpu.topology.cores) if cpu_total
        if cpu_cores || cpu_sockets
          vm_service.update(
            OvirtSDK4::Vm.new(
              :cpu => {
                :topology => {
                  :cores   => cpu_cores,
                  :sockets => cpu_sockets
                }
              }
            )
          )
        end

        # Remove disks:
        removed_disk_specs = spec['disksRemove']
        remove_vm_disks(vm_service, removed_disk_specs) if removed_disk_specs

        # Add disks:
        added_disk_specs = spec['disksAdd']
        add_vm_disks(vm_service, added_disk_specs) if added_disk_specs
      end

      _log.info("#{log_header} Completed.")
    end

    def advertised_images
      ext_management_system.with_provider_connection(VERSION_HASH) do |ems_service|
        query = { :search => "status=#{OvirtSDK4::DataCenterStatus::UP}" }
        data_centers = ems_service.system_service.data_centers_service.list(:query => query)
        iso_sd = nil
        data_centers.each do |dc|
          iso_sd = ems_service.follow_link(dc.storage_domains).detect do |sd|
            sd.type == OvirtSDK4::StorageDomainType::ISO && sd.status == OvirtSDK4::StorageDomainStatus::ACTIVE
          end
          break iso_sd if iso_sd
        end
        return [] unless iso_sd
        sd_service = ems_service.system_service.storage_domains_service.storage_domain_service(iso_sd.id)
        iso_images = sd_service.files_service.list
        iso_images.collect(&:name)
      end
    rescue OvirtSDK4::Error => err
      name = ext_management_system.try(:name)
      _log.error("Error Getting ISO Images on ISO Datastore on Management System <#{name}>: #{err.class.name}: #{err}")
      raise ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Error, err
    end

    def host_activate(host)
      host.with_provider_object(&:activate)
    end

    def host_deactivate(host)
      host.with_provider_object(&:deactivate)
    end

    class VmProxyDecorator < SimpleDelegator
      attr_reader :ovirt_services, :connection

      def initialize(vm_service, connection, ovirt_services)
        @obj = vm_service
        @connection = connection
        @ovirt_services = ovirt_services
        super(vm_service)
      end

      def update_memory_reserve!(memory_reserve_size)
        vm = get
        vm.memory_policy.guaranteed = memory_reserve_size
        update(vm)
      end

      def update_description!(description)
        vm = get
        vm.description = description
        update(vm)
      end

      def update_memory!(memory, limit)
        vm = get
        vm.memory = memory unless memory.zero?
        vm.memory_policy.max = limit unless limit.zero?
        update(vm)
      end

      def update_host_affinity!(dest_host_ems_ref)
        vm = get
        vm.placement_policy.hosts = [OvirtSDK4::Host.new(:id => ovirt_services.uuid_from_href(dest_host_ems_ref))]
        update(vm)
      end

      def update_cpu_topology!(cpu_hash)
        vm = get
        vm.cpu.topology = OvirtSDK4::CpuTopology.new(cpu_hash)
        update(vm)
      end

      def attach_floppy(filename_hash)
        name, content = filename_hash.first
        file = OvirtSDK4::File.new(:name => name, :content => content)
        payload = OvirtSDK4::Payload.new(:files => [file], type: "floppy")
        vm = get
        vm.payloads ||= []
        vm.payloads << payload
        update(vm)
      end

      #
      # Updates the `initialization` of the virtual machine using the given custom script.
      #
      # @param content [String] YAML text containing the cloud-init configuration.
      #
      def update_cloud_init!(content)
        # Do nothing if the cloud-init configuration is empty or nil:
        return if content.blank?

        # When this was implemented using version 3 of the API some of the attributes of the
        # initialization object were directly copied from the YAML text, ignoring the syntax of the
        # cloud-init files. For example, we expected to have a YAML file like this:
        #
        #   host_name: myvm.example.com
        #   user_name: root
        #   root_password: mypass
        #   ...
        #
        # These are *not* part of the syntax supported by cloud-init, but just values that we used
        # to copy to the initialization object. To preserve backwards compatibility, and to support
        # the existing customization scripts, we need to use the same logic that the 'ovirt' gem
        # used to extract these values. For more details see 'cloud_init=' and
        # 'converted_cloud_init' methods in the 'vm.rb' file of the 'ovirt' gem.
        #
        # This is the list of keys that need special treatment:
        keys = %i(
          active_directory_ou
          authorized_ssh_keys
          dns_search
          dns_servers
          domain
          host_name
          input_locale
          nic_configurations
          org_name
          regenerate_ssh_keys
          root_password
          system_locale
          timezone
          ui_language
          user_locale
          user_name
        )

        # Load the YAML text and check it is a hash, as otherwise we will not be able to process it
        # and cloud-init will not understand it either.
        yaml = YAML.safe_load(content)
        unless yaml.kind_of?(Hash)
          message = \
            "The cloud-init configuration '#{content}' can't be parsed as hash;" \
            "cloud-init would not understand it"
          raise MiqException::MiqProvisionError, message
        end

        # Remove from the YAML the keys that need special treatment, and add them to the hash that
        # will be used to create the initialization object.
        hash = {}
        keys.each do |key|
          value = yaml.delete(key.to_s)
          hash[key] = value if value
        end

        # The SDK expects a hash where keys are symbols, but we may have strings inside nested
        # hashes, for example for NIC configurations, so we need to convert them to symbols:
        hash = hash.deep_symbolize_keys

        # Convert the remaining YAML back to text, removing the initial '---' line that the dump
        # method adds, as cloud-init does not understand it. The result will be used as the custom
        # cloud-init script.
        unless yaml.empty?
          script = YAML.dump(yaml)
          script.sub!(/^---\n/, '')
          hash[:custom_script] = script
        end

        # Send the update to the server:
        update(
          OvirtSDK4::Vm.new(
            :initialization => hash
          )
        )
      end

      def make_template(options)
        templates_service = connection.system_service.templates_service
        cluster = ovirt_services.cluster_from_href(options[:cluster], connection)
        if options[:storage]
          storage = ovirt_services.storage_from_href(options[:storage], connection)
        end
        vm = get
        vm.disk_attachments = connection.follow_link(vm.disk_attachments)
        template = build_template_from_hash(:name        => options[:name],
                                            :vm          => vm,
                                            :description => options[:description],
                                            :cluster     => cluster,
                                            :storage     => storage)
        templates_service.add(template, :seal => options[:seal])
      end

      def build_template_from_hash(args)
        options = {
          :name           => args[:name],
          :description    => args[:description],
          :vm             => args[:vm],
          :cluster        => args[:cluster],
          :storage_domain => args[:storage] && {:id => args[:storage].id}
        }.compact
        OvirtSDK4::Template.new(options)
      end

      def update_sysprep!(content)
        update(OvirtSDK4::Vm.new(
                 :initialization => {
                   :custom_script => content
                 }
        ))
      end

      def destroy
        remove
      end

      def unregister
        remove(:detach_only => true)
      end
    end

    class TemplateProxyDecorator < SimpleDelegator
      attr_reader :connection, :ovirt_services
      def initialize(template_service, connection, ovirt_services)
        @obj = template_service
        @connection = connection
        @ovirt_services = ovirt_services
        super(template_service)
      end

      def create_vm(options)
        vms_service = connection.system_service.vms_service
        cluster = ovirt_services.cluster_from_href(options[:cluster], connection)
        template = get
        clone = options[:clone_type] == :full
        disk_attachments = clone ? build_disk_attachments(template, options[:sparse], options[:storage], options[:name]) : nil
        vm = build_vm_from_hash(:name             => options[:name],
                                :template         => template,
                                :cluster          => cluster,
                                :disk_attachments => disk_attachments)
        vms_service.add(vm, :clone => clone)
      end

      def build_disk_attachments(template, sparse, storage_href, vm_name)
        disk_attachments = connection.follow_link(template.disk_attachments)
        apply_sparsity_on_disk_attachments(disk_attachments, sparse) unless sparse.nil?
        apply_storage_domain_on_disk_attachments(disk_attachments, storage_href) unless storage_href.nil?
        apply_name_on_disk_attachments(disk_attachments, vm_name)
        disk_attachments
      end

      def apply_name_on_disk_attachments(disk_attachments, vm_name)
        disk_attachments.each_with_index { |disk_attachment, index| disk_attachment.disk.name = "#{vm_name}_Disk#{index + 1}" }
      end

      def apply_storage_domain_on_disk_attachments(disk_attachments, storage_href)
        return if storage_href.nil?
        storage_domain = ovirt_services.storage_from_href(storage_href, connection)
        disk_attachments.each do |disk_attachment|
          disk_attachment.disk.storage_domains = [storage_domain]
        end
      end

      def apply_sparsity_on_disk_attachments(disk_attachments, sparse)
        return if sparse.nil?
        disk_attachments.each do |disk_attachment|
          disk_attachment.disk.sparse = sparse
        end
      end

      def build_vm_from_hash(args)
        vm_options = {
          :name             => args[:name],
          :template         => args[:template],
          :cluster          => args[:cluster],
          :disk_attachments => args[:disk_attachments]
        }.compact
        OvirtSDK4::Vm.new(vm_options)
      end
    end

    def cluster_from_href(href, connection)
      connection.system_service.clusters_service.cluster_service(uuid_from_href(href)).get
    end

    def storage_from_href(href, connection)
      connection.system_service.storage_domains_service.storage_domain_service(uuid_from_href(href)).get
    end

    def uuid_from_href(ems_ref)
      URI(ems_ref).path.split('/').last
    end

    def get_mac_address_of_nic_on_requested_vlan(args)
      vm = args[:destination]
      nics = nics_for_vm(vm)
      find_mac_address_on_network(nics, args[:value_of_vlan_option], vm.uid_ems)
    end

    def find_mac_address_on_network(nics, vnic_profile_id, uid_ems)
      vnic_profile_id = parse_vnic_profile_id(vnic_profile_id, uid_ems)
      nic = if vnic_profile_id == '<Empty>'
              nics.detect do |n|
                n.vnic_profile.nil?
              end
            elsif vnic_profile_id == '<Template>'
              nics.first
            else
              nics.detect do |n|
                n.vnic_profile.id == vnic_profile_id
              end
            end

      if nics.empty?
        _log.warn("Cannot find a MAC address, there are no NICs")
      elsif nic.nil?
        _log.warn("Cannot find a MAC address based on vnic_profile=#{vnic_profile_id}, there is no NIC with this profile")
      end

      nic && nic.mac && nic.mac.address
    end

    def event_fetcher
      ManageIQ::Providers::Redhat::InfraManager::EventFetcher.new(ext_management_system)
    end

    def collect_external_network_providers
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        connection.system_service.openstack_network_providers_service.list
      end
    end

    private

    #
    # Hot plug of virtual memory has to be done in quanta of this size. Actually this is configurable in the
    # engine, using the `HotPlugMemoryMultiplicationSizeMb` configuration parameter, but it is very unlikely
    # that it will change.
    #
    HOT_PLUG_DIMM_SIZE = 256.megabyte.freeze

    def cluster_proxy_from_href(href, connection)
      connection.system_service.clusters_service.cluster_service(uuid_from_href(href)).get
    end

    def vm_service_by_href(href, connection)
      vm_uuid = uuid_from_href(href)
      connection.system_service.vms_service.vm_service(vm_uuid)
    end

    def template_service_by_href(href, connection)
      template_uuid = uuid_from_href(href)
      connection.system_service.templates_service.template_service(template_uuid)
    end

    #
    # Updates the amount memory of a virtual machine.
    #
    # @param vm [OvirtSDK4::Vm] The current representation of the virtual machine.
    # @param vm_service [OvirtSDK4::VmService] The service that manages the virtual machine.
    # @param memory [Integer] The new amount of memory requested by the user.
    #
    def update_vm_memory(vm, vm_service, memory)
      # Calculate the adjusted virtual and guaranteed memory:
      virtual = calculate_adjusted_virtual_memory(vm, memory)
      guaranteed = calculate_adjusted_guaranteed_memory(vm, memory)

      # The required memory cannot exceed the max configured memory of the VM. Therefore, we'll increase the max
      # memory up to 1TB or to the required limit, to allow a successful update for the VM.
      # Once 'max' memory attribute will be introduced, this code should be replaced with the specified max memory.
      supports_max = ext_management_system.version_at_least?('4.1')
      max = calculate_max_memory(vm, memory) if supports_max

      # If the virtual machine is running we need to update first the configuration that will be used during the
      # next run, as the guaranteed memory can't be changed for the running virtual machine.
      if vm.status == OvirtSDK4::VmStatus::UP
        vm_service.update(
          OvirtSDK4::Vm.new(
            :memory        => virtual,
            :memory_policy => {
              :guaranteed => guaranteed,
              :max        => (max if supports_max)
            }.compact
          ),
          :next_run => true
        )
        vm_service.update(
          OvirtSDK4::Vm.new(
            :memory => virtual
          )
        )
      else
        vm_service.update(
          OvirtSDK4::Vm.new(
            :memory        => virtual,
            :memory_policy => {
              :guaranteed => guaranteed,
              :max        => (max if supports_max)
            }.compact
          )
        )
      end
    end

    #
    # Adjusts the new requested virtual memory of a virtual machine so that it satisfies the constraints imposed
    # by the engine.
    #
    # @param vm [OvirtSDK4::Vm] The current representation of the virtual machine.
    # @param memory [Integer] The new amount of memory requested by the user.
    # @return [Integer] The amount of memory requested by the user adjusted so that it satisfies the constrains
    #   imposed by the engine.
    #
    def calculate_adjusted_virtual_memory(vm, memory)
      # Initially there is no need for adjustment:
      adjusted = memory

      # If the virtual machine is running then the difference in memory has to be a multiple of 256 MiB, otherwise
      # the engine will not perform the hot plug of the new memory. The reason for this is that hot plugging of
      # memory is performed adding a new virtual DIMM to the virtual machine, and the size of the virtual DIMM
      # is 256 MiB. This means that we need to round the difference up to the closest multiple of 256 MiB.
      if vm.status == OvirtSDK4::VmStatus::UP
        delta = memory - vm.memory
        remainder = delta % HOT_PLUG_DIMM_SIZE
        if remainder > 0
          adjustment = HOT_PLUG_DIMM_SIZE - remainder
          adjusted = memory + adjustment
          _log.info(
            "The change in virtual memory of virtual machine '#{vm.name}' needs to be a multiple of " \
            "#{HOT_PLUG_DIMM_SIZE / 1.megabyte} MiB, so it will be adjusted to #{adjusted / 1.megabyte} MiB."
          )
        end
      end

      # Return the adjusted memory:
      adjusted
    end

    #
    # Adjusts the guaranteed memory of a virtual machine so that it satisfies the constraints imposed by the
    # engine.
    #
    # @param vm [OvirtSDK4::Vm] The current representation of the virtual machine.
    # @param memory [Integer] The new amount of memory requested by the user (and maybe already adjusted).
    # @return [Integer] The amount of guaranteed memory to request so that it satisfies the constraints imposed by
    #   the engine.
    #
    def calculate_adjusted_guaranteed_memory(vm, memory)
      # Get the current amount of guaranteed memory:
      current = vm.memory_policy.guaranteed

      # Initially there is no need for adjustment:
      adjusted = current

      # The engine requires that the virtual memory is bigger or equal than the guaranteed memory at any given
      # time. Therefore, we need to adjust the guaranteed memory so that it is the minimum of the previous
      # guaranteed memory and the new virtual memory.
      if current > memory
        adjusted = memory
        _log.info(
          "The guaranteed physical memory of virtual machine '#{vm.name}' needs to be less or equal than the " \
          "virtual memory, so it will be adjusted to #{adjusted / 1.megabyte} MiB."
        )
      end

      # Return the adjusted guaranteed memory:
      adjusted
    end

    #
    # Adjusts the max memory of a virtual machine so that it satisfies the constraints imposed by the
    # engine. The max memory is supported since version 4.1 and limited to 1TB according to the UI limits
    # defined for ovirt provider.
    #
    # @param vm [OvirtSDK4::Vm] The current representation of the virtual machine.
    # @param memory [Integer] The new amount of memory requested by the user.
    # @return [Integer] The amount of max memory to request so that it satisfies the constraints imposed by
    #   the engine.
    #
    def calculate_max_memory(vm, memory)
      max = vm.memory_policy&.max || memory
      if memory >= 1.terabyte
        max = memory
      else
        max = [memory * 4, 1.terabyte].min if memory > max
      end

      max
    end

    #
    # Adds disks to a virtual machine.
    #
    # @param vm_service [OvirtSDK4::VmsService] The service that manages the virtual machine.
    # @param disk_specs [Hash] The specification of the disks to add.
    #
    def add_vm_disks(vm_service, disk_specs)
      storage_spec = disk_specs[:storage]
      attachments_service = vm_service.disk_attachments_service
      disk_specs[:disks].each do |disk_spec|
        attachment = prepare_vm_disk_attachment(disk_spec, storage_spec)
        attachments_service.add(attachment)
      end
    end

    #
    # Prepares a disk attachment for adding a new disk to a virtual machine.
    #
    # @param disk_spec [Hash] The specification of the disk to add.
    # @param storage_spec [Hash] The specification of the storage to use.
    #
    def prepare_vm_disk_attachment(disk_spec, storage_spec)
      disk_spec = disk_spec.symbolize_keys
      attachment_builder = ManageIQ::Providers::Redhat::InfraManager::DiskAttachmentBuilder.new(
        :size_in_mb       => disk_spec[:disk_size_in_mb],
        :storage          => storage_spec,
        :name             => disk_spec[:disk_name],
        :thin_provisioned => disk_spec[:thin_provisioned],
        :bootable         => disk_spec[:bootable],
      )
      attachment_builder.disk_attachment
    end

    #
    # Removes disks from a virtual machine.
    #
    # @param vm_service [OvirtSDK4::VmsService] The service that manages the virtual machine.
    # @param disk_specs [Array<Hash>] The specifications of the disks to remove.
    #
    # TODO: Note that disk_spec['disk_name'] is actually the disks id not its name.
    # we should change that because it is very confusing.
    def remove_vm_disks(vm_service, disk_specs)
      attachments_service = vm_service.disk_attachments_service
      disk_specs.each do |disk_spec|
        begin
          disk_spec = disk_spec.with_indifferent_access
          attachment_service = attachments_service.attachment_service(disk_spec['disk_name'])
          attachment_service.remove(:detach_only => !disk_spec['delete_backing'])
        rescue OvirtSDK4::NotFoundError
          raise "no disk with the id #{disk_spec['disk_name']} is attached to the vm: #{vm_service.get.name}"
        rescue OvirtSDK4::Error
          raise "Failed to detach disk with the id #{disk_spec['disk_name']} from the vm: #{vm_service.get.name}, check that it exists"
        end
      end
    end

    def configure_vnic_with_requested_data(name, requested_vnic, destination_vnic, nics_service, destination_cluster)
      requested_profile_id = parse_vnic_profile_id(requested_vnic[:network], destination_cluster.uid_ems)
      if requested_profile_id == '<Empty>'
        profile_id = nil
      else
        vnic_profile = find_vnic_profile_in_cluster(requested_profile_id, destination_cluster.uid_ems)
        if vnic_profile.nil?
          raise MiqException::MiqProvisionError, "Unable to find specified profile: <#{requested_profile_id}>"
        else
          profile_id = vnic_profile[0].id
        end
      end

      configure_vnic(
        :mac_addr     => requested_vnic[:mac_address],
        :vnic_profile => profile_id,
        :nic_name     => name,
        :interface    => requested_vnic[:interface],
        :vnic         => destination_vnic,
        :nics_service => nics_service,
        :logger       => _log
      )
    end

    def private_load_allowed_networks(vlans, uid_ems_cluster)
      profiles = get_vnic_profiles_in_cluster(uid_ems_cluster)
      profiles.each do |profile, profile_network|
        vlans[profile.id] = "#{profile.name} (#{profile_network.name})"
      end

      vlans['<Empty>'] = _('<No Profile>')
      vlans['<Template>'] = _('<Use template nics>')
    end

    def parse_vnic_profile_id(requested_profile, uid_ems_cluster)
      if requested_profile.include?('(')
        vlans = {}
        private_load_allowed_networks(vlans, uid_ems_cluster)
        matches = vlans.select { |_profile_id, profile_description| profile_description == requested_profile }
        return matches.keys[0] unless matches.empty?
      end

      requested_profile
    end

    def configure_vnic(args)
      mac_addr = args[:mac_addr]
      vnic = args[:vnic]

      profile_id = args[:vnic_profile]
      nics_service = args[:nics_service]
      options = {
        :name         => args[:nic_name],
        :interface    => args[:interface],
        :mac          => mac_addr ? OvirtSDK4::Mac.new(:address => mac_addr) : nil,
        :vnic_profile => {:id => profile_id}
      }.delete_blanks
      args[:logger].info("with options: <#{options.inspect}>")
      if vnic
        nics_service.nic_service(vnic.id).update(options)
      else
        nics_service.add(OvirtSDK4::Nic.new(options))
      end
    end

    def get_vnic_profiles_in_cluster(uid_ems_cluster)
      cluster_profiles = {}
      ext_management_system.with_provider_connection(VERSION_HASH) do |connection|
        profiles = connection.system_service.vnic_profiles_service.list

        cluster_networks = connection.system_service.clusters_service.cluster_service(uid_ems_cluster).networks_service.list

        profiles.each do |p|
          profile_network = cluster_networks.detect { |n| n.id == p.network.id }
          if profile_network
            cluster_profiles[p] = profile_network
          end
        end
      end
      cluster_profiles
    end

    def find_vnic_profile_in_cluster(profile_id, uid_ems_cluster)
      profiles = get_vnic_profiles_in_cluster(uid_ems_cluster)
      profiles.detect { |profile, _profile_network| profile.id == profile_id }
    end
  end
end


text:
package org.jfree.chart.renderer;

import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.plot.PlotRenderingInfo;

/**
 * Represents the current state of a renderer.
 */
public class RendererState {

    /** The plot rendering info. */
    private PlotRenderingInfo info;

    /**
     * Creates a new state object.
     *
     * @param info  the plot rendering info.
     */
    public RendererState(PlotRenderingInfo info) {
        this.info = info;
    }

    /**
     * Returns the plot rendering info.
     *
     * @return The info.
     */
    public PlotRenderingInfo getInfo() {
        return this.info;
    }

    /**
     * A convenience method that returns a reference to the entity
     * collection (may be null) being used to record
     * chart entities.
     *
     * @return The entity collection (possibly null).
     */
    public EntityCollection getEntityCollection() {
        EntityCollection result = null;
        if (this.info != null) {
            ChartRenderingInfo owner = this.info.getOwner();
            if (owner != null) {
                result = owner.getEntityCollection();
            }
        }
        return result;
    }

}


text:
module Meters
  class DccWithdrawTrustedConsents
    attr_reader :errors

    def initialize(meters, n3rgy_api_factory = Amr::N3rgyApiFactory.new)
      @meters = meters
      @n3rgy_api_factory = n3rgy_api_factory
      @errors = []
    end

    def perform
      @meters.each do |meter|
        begin
          meter.update(consent_granted: false)
          @n3rgy_api_factory.consent_api(meter).withdraw_trusted_consent(meter.mpan_mprn)
        rescue => e
          @errors << e
          Rails.logger.error("#{e.message} for mpxn #{meter.mpan_mprn}, school #{meter.school.name}")
          Rollbar.error(e, job: :dcc_withdraw_trusted_consents, mpxn: meter.mpan_mprn, school_name: meter.school.name)
        end
      end
      return errors.empty?
    end
  end
end


text:
package org.wso2.carbon.tryit;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.http.protocol.HTTP;
import org.wso2.carbon.core.transports.CarbonHttpRequest;
import org.wso2.carbon.core.transports.CarbonHttpResponse;
import org.wso2.carbon.core.transports.HttpGetRequestProcessor;
import org.wso2.carbon.tryit.wadl.generator.WADLReader;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.wsdl2form.WSDL2FormGenerator;

import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;
import java.net.URLEncoder;

public class WADLTryItRequestProcessor implements HttpGetRequestProcessor {
    @Override
    public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configurationContext) throws Exception {
        OutputStream outputStream = response.getOutputStream();
        response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
        response.addHeader("Access-Control-Allow-Origin", "*");

        Result result = new StreamResult(outputStream);
        String url = request.getParameter("resourceurl");
        url = URLEncoder.encode(url.toString(), "UTF-8");
        String contextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");

        outputStream.write(("<meta content=\"text/html;charset=utf-8\" http-equiv=\"Content-Type\">\n" +
                "<meta content=\"utf-8\" http-equiv=\"encoding\">").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("").getBytes());
        outputStream.write(("<link rel='stylesheet' type='text/css' href='?wadl2form&contentType=text/css&resource=css/screen.css'/>").getBytes());

        outputStream
                .write(("\n" +
                        "\n" +
                        "\n" +
                        "\n" +
                        "
Please wait while loading try it page....
\n" +
                        "\n").getBytes());
        outputStream.write(("<input type='hidden' name='contextRoot_name' id='contextRoot' value='"+contextRoot+"'>").getBytes());
        outputStream.flush();

    }
}


text:
var inspector = require('../');

// Custom type schema
var customValidation = {
	validDate: function (schema, date) {
      if (schema.$validDate === true
         && Object.prototype.toString.call(date) === "[object Date]"
         && isNaN(date.getTime())) {
          this.report('must be a valid date');
      }
  }
};
inspector.Validation.extend(customValidation);

var data = {
	validDate: new Date(),
	invalidDate: new Date('invalid'),
	noDate: 'hello!'
};
var schema = {
	type: 'object',
	items: {
		type: 'date',
		$validDate: true
	}
};

var result = inspector.validate(schema, data);
console.log(result.format());
/*
Property @[invalidDate]: must be a valid date
Property @[noDate]: must be date, but is string
*/


text:
tinyjs
======

Simple javascript mvc framework


text:
namespace Qart.Testing
{
    public interface IItemProvider
    {
        bool TryGetItem<T>(string itemKey, out T item) where T : class;
    }
}


text:
package org.springframework.cloud.contract.verifier.builder;

import org.springframework.cloud.contract.verifier.config.TestFramework;
import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;

class SpockMockMvcRequestGiven implements Given, MockMvcAcceptor {

	private final BlockBuilder blockBuilder;

	private final GeneratedClassMetaData generatedClassMetaData;

	SpockMockMvcRequestGiven(BlockBuilder blockBuilder, GeneratedClassMetaData metaData) {
		this.blockBuilder = blockBuilder;
		this.generatedClassMetaData = metaData;
	}

	@Override
	public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
		this.blockBuilder.addIndented("def request = given()");
		return this;
	}

	@Override
	public boolean accept(SingleContractMetadata metadata) {
		return acceptType(this.generatedClassMetaData, metadata)
				&& this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.SPOCK;
	}

}


text:
goog.provide('shaka.util.FakeEvent');

goog.require('goog.asserts');

/**
 * @summary Create an Event work-alike object based on the provided dictionary.
 * The event should contain all of the same properties from the dict.
 *
 * @extends {Event}
 * @export
 */
shaka.util.FakeEvent = class {
  /**
   * @param {!Event} event
   * @return {!shaka.util.FakeEvent}
   */
  static fromRealEvent(event) {
    const fakeEvent = new shaka.util.FakeEvent(event.type);
    for (const key in event) {
      Object.defineProperty(fakeEvent, key, {
        value: event[key],
        writable: true,
        enumerable: true,
      });
    }
    return fakeEvent;
  }

  /**
   * Allows us to tell the compiler that the dictionary "map" is actually a
   * generic object, for backwards compatibility.
   * @param {!Map.<string, Object>} dict
   * @return {!Object}
   * @suppress {invalidCasts}
   * @private
   */
  static recastDictAsObject_(dict) {
    goog.asserts.assert(!(dict instanceof Map), 'dict should not be a map');
    return /** @type {!Object} */ (dict);
  }

  /**
   * @param {string} type
   * @param {Map.<string, Object>=} dict
   */
  constructor(type, dict) {
    if (dict) {
      if (dict instanceof Map) {
        // Take properties from dict if present.
        for (const key of dict.keys()) {
          Object.defineProperty(this, key, {
            value: dict.get(key),
            writable: true,
            enumerable: true,
          });
        }
      } else {
        // For backwards compatibility with external apps that may make use of
        // this public constructor, this should still accept generic objects.
        const obj = shaka.util.FakeEvent.recastDictAsObject_(dict);
        for (const key in obj) {
          Object.defineProperty(this, key, {
            value: obj[key],
            writable: true,
            enumerable: true,
          });
        }
      }
    }

    // The properties below cannot be set by the dict.  They are all provided
    // for compatibility with native events.

    /** @const {boolean} */
    this.bubbles = false;

    /** @type {boolean} */
    this.cancelable = false;

    /** @type {boolean} */
    this.defaultPrevented = false;

    /**
     * According to MDN, Chrome uses high-res timers instead of epoch time.
     * Follow suit so that timeStamps on FakeEvents use the same base as
     * on native Events.
     * @const {number}
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/timeStamp
     */
    this.timeStamp = window.performance && window.performance.now ?
        window.performance.now() : Date.now();

    /** @const {string} */
    this.type = type;

    /** @const {boolean} */
    this.isTrusted = false;

    /** @type {EventTarget} */
    this.currentTarget = null;

    /** @type {EventTarget} */
    this.target = null;

    /**
     * Non-standard property read by FakeEventTarget to stop processing
     * listeners.
     * @type {boolean}
     */
    this.stopped = false;
  }

  /**
   * Prevents the default action of the event.  Has no effect if the event isn't
   * cancellable.
   * @override
   */
  preventDefault() {
    if (this.cancelable) {
      this.defaultPrevented = true;
    }
  }

  /**
   * Stops processing event listeners for this event.  Provided for
   * compatibility with native Events.
   * @override
   */
  stopImmediatePropagation() {
    this.stopped = true;
  }

  /**
   * Does nothing, since FakeEvents do not bubble.  Provided for compatibility
   * with native Events.
   * @override
   */
  stopPropagation() {}
};


text:
package com.eharmony.aloha.semantics.compiled

package object compiler {
    private[compiler] implicit class BooleanWrapper(val b: Boolean) extends AnyVal {
        def or(s: => String) = (if (b) Right(b) else Left(new IllegalArgumentException(s))).right
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>My New Hugo Site</title>
  <meta name="author" content="">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" href="/favicon.png" />
  <link rel="apple-touch-icon-precomposed" href="/apple-touch-icon.png" />

  <link rel="stylesheet" href="/style.css" />

My New Hugo Site

404 Not Found

Sorry, but we couldn't find the page you're looking for.

Please head back home.


text:
package org.apache.jackrabbit.core.query;

import static org.apache.jackrabbit.JcrConstants.*;
import javax.jcr.Node;
import javax.jcr.RepositoryException;

public class DescendantSelfAxisTest extends AbstractQueryTest {

    /**
     * JCR-3407 CaseTermQuery #rewrite behavior changes
     */
    public void testCaseTermQueryNPE() throws RepositoryException {
        String xpathNPE = "//element(*,nt:unstructured)[fn:lower-case(@jcr:language)='en']//element(*,nt:unstructured)[@jcr:message]/(@jcr:key|@jcr:message)";
        executeXPathQuery(xpathNPE, new Node[] {});
    }

    /**
     * JCR-3401 Wrong results when querying with a DescendantSelfAxisQuery
     */
    public void testNodeName() throws RepositoryException {
        String name = "testNodeName" + System.currentTimeMillis();

        Node foo = testRootNode.addNode("foo", NT_UNSTRUCTURED);
        foo.addNode("branch1", NT_FOLDER).addNode(name, NT_FOLDER);
        foo.addNode("branch2", NT_FOLDER).addNode(name, NT_FOLDER);
        Node bar = testRootNode.addNode(name, NT_UNSTRUCTURED);

        testRootNode.getSession().save();

        executeXPathQuery("//element(*, nt:unstructured)[fn:name() = '" + name
                + "']", new Node[] { bar });
        executeXPathQuery("//element(" + name + ", nt:unstructured)",
                new Node[] { bar });
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.fop.pdf.PDFCIDFont (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.fop.pdf.PDFCIDFont

Packages that use PDFCIDFont

org.apache.fop.pdf
Classes for handling the low-level creation of PDF documents.

Uses of PDFCIDFont in org.apache.fop.pdf

Methods in org.apache.fop.pdf with parameters of type PDFCIDFont

 void
PDFFontType0.setDescendantFonts(PDFCIDFont descendantFonts)

          Set the descendant font

Constructors in org.apache.fop.pdf with parameters of type PDFCIDFont

PDFFontType0(java.lang.String fontname,
             java.lang.String basefont,
             java.lang.Object encoding,
             PDFCIDFont descendantFonts)

          Create the /Font object

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.


text:
from .csv import CsvFormatter
from .json import JsonFormatter
from .humanable import HumanableFormatter

__all__ = ('CsvFormatter', 'JsonFormatter', 'HumanableFormatter')


text:
eShopOnContainers is a sample application written in C# running on .NET Core using a microservice architecture, Domain Driven Design.

> .NET Core reference application, powered by Microsoft, based on a simplified microservices architecture and Docker containers.

> This reference application is cross-platform at the server and client side, thanks to .NET Core services capable of running on Linux or Windows containers depending on your Docker host, and to Xamarin for mobile apps running on Android, iOS or Windows/UWP plus any browser for the client web apps.

> The architecture proposes a microservice oriented architecture implementation with multiple autonomous microservices (each one owning its own data/db) and implementing different approaches within each microservice (simple CRUD vs. DDD/CQRS patterns) using Http as the communication protocol between the client apps and the microservices and supports asynchronous communication for data updates propagation across multiple services based on Integration Events and an Event Bus (a light message broker, to choose between RabbitMQ or Azure Service Bus, underneath) plus other features defined at the roadmap.

## eShopOnContainers with CAP

你可以在下面的地址看到如何在 eShopOnContainers 中使用 CAP。

https://github.com/yang-xiaodong/eShopOnContainers


text:
package store_instructions

import (
	"github.com/Frederick-S/jvmgo/instructions/base_instructions"
	"github.com/Frederick-S/jvmgo/runtime_data_area"
)

// astore_2
// Store reference into local variable
type AStore2 struct {
	base_instructions.NoOperandsInstruction
}

func (aStore2 *AStore2) Execute(frame *runtime_data_area.Frame) {
	popReferenceValueAndStore(frame, 2)
}


text:
module Azure::Compute::Mgmt::V2019_12_01
  module Models
    #
    # Describes the parameters of a ScaleSet managed disk.
    #
    class VirtualMachineScaleSetManagedDiskParameters

      include MsRestAzure

      # @return [StorageAccountTypes] Specifies the storage account type for
      # the managed disk. Managed OS disk storage account type can only be set
      # when you create the scale set. NOTE: UltraSSD_LRS can only be used with
      # data disks, it cannot be used with OS Disk. Possible values include:
      # 'Standard_LRS', 'Premium_LRS', 'StandardSSD_LRS', 'UltraSSD_LRS'
      attr_accessor :storage_account_type

      # @return [DiskEncryptionSetParameters] Specifies the customer managed
      # disk encryption set resource id for the managed disk.
      attr_accessor :disk_encryption_set

      #
      # Mapper for VirtualMachineScaleSetManagedDiskParameters class as Ruby
      # Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'VirtualMachineScaleSetManagedDiskParameters',
          type: {
            name: 'Composite',
            class_name: 'VirtualMachineScaleSetManagedDiskParameters',
            model_properties: {
              storage_account_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'storageAccountType',
                type: {
                  name: 'String'
                }
              },
              disk_encryption_set: {
                client_side_validation: true,
                required: false,
                serialized_name: 'diskEncryptionSet',
                type: {
                  name: 'Composite',
                  class_name: 'DiskEncryptionSetParameters'
                }
              }
            }
          }
        }
      end
    end
  end
end