text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gum.DataTypes;
using Gum.DataTypes.Variables;
using RenderingLibrary.Graphics;

using Microsoft.Xna.Framework;
using Gum.Wireframe;
using Gum.RenderingLibrary;

#if GUM
using System.Windows.Documents;
using Gum.Plugins;
using Gum.PropertyGridHelpers.Converters;
#endif

namespace Gum.Managers
{
    #region Enums

    public enum TextureAddress
    {
        EntireTexture,
        Custom,
        DimensionsBased
    }

    public enum ChildrenLayout
    {
        Regular,
        TopToBottomStack,
        LeftToRightStack

    }

    #endregion

    public class StandardElementsManager
    {
        #region Enums

        public enum DimensionVariableAction
        {
            ExcludeFileOptions,
            AllowFileOptions,
            DefaultToPercentageOfFile
        }

        #endregion

        #region Fields

        Dictionary<string, StateSave> mDefaults;

        static StandardElementsManager mSelf;

        #endregion

        #region Properties

        public IEnumerable<string> DefaultTypes
        {
            get
            {
                foreach (var kvp in mDefaults)
                {
                    yield return kvp.Key;
                }
            }
        }

        public static StandardElementsManager Self
        {
            get
            {
                if (mSelf == null)
                {
                    mSelf = new StandardElementsManager();
                }
                return mSelf;
            }
        }

        public string DefaultType
        {
            get
            {
                return "Container";
            }
        }

        public Dictionary<string, StateSave> DefaultStates => mDefaults;

        #endregion

        public void Initialize()
        {
            RefreshDefaults();
        }

        public void RefreshDefaults()
        {
            mDefaults = new Dictionary<string, StateSave>();

            // Eventually this would get read from somewhere like an XML file
            // or a CSV file, but for
            // now we'll just use hard values.

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                     Text                                                           //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave, includeBaseline: true);

                AddDimensionsVariables(stateSave, 100, 50, DimensionVariableAction.ExcludeFileOptions);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = "Hello", Name = "Text", Category = "Text" });

                // Okay so here's some info on this value.
                // It would be nice to be able to select whether
                // a Text should or should not be localized in Gum.
                // The problem is that when we do the localization, we
                // only have access to the GraphicalUiElement, not the InstanceSave.
                // Sure, we could get the reference, but what about at runtime in a game?
                // We ultimately want this value to be saved in the GraphicalUiElement so it
                // can be applied at runtime too. This is a pain to do, since it would require
                // changes to SkiaGum and possibly to FRB plugins. It's a bigger project, so until
                // then, we'll leave this out and put it back in when it's time.
                //stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Apply Localization", Category = "Text" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "HorizontalAlignment", Value = HorizontalAlignment.Left, Name = "HorizontalAlignment", Category = "Text" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "VerticalAlignment", Value = VerticalAlignment.Top, Name = "VerticalAlignment", Category = "Text" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int?", Value = null, Name = "MaxLettersToShow", Category = "Text" });

                // font:
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Name = "UseCustomFont", Category = "Font" });

                var fontVariable = new VariableSave { SetsValue = true, Type = "string", Value = "Arial", Name = "Font", IsFont = true, Category = "Font" };
                fontVariable.PropertiesToSetOnDisplayer["IsEditable"] = true;
                stateSave.Variables.Add(fontVariable);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 18, Name = "FontSize", Category = "Font" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "OutlineThickness", Category = "Font" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Name = "IsItalic", Category = "Font" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Name = "IsBold", Category = "Font" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "UseFontSmoothing", Category = "Font" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = "", Name = "CustomFontFile", Category = "Font", IsFile = true });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 1.0f, Name = "Font Scale", Category = "Font" });

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                AddVariableReferenceList(stateSave);

                AddColorVariables(stateSave, includeAlpha: true);

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("Text", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                     Sprite                                                         //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";
                AddPositioningVariables(stateSave);
                AddDimensionsVariables(stateSave, 100, 100, DimensionVariableAction.DefaultToPercentageOfFile);
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = "", Name = "SourceFile", IsFile = true });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Category = "Animation", Name = "Animate" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = null, Category = "Animation", Name = "CurrentChainName" });

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Category = "Flip and Rotation", Name = "FlipHorizontal" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Category = "Flip and Rotation", Name = "FlipVertical" });

                //stateSave.Variables.Add(new VariableSave { Type = "bool", Value = false, Name = "Custom Texture Coordinates", Category="Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "TextureAddress", Value = Gum.Managers.TextureAddress.EntireTexture, Name = "Texture Address", Category = "Source" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Left", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Top", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Width", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Height", Category = "Source" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 0.0f, Name = "Texture Width Scale", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 0.0f, Name = "Texture Height Scale", Category = "Source" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Name = "Wrap", Category = "Source" });

                AddColorVariables(stateSave);

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                AddVariableReferenceList(stateSave);

                List<string> list = new List<string>();
                stateSave.VariableLists.Add(new VariableListSave<string> { Type = "string", Value = list, Category = "Animation", Name = "AnimationFrames" });

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("Sprite", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                   Container                                                        //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave);

                AddDimensionsVariables(stateSave, 150, 150, DimensionVariableAction.ExcludeFileOptions);

                stateSave.Variables.Add(new VariableSave
                {
                    SetsValue = true,
                    Category = "Children",
                    Type = "string",
                    Value = null,
                    Name = "Contained Type"
#if GUM
                    ,
                    CustomTypeConverter = new AvailableContainedTypeConverter()
#endif
                });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Category = "Children", Type = "ChildrenLayout", Value = ChildrenLayout.Regular, Name = "Children Layout" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Category = "Children", Type = "float", Value = 0.0f, Name = "StackSpacing" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Category = "Children", Type = "bool", Value = false, Name = "Wraps Children" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Category = "Children", Type = "bool", Value = false, Name = "Clips Children" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = false, Category = "Flip and Rotation", Name = "FlipHorizontal" });

                AddVariableReferenceList(stateSave);

                AddEventVariables(stateSave, defaultHasEvents: true);

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("Container", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                               ColoredRectangle                                                     //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave);

                AddDimensionsVariables(stateSave, 50, 50, DimensionVariableAction.ExcludeFileOptions);

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });
                AddColorVariables(stateSave, true);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "Blend", Value = Blend.Normal, Name = "Blend", Category = "Rendering" });

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                ApplySortValuesFromOrderInState(stateSave);

                AddVariableReferenceList(stateSave);

                mDefaults.Add("ColoredRectangle", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                               Circle                                                               //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 16.0f, Name = "Radius" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 16.0f, Name = "Width", IsHiddenInPropertyGrid = true });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 16.0f, Name = "Height", IsHiddenInPropertyGrid = true });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });
                AddColorVariables(stateSave, true);

                // Although rotating a circle about its center does nothing we add rotation because you can rotate it about a different origin
                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                ApplySortValuesFromOrderInState(stateSave);

                AddVariableReferenceList(stateSave);

                mDefaults.Add("Circle", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                               Rectangle                                                            //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave);

                AddDimensionsVariables(stateSave, 16, 16, DimensionVariableAction.ExcludeFileOptions);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });
                AddColorVariables(stateSave, true);

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                ApplySortValuesFromOrderInState(stateSave);

                AddVariableReferenceList(stateSave);

                mDefaults.Add("Rectangle", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                     Polygon                                                        //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                var stateSave = new StateSave();
                stateSave.Name = "Default";

                AddPositioningVariables(stateSave, addOriginVariables: false);

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });
                AddColorVariables(stateSave, true);

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                var pointsVariable = new VariableListSave<Vector2>()
                { Name = "Points", Category = "Points" };

                pointsVariable.Value.Add(new Vector2(-32, -32));
                pointsVariable.Value.Add(new Vector2(32, -32));
                pointsVariable.Value.Add(new Vector2(32, 32));
                pointsVariable.Value.Add(new Vector2(-32, 32));
                // close it:
                pointsVariable.Value.Add(new Vector2(-32, -32));

                stateSave.VariableLists.Add(pointsVariable);

                AddStateVariable(stateSave);

                AddVariableReferenceList(stateSave);

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("Polygon", stateSave);
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                    NineSlice                                                       //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";
                AddPositioningVariables(stateSave);
                AddDimensionsVariables(stateSave, 64, 64, DimensionVariableAction.ExcludeFileOptions);
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = "", Name = "SourceFile", IsFile = true });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "bool", Value = true, Name = "Visible" });

                AddColorVariables(stateSave);
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "Blend", Value = Blend.Normal, Name = "Blend", Category = "Rendering" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "TextureAddress", Value = Gum.Managers.TextureAddress.EntireTexture, Name = "Texture Address", Category = "Source" });

                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Left", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Top", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Width", Category = "Source" });
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 0, Name = "Texture Height", Category = "Source" });

                AddVariableReferenceList(stateSave);

                AddEventVariables(stateSave);

                AddStateVariable(stateSave);

                stateSave.Variables.Add(new VariableSave { Type = "float", Value = 0.0f, Category = "Flip and Rotation", Name = "Rotation" });

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("NineSlice", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                     Component                                                      //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

#if GUM
                // Victor Chelaru
                // August 21, 2014
                // Not sure why we have
                // this here.  Doing so would
                // create an endless loop...
                //stateSave.Variables.Add(new VariableSave { Type = "string", Value = "Default", Name = "State", CustomTypeConverter = new AvailableStatesConverter(null)});
                // The type used to be "string" but we want to differentiate it from actual strings so we use "State"
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "State", Value = null, Name = "State", CustomTypeConverter = new AvailableStatesConverter(null) });
#endif

                ApplySortValuesFromOrderInState(stateSave);

                AddStateVariable(stateSave);

                // Not sure if component needs this - does it get values from container?
                //AddEventVariables(stateSave);

                mDefaults.Add("Component", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            {
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                                    Screen                                                          //
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                var stateSave = new StateSave();
                stateSave.Name = "Default";

                ApplySortValuesFromOrderInState(stateSave);

                mDefaults.Add("Screen", stateSave);
                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            }

            RefreshStateVariablesThroughPlugins();

            // We shouldn't do this because states above may explicitly not want to set values - like the variable for state
            //foreach (var defaultState in mDefaults.Values)
            //{
            //    foreach (var variable in defaultState.Variables)
            //    {
            //        variable.SetsValue = true;
            //    }
            //}
        }

        private void AddVariableReferenceList(StateSave stateSave)
        {
            stateSave.VariableLists.Add(new VariableListSave<string> { Type = "string", Value = new List<string>(), Category = "References", Name = "VariableReferences" });
        }

        public void RefreshStateVariablesThroughPlugins()
        {
#if GUM
            foreach (var kvp in DefaultStates)
            {
                PluginManager.Self.ModifyDefaultStandardState(kvp.Key, kvp.Value);
            }
#endif
        }

        private void AddEventVariables(StateSave stateSave, bool defaultHasEvents = false)
        {
            stateSave.Variables.Add(
                new VariableSave
                { SetsValue = true, Type = "bool", Value = defaultHasEvents, Name = "HasEvents", Category = "Behavior", CanOnlyBeSetInDefaultState = true,
                    // We used to exclude them from instances, but there are plenty of situations where we want to hide events on an instance. It's similar to InputTransparent in XamForms
                    //ExcludeFromInstances = true
                });
            stateSave.Variables.Add(
                new VariableSave
                { SetsValue = true, Type = "bool", Value = defaultHasEvents, Name = "ExposeChildrenEvents", Category = "Behavior", CanOnlyBeSetInDefaultState = true,
                    // We used to exclude them from instances, but there are plenty of situations where we want to hide events on an instance. It's similar to InputTransparent in XamForms
                    //ExcludeFromInstances = true
                });
        }

        private static void AddStateVariable(StateSave stateSave)
        {
            stateSave.Variables.Add(new VariableSave
            {
                // Don't want it to set the value...
                SetsValue = false,
                Type = "State",
                Value = "Default",
                Name = "State"
#if GUM
,
                CustomTypeConverter = new AvailableStatesConverter(null)
#endif
            });
        }

        private void ApplySortValuesFromOrderInState(StateSave stateSave)
        {
            for (int i = 0; i < stateSave.Variables.Count; i++)
            {
                stateSave.Variables[i].DesiredOrder = i;
            }
        }

        public static void AddColorVariables(StateSave stateSave, bool includeAlpha = true)
        {
            if (includeAlpha)
            {
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 255, Name = "Alpha", Category = "Rendering" });
            }
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 255, Name = "Red", Category = "Rendering" });
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 255, Name = "Green", Category = "Rendering" });
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "int", Value = 255, Name = "Blue", Category = "Rendering" });
        }

        public static void AddDimensionsVariables(StateSave stateSave, float defaultWidth, float defaultHeight, DimensionVariableAction dimensionVariableAction)
        {
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = defaultWidth, Name = "Width", Category = "Dimensions" });

            var defaultValue = DimensionUnitType.Absolute;

            if(dimensionVariableAction == DimensionVariableAction.DefaultToPercentageOfFile)
            {
                defaultValue = DimensionUnitType.PercentageOfSourceFile;
            }

            VariableSave variableSave = new VariableSave { SetsValue = true, Type = typeof(DimensionUnitType).Name, Value = defaultValue, Name = "Width Units", Category = "Dimensions" };
            if (dimensionVariableAction == DimensionVariableAction.ExcludeFileOptions)
            {
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.PercentageOfSourceFile);
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.MaintainFileAspectRatio);
            }
            stateSave.Variables.Add(variableSave);

            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = defaultHeight, Name = "Height", Category = "Dimensions" });

            variableSave = new VariableSave { SetsValue = true, Type = typeof(DimensionUnitType).Name, Value = defaultValue, Name = "Height Units", Category = "Dimensions" };
            if (dimensionVariableAction == DimensionVariableAction.ExcludeFileOptions)
            {
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.PercentageOfSourceFile);
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.MaintainFileAspectRatio);
            }
            stateSave.Variables.Add(variableSave);
        }

        public static void AddPositioningVariables(StateSave stateSave, bool addOriginVariables = true, bool includeBaseline = false)
        {
            List<object> xUnitsExclusions = new List<object>();
            xUnitsExclusions.Add(PositionUnitType.PixelsFromTop);
            xUnitsExclusions.Add(PositionUnitType.PercentageHeight);
            xUnitsExclusions.Add(PositionUnitType.PixelsFromBottom);
            xUnitsExclusions.Add(PositionUnitType.PixelsFromCenterY);
            xUnitsExclusions.Add(PositionUnitType.PixelsFromCenterYInverted);
            xUnitsExclusions.Add(PositionUnitType.PixelsFromBaseline);

            List<object> yUnitsExclusions = new List<object>();
            yUnitsExclusions.Add(PositionUnitType.PixelsFromLeft);
            yUnitsExclusions.Add(PositionUnitType.PixelsFromCenterX);
            yUnitsExclusions.Add(PositionUnitType.PercentageWidth);
            yUnitsExclusions.Add(PositionUnitType.PixelsFromRight);

            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 0.0f, Name = "X", Category = "Position" });
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = typeof(PositionUnitType).Name, Value = PositionUnitType.PixelsFromLeft, Name = "X Units", Category = "Position", ExcludedValuesForEnum = xUnitsExclusions });

            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = 0.0f, Name = "Y", Category = "Position" });
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = typeof(PositionUnitType).Name, Value = PositionUnitType.PixelsFromTop, Name = "Y Units", Category = "Position", ExcludedValuesForEnum = yUnitsExclusions });

            if(addOriginVariables)
            {
                stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = nameof(HorizontalAlignment), Value = HorizontalAlignment.Left, Name = "X Origin", Category = "Position" });

                var verticalAlignmentVariable =
                    new VariableSave { SetsValue = true, Type = nameof(VerticalAlignment), Value = VerticalAlignment.Top, Name = "Y Origin", Category = "Position" };
                if(includeBaseline == false)
                {
                    verticalAlignmentVariable.ExcludedValuesForEnum.Add(VerticalAlignment.TextBaseline);
                }
                stateSave.Variables.Add(verticalAlignmentVariable);
            }

            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "string", Value = null, Name = "Guide", Category = "Position" });
#if GUM
            AddParentVariables(stateSave);
#endif
        }

#if GUM
        private static void AddParentVariables(StateSave variables)
        {
            VariableSave variableSave = new VariableSave();
            variableSave.SetsValue = true;
            variableSave.Type = "string";
            variableSave.Name = "Parent";
            variableSave.CanOnlyBeSetInDefaultState = true;
            variableSave.CustomTypeConverter = new AvailableInstancesConverter() { IncludeScreenBounds = true };

            variableSave.PropertiesToSetOnDisplayer["IsEditable"] = true;

            variables.Variables.Add(variableSave);
        }
#endif

        public StateSave GetDefaultStateFor(string type, bool throwExceptionOnMissing = true)
        {
            if (mDefaults == null)
            {
                throw new Exception("You must first call Initialize on StandardElementsManager before calling this function");
            }
            if(string.IsNullOrEmpty(type))
            {
                return null;
            }
            if(mDefaults.ContainsKey(type))
            {
                return mDefaults[type];

            }
            else
            {

                StateSave customState = null;
#if GUM
                customState = PluginManager.Self.GetDefaultStateFor(type);
#elif SKIA
                // In Skia we will assume that any type that comes through has a default state:
                customState = new StateSave();
                AddPositioningVariables(customState, addOriginVariables: true);
                mDefaults[type] = customState;
#endif

                if (customState == null && throwExceptionOnMissing)
                {
                    throw new InvalidOperationException(
                        $"Could not get the default state for type {type} in either the default or through plugins");
                }
                else
                {
                    return customState;
                }
            }
        }

        public bool IsDefaultType(string type)
        {
            return mDefaults.ContainsKey(type);
        }

        public void PopulateProjectWithDefaultStandards(GumProjectSave gumProjectSave)
        {
            if (mDefaults == null)
            {
                throw new Exception("You must first call Initialize on this StandardElementsManager");
            }

            foreach (KeyValuePair<string, StateSave> kvp in mDefaults)
            {

                string type = kvp.Key;

                if (type != "Screen")
                {
                    AddStandardElementSaveInstance(gumProjectSave, type);
                }
            }
        }

        public StandardElementSave AddStandardElementSaveInstance(GumProjectSave gumProjectSave, string type)
        {
            StandardElementSave elementSave = new StandardElementSave();
            elementSave.Initialize(mDefaults[type]);
            elementSave.Name = type;

            gumProjectSave.StandardElementReferences.Add( new ElementReference { Name = type, ElementType = ElementType.Standard});
            gumProjectSave.StandardElements.Add( elementSave);

            return elementSave;
        }

    }
}


text:
'use strict';

require('mocha');
var assert = require('assert');
var scripts = require('..');

describe('script-tags:', function () {
  it('should extract inner html from the script tag.', function () {
    var actual = scripts('<script src="bootstrap.js"></script>');
    assert(actual[0].hasOwnProperty('html'));
    assert(actual[0].hasOwnProperty('text'));
    assert(actual[0].attrs.hasOwnProperty('src'));
    assert.equal(actual[0].attrs.src, 'bootstrap.js');
  });

  it('should extract inner html from the script tag.', function () {
    var actual = scripts('<script>var foo = "bar";</script>');
    assert(/foo/.test(actual[0].html));
    assert(actual[0].hasOwnProperty('html'));
    assert(actual[0].hasOwnProperty('text'));
  });
});

redpajama_set_name: RedPajamaGithub


text:
var socket = io.connect(location.origin);
var inits = angular.module('myapp', []);

inits.controller('myappCtrl', ['$rootScope', '$scope','$http', function ($rootScope, $scope,$http) {
    socket.on('message', function (data) {
        $scope.$apply(function () {
            setTimeout(function () {
                angular.element($('.nav-tabs .active').get(0)).trigger('click');
            }, 100);
        });
        $scope.getDetail(data.id);
    });

    $scope.getDetail = function (id,event) {
        $scope.getDetailActive = function (){
            $http.post('/detail/' + id).success(function (reponse) {
                if($rootScope.currentId == id){
                    $rootScope.detail = reponse[0];
                } else {
                    $rootScope.tempdetail = reponse[0];
                }

            });
        };

        if(event){
            $rootScope.currentId = id;
            $scope.getDetailActive();
        } else {
            if($('.btn-warning').attr('id') == id){
                $scope.getDetailActive();
            }
        }
    };

    $http.post('./').success(function (reponse) {
        $rootScope.data = reponse;

        setTimeout(function () {
            angular.element($('.nav-tabs .active').get(0)).trigger('click');
        }, 100);

    });

    $scope.tabsClick = function (name){
        $http.post('admin/query/'+name).success(function (reponse) {
            $rootScope.schedules = reponse;
        });
    };
}]);


text:
versal-component-launcher {
  display: block;
  line-height: 0;
}


text:
package com.larroy.quant.quotedb

import org.specs2.specification.Scope

import java.io.File

trait TempDBScope extends Scope {
  val tmpPath = File.createTempFile("quoteDB_tests_", ".db")
  tmpPath.deleteOnExit()
  val quoteDB = QuoteDB(s"sqlite://$tmpPath")
}


text:
package gwt.client.place;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

public class RulePlace extends Place {

    public static class Tokenizer implements PlaceTokenizer<RulePlace> {

        @Override
        public String getToken(RulePlace place) {
            return place.getToken();
        }

        @Override
        public RulePlace getPlace(String token) {
            return new RulePlace();
        }
    }

    private String token;

    public RulePlace(){
        this.token = "";
    }

    public String getToken() {
        return this.token;
    }
}


text:
package html5.app.chap11;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@MultipartConfig
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		res.setCharacterEncoding("utf-8");
		String id = req.getParameter("id");
		String pass = req.getParameter("pass");
		String msg = "";
		if ("hong".equals(id) && "1234".equals(pass)) {
			msg="반갑습니다.";
		} else {
			msg = "id 또는 pass를 확인하세요.";
		}

		PrintWriter out = res.getWriter();
		out.println(msg);
	}
}


text:
<?php
namespace app\widgets;

use Yii;
use yii\base\Widget;

class Topnav extends Widget
{
    public $user;

    public function init()
    {

    }

    public function run()
    {
        return $this->render('topnav', [
            'user' => $this->user,
        ]);
    }

}


text:
#ifndef __vqQueryVideoPlayer_h
#define __vqQueryVideoPlayer_h

#include <QUrl>

#include <vvQueryVideoPlayer.h>

class vqQueryVideoPlayer : public vvQueryVideoPlayer
{
  Q_OBJECT

public:
  vqQueryVideoPlayer(QWidget* parent = 0);
  ~vqQueryVideoPlayer();

  bool setVideoUri(QUrl uri);

  virtual int videoHeight();

  void setTimeRange(double startTime, double endTime);

public slots:
  virtual void reset();

protected:
  virtual void buildVideoModel();

protected:
  struct qvpInternal;
  qvpInternal* MyInternal;
};

#endif


text:
// -*- C++ -*-

// Copyright (C) 2005, 2006, 2009, 2010 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.

// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.

// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.

// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
// <http://www.gnu.org/licenses/>.

// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.

// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.

/**
 * @file tree_policy.hpp
 * Contains tree-related policies.
 */

#ifndef PB_DS_TREE_POLICY_HPP
#define PB_DS_TREE_POLICY_HPP

#include <bits/c++config.h>
#include <iterator>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/basic_tree_policy/basic_tree_policy_base.hpp>

namespace __gnu_pbds
{
  // A null node updator, indicating that no node updates are required.
  template<typename Const_Node_Iterator,
	   typename Node_Iterator,
	   typename Cmp_Fn,
	   typename Allocator>
  struct null_tree_node_update
  { };

#define PB_DS_CLASS_T_DEC \
  template<typename Const_Node_Iterator, class Node_Iterator, class Cmp_Fn, class Allocator>

#define PB_DS_CLASS_C_DEC \
  tree_order_statistics_node_update<Const_Node_Iterator, Node_Iterator, Cmp_Fn, Allocator>

#define PB_DS_BASE_C_DEC						\
  detail::basic_tree_policy_base<Const_Node_Iterator, Node_Iterator, Allocator>

  // Functor updating ranks of entrees.
  template<typename Const_Node_Iterator, typename Node_Iterator,
	   typename Cmp_Fn, typename Allocator>
  class tree_order_statistics_node_update : private PB_DS_BASE_C_DEC
  {
  private:
    typedef PB_DS_BASE_C_DEC base_type;

  public:
    typedef Cmp_Fn cmp_fn;
    typedef Allocator allocator_type;
    typedef typename allocator_type::size_type size_type;
    typedef typename base_type::key_type key_type;
    typedef typename base_type::const_key_reference const_key_reference;

    typedef size_type metadata_type;
    typedef Const_Node_Iterator const_node_iterator;
    typedef Node_Iterator node_iterator;
    typedef typename const_node_iterator::value_type const_iterator;
    typedef typename node_iterator::value_type iterator;

    // Finds an entry by __order. Returns a const_iterator to the
    // entry with the __order order, or a const_iterator to the
    // container object's end if order is at least the size of the
    // container object.
    inline const_iterator
    find_by_order(size_type order) const;

    // Finds an entry by __order. Returns an iterator to the entry
    // with the __order order, or an iterator to the container
    // object's end if order is at least the size of the container
    // object.
    inline iterator
    find_by_order(size_type order);

    // Returns the order of a key within a sequence. For exapmle, if
    // r_key is the smallest key, this method will return 0; if r_key
    // is a key between the smallest and next key, this method will
    // return 1; if r_key is a key larger than the largest key, this
    // method will return the size of r_c.
    inline size_type
    order_of_key(const_key_reference r_key) const;

  private:
    // Const reference to the container's value-type.
    typedef typename base_type::const_reference const_reference;

    // Const pointer to the container's value-type.
    typedef typename base_type::const_pointer const_pointer;

    typedef typename allocator_type::template rebind<metadata_type>::other metadata_rebind;
    // Const metadata reference.
    typedef typename metadata_rebind::const_reference const_metadata_reference;

    // Metadata reference.
    typedef typename metadata_rebind::reference metadata_reference;

    // Returns the const_node_iterator associated with the tree's root node.
    virtual const_node_iterator
    node_begin() const = 0;

    // Returns the node_iterator associated with the tree's root node.
    virtual node_iterator
    node_begin() = 0;

    // Returns the const_node_iterator associated with a just-after leaf node.
    virtual const_node_iterator
    node_end() const = 0;

    // Returns the node_iterator associated with a just-after leaf node.
    virtual node_iterator
    node_end() = 0;

    // Access to the cmp_fn object.
    virtual cmp_fn&
    get_cmp_fn() = 0;

  protected:
    // Updates the rank of a node through a node_iterator node_it;
    // end_nd_it is the end node iterator.
    inline void
    operator()(node_iterator node_it, const_node_iterator end_nd_it) const;

    virtual
    ~tree_order_statistics_node_update();
  };

#include <ext/pb_ds/detail/tree_policy/order_statistics_imp.hpp>

#undef PB_DS_CLASS_T_DEC
#undef PB_DS_CLASS_C_DEC
#undef PB_DS_BASE_C_DEC

} // namespace __gnu_pbds

#endif


text:
CKEDITOR.plugins.setLang( 'pastefromword', 'sk', {
	confirmCleanup: 'Vkladaný text vyzerá byť skopírovaný z Wordu. Chcete ho automaticky vyčistiť pred vkladaním?',
	error: 'Nebolo možné vyčistiť vložené dáta kvôli internej chybe',
	title: 'Vložiť z Wordu',
	toolbar: 'Vložiť z Wordu'
});


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.gradle.testkit.runner (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">

org.gradle.testkit.runner

Interfaces

BuildResult

BuildTask

Classes

GradleRunner

Enums

TaskOutcome

Exceptions

InvalidRunnerConfigurationException

UnexpectedBuildFailure

UnexpectedBuildSuccess


text:
package algolia.dsl

import algolia.definitions.BrowseIndexDefinition
import algolia.responses.BrowseResult
import algolia.{AlgoliaClient, Executable}
import org.json4s.Formats

import scala.concurrent.{ExecutionContext, Future}

trait BrowseDsl {

  implicit val formats: Formats

  case object browse {

    def index(index: String): BrowseIndexDefinition =
      BrowseIndexDefinition(index)

  }

  implicit object BrowseIndexDefinitionExecutable
      extends Executable[BrowseIndexDefinition, BrowseResult] {
    override def apply(client: AlgoliaClient, query: BrowseIndexDefinition)(
        implicit executor: ExecutionContext
    ): Future[BrowseResult] = {
      client.request[BrowseResult](query.build())
    }
  }

}


text:
import boto3

def get_export_value(name, client=None, session=None):
    def _get_export_value(name, next_token):
        resp = _list_exports(next_token=next_token, client=client, session=session)

        exports = resp['Exports']
        export = next((export for export in exports if export['Name'] == name), None)

        if export:
            return export['Value']

        next_token = resp['NextToken'] if 'NextToken' in resp else None
        if not export and next_token:
            return _get_export_value(name, next_token=next_token)

        # at this point, no export is found and next_token==None
        raise ExportNotFoundError(name=name)

    return _get_export_value(name, next_token=None)

def _list_exports(next_token=None, client=None, session=None):
    """
    Cloudformation facade, for easier mocking during unit testing
    """
    if client and session:
        raise ValueError('Cannot specify both client and session')

    if session:
        cf = session.client('cloudformation')
    elif client:
        cf = client
    else:
        cf = boto3.client('cloudformation')

    if next_token:
        return cf.list_exports(NextToken=next_token)
    else:
        return cf.list_exports()

class ExportNotFoundError(Exception):
    def __init__(self, name):
        super(ExportNotFoundError, self).__init__(
            'Name: {name} not found in exports'.format(name=name))


text:
/* eslint flowtype/require-valid-file-annotation: 0 */
'use strict'

const gulp = require('gulp')
const eslint = require('gulp-eslint')
const nodemon = require('gulp-nodemon')
const gutil = require('gulp-util')
const rollup = require('gulp-rollup')
const envLoader = require('node-env-file')
const insert = require('gulp-insert')
const flowtype = require('gulp-flowtype')
const removeFlow = require('rollup-plugin-flow')
const newer = require('gulp-newer')

envLoader(`./env.plain`)

const EXIT_ON_ERRORS = process.env.EXIT_ON_ERRORS || false
const nodePrepend = "'use strong'\n"
const flowOptions = {
  abort: process.env.EXIT_ON_ERRORS || false
}

const rollupPlugins = [ removeFlow() ]

const handleErrors = function (err) {
  gutil.log(err)
  this.emit('end')
}

function lint () {
  const stream = gulp.src(['./src/**/*.js'])
  .pipe(newer('./_build/'))
  .pipe(eslint()).pipe(eslint.format())
  if (EXIT_ON_ERRORS) stream.pipe(eslint.failAfterError())
  else stream.on('error', handleErrors)

  return stream
}

function flow () {
  return gulp.src(['./src/**/*.js'])
    .pipe(flowtype(flowOptions))
}
gulp.task('flow', gulp.parallel(flow))

function botRollup () {
  return gulp.src(['./src/**/*.js'])
  .pipe(rollup({
    entry: [ './src/index.js', './src/discord/index.js' ],
    sourceMap: true,
    plugins: rollupPlugins
  }))
  .pipe(newer('./_build/'))
  .pipe(insert.prepend(nodePrepend))
  .on('error', handleErrors)
  .pipe(gulp.dest('./_build/'))
}
gulp.task('botRollup', botRollup)

const all_tasks = gulp.parallel([
  botRollup, lint
])
gulp.task('default', all_tasks)
gulp.task('lint', lint)
gulp.task('rollup', botRollup)

gulp.task('watch', gulp.series(all_tasks, () => {
  nodemon({
    script: './_build/index.js',
    ext: '.js',
    watch: [
      'src/**/*.js', 'env.plain'
    ],
    tasks: ['botRollup', 'lint']
  })
}))


text:
/**
 * Command Sender
 */

'use strict';

var helper = require(__dirname + '/helper');

/**
 * Constructor
 * @param {Ws} Instance of WebSocket connection
 */
var CommandSender = function (ws_instance) {

	this.httpReq = null;
	this.httpRes = null;
	this.wsInstance = null;

};

/**
 * Make an instance from the http request
 * @param  {Request} req	Request object of Express.js
 * @param  {Response} res	Response object of Express.js
 * @return {CommandSender}     Instance
 */
CommandSender.getInstanceByHttpReq = function(req, res) {

	var instance = new CommandSender();
	instance.httpReq = req;
	instance.httpRes = res;

	return instance;

};

/**
 * Make an instance from the WebSocket connection
 * @param  {Ws} ws_instance		WebSocket connection
 * @return {CommandSender}     Instance
 */
CommandSender.getInstanceByWs = function(ws_instance) {

	var instance = new CommandSender();
	instance.wsInstance = ws_instance;

	return instance;

};

/**
 * To notify that the command has been executed
 * @param  {String} cmd_id			ID of the executed command
 * @param  {Array} responses		Array of the reponses of each devices
 */
CommandSender.prototype.onCommandExecuted = function (cmd_id, responses) {

	var self = this;

	console.log('onCommandExecuted');

	// Listup the devices
	var device_ids = [];
	responses.forEach(function (cmd_response, index) {
		device_ids.push(cmd_response.deviceId);
	});

	// Listup the execution successful or failed devices
	var success_device_ids = [], failed_device_ids = [], success_responses = [], error_responses = [];
	responses.forEach(function (cmd_response, index) {
		if (cmd_response.responseSuccess) {
			success_device_ids.push(cmd_response.deviceId);
			success_responses.push(cmd_response.responseSuccess);
		} else {
			failed_device_ids.push(cmd_response.deviceId);
			error_responses.push(cmd_response.responseError);
		}
	});

	// Make a send data
	var message = null;
	if (responses.length == 0) {
		message = 'There are no online devices';
	} else {
		message = 'Your command has sent to ' + success_device_ids.length + ' devices within Device ID ' + device_ids.join(',') + '.';
	}
	var response_data = {
		cmdExecId: cmd_id,
		devices: device_ids,
		successDevices: success_device_ids,
		successResponses: success_responses,
		errorDevices: failed_device_ids,
		errorResponses: error_responses,
		summaryMessage: message
	};

	// Send a response to the sender
	if (self.wsInstance) { // WebSocket connection

		try {
			self.wsInstance.send(JSON.stringify({
				cmd: '_sendCmdResponse',
				args: response_data
			}));
		} catch (e) {
			console.warn('CommandSender - onCommandExecuted - Could not sent a response: ' + e);
		}

	} else if (self.httpReq && self.httpRes) { // HTTP request

		if (0 < success_responses.length) {
			self.httpRes.send(response_data);
		} else {
			self.httpRes.status(400).send(response_data);
		}

	}

};

// ----

module.exports = CommandSender;


text:
using namespace analyze_BMP;

item_BITMAPCORE::item_BITMAPCORE(const agaliaContainer* image, uint64_t offset, uint64_t size)
	:item_Base(image, offset, size)
{
}

item_BITMAPCORE::~item_BITMAPCORE()
{
}

HRESULT item_BITMAPCORE::getItemName(agaliaString** str) const
{
	if (str == nullptr) return E_POINTER;
	*str = agaliaString::create(L"BITMAPCOREHEADER");
	return S_OK;
}

HRESULT item_BITMAPCORE::getItemPropCount(uint32_t* count) const
{
	if (count == nullptr) return E_POINTER;
	*count = prop_last;
	return S_OK;
}

HRESULT item_BITMAPCORE::getItemPropName(uint32_t index, agaliaString** str) const
{
	if (str == nullptr) return E_POINTER;

	const wchar_t* name = nullptr;
	switch (index)
	{
	case prop_bcSize: name = L"bcSize"; break;
	case prop_bcWidth: name = L"bcWidth"; break;
	case prop_bcHeight: name = L"bcHeight"; break;
	case prop_bcPlanes: name = L"bcPlanes"; break;
	case prop_bcBitCount: name = L"bcBitCount"; break;
	default:
		return __super::getItemPropName(index, str);
	};

	*str = agaliaString::create(name);
	return S_OK;
}

HRESULT item_BITMAPCORE::getItemPropValue(uint32_t index, agaliaString** str) const
{
	BITMAPCOREHEADER bch = {};
	std::wstringstream temp;
	if (index == prop_bcSize)
	{
		auto hr = image->ReadData(&bch.bcSize, getOffset() + offsetof(BITMAPCOREHEADER, bcSize), sizeof(bch.bcSize));
		if (FAILED(hr)) return hr;
		format_dec(temp, bch.bcSize);
	}
	else if (index == prop_bcWidth)
	{
		auto hr = image->ReadData(&bch.bcWidth, getOffset() + offsetof(BITMAPCOREHEADER, bcWidth), sizeof(bch.bcWidth));
		if (FAILED(hr)) return hr;
		format_dec(temp, bch.bcWidth);
	}
	else if (index == prop_bcHeight)
	{
		auto hr = image->ReadData(&bch.bcHeight, getOffset() + offsetof(BITMAPCOREHEADER, bcHeight), sizeof(bch.bcHeight));
		if (FAILED(hr)) return hr;
		format_dec(temp, bch.bcHeight);
	}
	else if (index == prop_bcPlanes)
	{
		auto hr = image->ReadData(&bch.bcPlanes, getOffset() + offsetof(BITMAPCOREHEADER, bcPlanes), sizeof(bch.bcPlanes));
		if (FAILED(hr)) return hr;
		format_dec(temp, bch.bcPlanes);
	}
	else if (index == prop_bcBitCount)
	{
		auto hr = image->ReadData(&bch.bcBitCount, getOffset() + offsetof(BITMAPCOREHEADER, bcBitCount), sizeof(bch.bcBitCount));
		if (FAILED(hr)) return hr;
		format_dec(temp, bch.bcBitCount);
	}
	else
	{
		return __super::getItemPropValue(index, str);
	}

	*str = agaliaString::create(temp.str().c_str());
	return S_OK;
}

HRESULT item_BITMAPCORE::getNextItem(agaliaItem** next) const
{
	BITMAPCOREHEADER bch = {};
	auto hr = image->ReadData(&bch, getOffset(), sizeof(bch));
	if (FAILED(hr)) return hr;

	LONG scans = abs(bch.bcHeight);
	LONG bytes_of_line = (bch.bcBitCount * bch.bcWidth / 8 + 3) & ~3;
	LONG size_image = bytes_of_line * scans;

	auto p = new item_ColorIndexParent(image, bfOffBits, size_image);
	p->bfOffBits = bfOffBits;
	p->scans = scans;
	p->bytes_of_line = bytes_of_line;
	p->biSizeImage = size_image;
	*next = p;
	return S_OK;
}

HRESULT item_BITMAPCORE::getColumnValue(uint32_t column, agaliaString** str) const
{
	if (column == column_offset)
	{
		std::wstringstream temp;
		format_hex(temp, getOffset(), 8);
		*str = agaliaString::create(temp.str().c_str());
		return S_OK;
	}
	else if (column == column_structure)
	{
		return getItemName(str);
	}
	else if (column == column_value)
	{
		BITMAPCOREHEADER bch = {};
		auto hr = image->ReadData(&bch.bcSize, getOffset() + offsetof(BITMAPCOREHEADER, bcSize), sizeof(bch.bcSize));
		if (FAILED(hr)) return hr;

		std::wstringstream temp;
		temp << L"bcSize : " << bch.bcSize;
		*str = agaliaString::create(temp.str().c_str());
		return S_OK;
	}
	return E_NOTIMPL;
}

HRESULT item_BITMAPCORE::getAdditionalInfoCount(uint32_t* row) const
{
	*row = addinf_last;
	return S_OK;
}

HRESULT item_BITMAPCORE::getAdditionalInfoValue(uint32_t row, agaliaString** str) const
{
	BITMAPCOREHEADER bch = {};
	std::wstringstream temp;
	if (row == addinf_bcWidth)
	{
		auto hr = image->ReadData(&bch.bcWidth, getOffset() + offsetof(BITMAPCOREHEADER, bcWidth), sizeof(bch.bcWidth));
		if (FAILED(hr)) return hr;

		temp << L"bcWidth : " << bch.bcWidth;
	}
	else if (row == addinf_bcHeight)
	{
		auto hr = image->ReadData(&bch.bcHeight, getOffset() + offsetof(BITMAPCOREHEADER, bcHeight), sizeof(bch.bcHeight));
		if (FAILED(hr)) return hr;

		temp << L"bcHeight : " << bch.bcHeight;
	}
	else if (row == addinf_bcPlanes)
	{
		auto hr = image->ReadData(&bch.bcPlanes, getOffset() + offsetof(BITMAPCOREHEADER, bcPlanes), sizeof(bch.bcPlanes));
		if (FAILED(hr)) return hr;

		temp << L"bcPlanes : " << bch.bcPlanes;
	}
	else if (row == addinf_bcBitCount)
	{
		auto hr = image->ReadData(&bch.bcBitCount, getOffset() + offsetof(BITMAPCOREHEADER, bcBitCount), sizeof(bch.bcBitCount));
		if (FAILED(hr)) return hr;

		temp << L"bcBitCount : " << bch.bcBitCount;
	}
	else
	{
		return E_INVALIDARG;
	}

	*str = agaliaString::create(temp.str().c_str());
	return S_OK;
}


text:
package com.f2prateek.couchpotato.ui;

import com.f2prateek.couchpotato.ui.debug.DebugAppContainer;
import com.f2prateek.couchpotato.ui.debug.SocketActivityHierarchyServer;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;

@Module(
    injects = DebugAppContainer.class,
    complete = false,
    library = true,
    overrides = true)
public final class DebugUiModule {
  @Provides @Singleton AppContainer provideAppContainer(DebugAppContainer debugAppContainer) {
    return debugAppContainer;
  }

  @Provides @Singleton ActivityHierarchyServer provideActivityHierarchyServer() {
    return new SocketActivityHierarchyServer();
  }
}


text:
import json
import bpy
import os
from bpy.types import Operator
from . import utils
from .assets.scripts.evertims import ( Evertims, evertUtils )

 # to launch EVERTims raytracing client
import subprocess
# ---------------------------------------------------------------
# import components necessary to report EVERTims raytracing client
# logs in console
import sys
import threading
try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.x

ON_POSIX = 'posix' in sys.builtin_module_names
ASSET_FILE_NAME = "evertims-assets.blend"

class EVERTimsImportObject(Operator):
    """Import default EVERTims element (KX_GameObject) into scene"""
    bl_label = "Import an object (KX_GameObject, Empty, etc.) from anther .blend file"
    bl_idname = 'evert.import_template'
    bl_options = {'REGISTER', 'UNDO'}

    arg = bpy.props.StringProperty()

    def execute(self, context):

        loadType = self.arg
        evertims = context.scene.evertims

        # cancel if simulation is running
        if evertims.enable_edit_mode:
            self.report({'WARNING'}, 'Cannot import element while simulation is running')
            return {'CANCELLED'}

        # cleanup before we start
        bpy.ops.object.select_all(action='DESELECT')

        # set asset .blend file name
        filename = ASSET_FILE_NAME
        obj = None

        if loadType == 'scene':
            # load each object separately for access to resulting obj.name
            obj = self.loadAsset(filename, ('Room'))
            evertims.room_object = obj.name
            obj = self.loadAsset(filename, ('Source'))
            evertims.source_object = obj.name
            obj = self.loadAsset(filename, ('Listener_Rotate', 'Listener'))
            evertims.listener_object = obj.name
            # load others
            self.loadAsset(filename, ('Logic_EVERTims'))

        if loadType == 'logic':
            obj = self.loadAsset(filename, ('Logic_EVERTims'))

        if loadType == 'room':
            obj = self.loadAsset(filename, ('Room'))
            evertims.room_object = obj.name

        if loadType == 'source':
            obj = self.loadAsset(filename, ('Source'))
            evertims.source_object = obj.name

        if loadType == 'listener':
            obj = self.loadAsset(filename, ('Listener_Rotate', 'Listener'))
            evertims.listener_object = obj.name

        if not obj:
            self.report({'ERROR'}, 'something went wrong')
            return {'CANCELLED'}
        else:

            obj.select = True
            bpy.context.scene.objects.active = obj
            return {'FINISHED'}

    def loadAsset(self, filename, objList):

        scriptPath = os.path.realpath(__file__)
        assetPath = os.path.join(os.path.dirname(scriptPath), 'assets', filename)

        try:
            with bpy.data.libraries.load(assetPath) as (data_from, data_to):
                data_to.objects = [name for name in data_from.objects if name in objList]

        except:
            return 'Asset file not found'

        for obj in data_to.objects:
            bpy.context.scene.objects.link(obj)

        return obj

class EVERTimsImportText(Operator):
    """Import the list of available EVERTims acoustic materials as a text file"""
    bl_label = "Import a text file from anther .blend file"
    bl_idname = 'evert.import_script'
    bl_options = {'REGISTER', 'UNDO'}

    arg = bpy.props.StringProperty()

    def execute(self, context):

        loadType = self.arg

        # set asset .blend file name
        filename = ASSET_FILE_NAME

        if loadType == 'materialList':
            isLoaded = self.loadAsset(filename, ('evertims-materials.txt'))

        if not isLoaded:
            self.report({'ERROR'}, 'something went wrong')
            return {'CANCELLED'}

        else:
            self.report({'INFO'}, 'EVERTims material file imported in Text Editor window.')
            return {'FINISHED'}

    def loadAsset(self, filename, objList):

        scriptPath = os.path.realpath(__file__)
        assetPath = os.path.join(os.path.dirname(scriptPath), 'assets', filename)

        try:
            with bpy.data.libraries.load(assetPath) as (data_from, data_to):
                data_to.texts = [name for name in data_from.texts if name in objList]
        except:
            return False

        return True

class EVERTimsInBge(Operator):
    """setup EVERTims for BGE session"""
    bl_label = "setup EVERTims in BGE"
    bl_idname = 'evert.evertims_in_bge'
    bl_options = {'REGISTER'}

    arg = bpy.props.StringProperty()

    def execute(self, context):

        loadType = self.arg
        evertims = context.scene.evertims
        logic_obj = bpy.context.scene.objects.get('Logic_EVERTims')

        if loadType == 'ENABLE':
            # check if evertims setup properly
            if not evertims.room_object or not evertims.source_object or not evertims.listener_object or not logic_obj:
                self.report({'ERROR'}, 'Create at least 1 room (with material), 1 listener, 1 source and import EVERTims Logic object')
                return {'CANCELLED'}

            # update logic object properties for in-BGE access
            self.init_evertims_module_path(context)
            # update flag
            evertims.enable_bge = True

        elif loadType == 'DISABLE':
            # update flag
            evertims.enable_bge = False

        # update logic object properties for in-BGE access
        self.update_evertims_props(context)

        return {'FINISHED'}

    def update_evertims_props(self, context):

        evertims = context.scene.evertims

        # remember current active object
        old_obj = bpy.context.scene.objects.active

        # get logic object
        obj = bpy.context.scene.objects.get('Logic_EVERTims')

        if obj:
            bpy.context.scene.objects.active = obj

            propList = [ 'enable_bge', 'debug_logs', 'debug_rays', 'ip_local', 'ip_raytracing', 'ip_auralization', 'port_read', 'port_write_raytracing', 'port_write_auralization', 'movement_threshold_loc', 'movement_threshold_rot', 'room_object', 'source_object', 'listener_object']
            # sync. properties (for bge access) with GUI's
            for propName in propList:
                propValue = eval('evertims.' + propName)
                obj.game.properties[propName].value = propValue

            # get room object, update its RT60 values (not possible in bge, based on bpy routines)
            room = bpy.context.scene.objects.get(evertims.room_object)
            rt60Values = evertUtils.getRt60Values(utils.str2dict(evertims.mat_list), room)
            obj.game.properties['rt60Values'].value = json.dumps(rt60Values)

        # reset old active object
        bpy.context.scene.objects.active = old_obj

    def init_evertims_module_path(self, context):

        # get add-on path
        current_script_file = os.path.realpath(__file__)
        current_script_directory = os.path.dirname(current_script_file)
        addon_path = os.path.join(current_script_directory, 'assets', 'scripts')

        # get logic object
        obj = context.scene.objects.get('Logic_EVERTims')
        if obj:
            obj.game.properties['evertims_path'].value = addon_path

class EVERTimsInEditMode(Operator):
    """Start OSC sync. with EVERTims raytracing client.
    Continuous upload of scene info (room, listener, etc.) for auralization and
    download of raytracing results for visual feedback."""
    bl_label = "Enable Blender to EVERTims raytracing client connection in edit mode (as opposed to BGE mode)"
    bl_idname = 'evert.evertims_in_edit_mode'
    bl_options = {'REGISTER'}

    arg = bpy.props.StringProperty()

    _evertims = Evertims()
    _handle_timer = None

    @staticmethod
    def handle_add(self, context):
        # EVERTimsInEditMode._handle_draw_callback = bpy.types.SpaceView3D.draw_handler_add(EVERTimsInEditMode._draw_callback, (self,context), 'WINDOW', 'PRE_VIEW')
        context.window_manager.modal_handler_add(self)
        EVERTimsInEditMode._handle_timer = context.window_manager.event_timer_add(0.075, context.window)
        if context.scene.evertims.debug_logs: print('added evertims callback to draw_handler')

    @staticmethod
    def handle_remove(context):
        if EVERTimsInEditMode._handle_timer is not None:
            context.window_manager.event_timer_remove(EVERTimsInEditMode._handle_timer)
            EVERTimsInEditMode._handle_timer = None
            # context.window_manager.modal_handler_add(self)
            # bpy.types.SpaceView3D.draw_handler_remove(EVERTimsInEditMode._handle_draw_callback, 'WINDOW')
            # EVERTimsInEditMode._handle_draw_callback = None
            if context.scene.evertims.debug_logs: print('removed evertims callback from draw_handler')

    @classmethod
    def poll(cls, context):
        return context.area.type == 'VIEW_3D'

    def invoke(self, context, event):

        scene = context.scene
        evertims = scene.evertims
        loadType = self.arg

        # get active object
        # obj = bpy.context.scene.objects.active

        if loadType == 'PLAY':

            # load mat file if not loaded already
            evertims.mat_list = utils.loadMatFile(context)
            self._evertims.setMaterials(utils.str2dict(evertims.mat_list))

            # check room materials definition
            roomMatError = self.checkRoomMaterials(context)
            if roomMatError:
                self.report({'ERROR'}, roomMatError)
                return {'CANCELLED'}

            # init evertims
            isInitOk = self.initEvertims(context)

            if isInitOk:
                # update enable flag
                evertims.enable_edit_mode = True

                # add callback
                self.handle_add(self,context)

                return {'RUNNING_MODAL'}
            else:

                self.report({'ERROR'}, 'Create at least 1 room (with material), 1 listener, 1 source and import EVERTims Logic object')
                return {'CANCELLED'}

        elif loadType == 'STOP':
            # update enable flag
            evertims.enable_edit_mode = False

            # erase rays from screen
            context.area.tag_redraw()

            return {'CANCELLED'}

        elif loadType == 'CRYSTALIZE':
            self._evertims.crystalizeVisibleRays()
            return {'FINISHED'}

    def modal(self, context, event):
        """
        modal method, run always, call cancel function when Blender quit / load new scene
        """
        # kill modal
        if not context.scene.evertims.enable_edit_mode:
            self.cancel(context)

            # return flag to notify callback manager that this callback is no longer running
            return {'CANCELLED'}

        # execute modal
        elif event.type == 'TIMER':
            # run evertims internal callbacks
            self._evertims.bpy_modal()
            # force bgl rays redraw (else only redraw rays on user input event)
            if not context.area is None:
                context.area.tag_redraw()

        return {'PASS_THROUGH'}

    def cancel(self, context):
        """
        called when Blender quit / load new scene. Remove local callback from stack
        """
        # remove local callback
        self.handle_remove(context)

        # remove nested callback
        self._evertims.handle_remove()

        # erase rays from screen
        if not context.area is None:
            context.area.tag_redraw()

    def checkRoomMaterials(self, context):
        """
        check if all room materials are defined in mat file, return error msg (string)
        """
        evertims = context.scene.evertims
        objects = bpy.context.scene.objects

        room = objects.get(evertims.room_object)
        if not room: return 'no room defined'

        slots = room.material_slots
        evertMat = utils.str2dict(evertims.mat_list)
        for mat in slots:
            if not mat.name in evertMat: return 'undefined room material: ' + mat.name

        return ''

    def initEvertims(self, context):
        """
        init the Evertims() class instance, using GUI defined parameters (in EVERTims add-on pannel)
        """
        evertims = context.scene.evertims

        IP_RAYTRACING = evertims.ip_raytracing # EVERTims client IP address
        IP_AURALIZATION = evertims.ip_auralization # Auralization Engine IP address
        PORT_W_RAYTRACING = evertims.port_write_raytracing # port used by EVERTims client to read data sent by the BGE
        PORT_W_AURALIZATION = evertims.port_write_auralization # port used by EVERTims client to read data sent by the BGE
        IP_LOCAL = evertims.ip_local # local host (this computer) IP address, running the BGE
        PORT_R = evertims.port_read # port used by the BGE to read data sent by the EVERTims client
        DEBUG_LOG = evertims.debug_logs # enable / disable console log
        DEBUG_RAYS = evertims.debug_rays # enable / disable visual feedback on traced rays
        MOVE_UPDATE_THRESHOLD_VALUE_LOC = evertims.movement_threshold_loc # minimum value a listener / source must move to be updated on EVERTims client (m)
        MOVE_UPDATE_THRESHOLD_VALUE_ROT = evertims.movement_threshold_rot # minimum value a listener / source must rotate to be updated on EVERTims client (deg)

        # set debug mode
        self._evertims.setDebugMode(DEBUG_LOG)

        # self._evertims.setBufferSize(4096)

        # define EVERTs elements: room, listener and source
        # 1. reset local dicts if already filled
        self._evertims.resetObjDict()
        # (in case something changed, don't want to keep old evertims elmt instances)
        # 2. define new elements
        objects = bpy.context.scene.objects
        # add room
        obj = objects.get(evertims.room_object)
        if obj: self._evertims.addRoom(obj)
        if evertims.debug_logs: print('adding room: ', obj.name)
        # add source
        obj = objects.get(evertims.source_object)
        if obj: self._evertims.addSource(obj)
        if evertims.debug_logs: print('adding source: ', obj.name)
        # add listener
        obj = objects.get(evertims.listener_object)
        if obj: self._evertims.addListener(obj)
        if evertims.debug_logs: print('adding listener: ', obj.name)

        # get logic object
        logic_obj = bpy.context.scene.objects.get('Logic_EVERTims')

        # get room for later check
        room_obj = self._evertims.getRoom()

        # limit listener / source position updates in EVERTims Client
        self._evertims.setMovementUpdateThreshold(MOVE_UPDATE_THRESHOLD_VALUE_LOC, MOVE_UPDATE_THRESHOLD_VALUE_ROT)

        # init network connections
        self._evertims.initConnection_writeRaytracing(IP_RAYTRACING, PORT_W_RAYTRACING)
        self._evertims.initConnection_writeAuralization(IP_AURALIZATION, PORT_W_AURALIZATION)
        self._evertims.initConnection_read(IP_LOCAL, PORT_R)

        # activate raytracing
        self._evertims.activateRayTracingFeedback(DEBUG_RAYS)

        # check if evertims module is ready to start
        # print (self._evertims.isReady(), logic_obj, room_obj.material_slots)
        if self._evertims.isReady() and logic_obj:
            # print('isready', [e for e in room_obj.material_slots])
            if room_obj.material_slots:
                # print('2')
                # start EVERTims client
                if evertims.debug_logs: print ('start simulation...')
                # print('3')
                self._evertims.startClientSimulation()
                # print('4')
                return True

        print ('\n###### EVERTims SIMULATION ABORTED ###### \nYou should create at least 1 room (with an EVERTims material), 1 listener, 1 source, \nimport the EVERTims Logic object \nand define EVERTims client parameters.\n')
        return False

class EVERTimsRaytracingClient(Operator):
    """Start the Evertims raytracing client as a subprocess"""
    bl_label = "Start / Stop the EVERTims raytracing client from Blender GUI"
    bl_idname = 'evert.evertims_raytracing_client'
    bl_options = {'REGISTER'}

    _raytracing_process = None
    _raytracing_debug_log_thread = None
    _raytracing_debug_log_queue = None
    _handle_timer = None
    _raytracing_debug_thread_stop_event = None

    arg = bpy.props.StringProperty()

    @staticmethod
    def handle_add(self, context, debugEnabled):
        """
        called when starting the EVERTims raytracing client,
        starts necessary callbacks to output client logs in Blender console.
        called even if debug mode disabled, the modal then runs uselessly yet we're sure
        that the self.cancel method is called if blender is closed, hence giving us a handle to kill
        the evertims ims sub process.
        """
        # start thread for non-blocking log
        if debugEnabled:
            EVERTimsRaytracingClient._raytracing_debug_log_queue = Queue()
            EVERTimsRaytracingClient._raytracing_debug_thread_stop_event = threading.Event() # used to stop the thread
            EVERTimsRaytracingClient._raytracing_debug_log_thread = threading.Thread(target=self.enqueue_output, args=(self._raytracing_process.stdout, EVERTimsRaytracingClient._raytracing_debug_log_queue, EVERTimsRaytracingClient._raytracing_debug_thread_stop_event))
            EVERTimsRaytracingClient._raytracing_debug_log_thread.daemon = True # thread dies with the program
            EVERTimsRaytracingClient._raytracing_debug_log_thread.start()

        # start modal
        context.window_manager.modal_handler_add(self)
        EVERTimsRaytracingClient._handle_timer = context.window_manager.event_timer_add(0.075,  context.window)
        if context.scene.evertims.debug_logs: print('added evertims raytracing modal callback to draw_handler')

    @staticmethod
    def handle_remove(context):
        """
        called when terminating the EVERTims raytracing client,
        remove callbacks added in handle_add method.
        """
        # skip if somehow this runs while handle time not defined in handle_add
        if EVERTimsRaytracingClient._handle_timer is None: return
        # kill modal
        context.window_manager.event_timer_remove(EVERTimsRaytracingClient._handle_timer)
        EVERTimsRaytracingClient._handle_timer = None
        # context.window_manager.modal_handler_add(self)
        # indicate it's ok to finish log in stdout thread
        # EVERTimsRaytracingClient._raytracing_debug_log_thread.daemon = False
        if EVERTimsRaytracingClient._raytracing_debug_thread_stop_event is not None:
            EVERTimsRaytracingClient._raytracing_debug_thread_stop_event.set()
        if context.scene.evertims.debug_logs_raytracing:
            print('removed raytracing modal callback from modal stack')

    @classmethod
    def poll(cls, context):
        return context.area.type == 'VIEW_3D'

    def enqueue_output(self, out, queue, stop_event):
        """
        Based on the Queue python module, this callback runs when debug mode enabled,
        allowing non-blocking print of EVERTims raytracing client logs in Blender console.
        """
        if not stop_event.is_set():
            for line in iter(out.readline, b''):
                queue.put(line)
            out.close()
        else:
            EVERTimsRaytracingClient._raytracing_debug_log_thread.stop()
            if evertims.debug_logs_raytracing:
                print('removed raytracing client log callback from modal stack')

    def invoke(self, context, event):
        """
        Method called when button attached to local bl_idname clicked
        """
        evertims = context.scene.evertims
        addon_prefs = context.user_preferences.addons[__package__].preferences
        loadType = self.arg

        # start Evertims raytracing client (subprocess)
        if loadType == 'PLAY':

            # get launch command out of GUI properties
            # cmd = "/Users/.../evertims/bin/ims -s 3858 -a 'listener_1/127.0.0.1:3860' -v 'listener_1/localhost:3862' -d 1 -D 2 -m /Users/.../evertims/resources/materials.dat -p 'listener_1/'"
            client_cmd  = bpy.path.abspath(addon_prefs.raytracing_client_path_to_binary)
            client_cmd += " -s " + str(evertims.port_write_raytracing) # reader port
            client_cmd += " -a " + "listener_1" + "/" + evertims.ip_auralization + ":" + str(evertims.port_write_auralization)
            client_cmd += " -v " + "listener_1" + "/" + evertims.ip_local + ":" + str(evertims.port_read)
            client_cmd += " -d " + str(evertims.min_reflection_order)
            client_cmd += " -D " + str(evertims.max_reflection_order)
            client_cmd += " -p " + "listener_1/ "
            client_cmd += " -m " + bpy.path.abspath(addon_prefs.raytracing_client_path_to_matFile)

            # launch subprocess
            EVERTimsRaytracingClient._raytracing_process = subprocess.Popen(client_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=ON_POSIX)
            evertims.enable_raytracing_client = True

            # enable log in Blender console if debug mode enabled
            if evertims.debug_logs_raytracing:
                print('launch EVERTims raytracing client subprocess')
                print('command: \n', client_cmd)
            self.handle_add(self, context, evertims.debug_logs_raytracing)
            return {'RUNNING_MODAL'}

        # terminate Evertims raytracing client (subprocess)
        elif loadType == 'STOP':

            # terminate subprocess
            if self._raytracing_process: # if process has been (e.g. manually) closed since
                self._raytracing_process.terminate()
            evertims.enable_raytracing_client = False

            # terminate modal thread
            if self._handle_timer:
                if self._raytracing_debug_thread_stop_event is not None: # debug enabled
                    self.handle_remove(context)
                else:
                    self.handle_remove(context)
                if evertims.debug_logs_raytracing: print('terminate EVERTims raytracing client subprocess')

            return {'CANCELLED'}

    def modal(self, context, event):
        """
        modal method, run always, call cancel function when Blender quit / load new scene
        """
        # useful only if debug mode not enabled
        if event.type == 'TIMER' and EVERTimsRaytracingClient._raytracing_debug_log_queue is not None:
            try:
                # get line from non-blocking Queue, attached to debug-log thread
                line = EVERTimsRaytracingClient._raytracing_debug_log_queue.get_nowait() # or q.get(timeout=.1)
            except Empty: # no output to print yet
                pass
            else: # got line, ready to print
                sys.stdout.write(line.decode('utf-8'))

        return {'PASS_THROUGH'}

    def cancel(self, context):
        """
        function called when Blender quit / load new scene. Remove local callback from stack
        """
        # kill ims process if blender exit while modal still running
        if self._raytracing_process: # if process has been (e.g. manually) closed since
            self._raytracing_process.terminate()
        # remove modal
        self.handle_remove(context)

class EVERTimsAuralizationClient(Operator):
    """Start the EVERTims auralization client as a subprocess"""
    bl_label = "Start / Stop the EVERTims auralization client from Blender GUI"
    bl_idname = 'evert.evertims_auralization_client'
    bl_options = {'REGISTER'}

    _process = None

    arg = bpy.props.StringProperty()

    def invoke(self, context, event):
        """
        Method called when button attached to local bl_idname clicked
        """
        evertims = context.scene.evertims
        addon_prefs = context.user_preferences.addons[__package__].preferences
        loadType = self.arg

        # start Evertims auralization client (subprocess)
        if loadType == 'PLAY':

            # get launch command out of GUI properties
            client_cmd  = bpy.path.abspath(addon_prefs.auralization_client_path_to_binary)

            # launch subprocess
            EVERTimsAuralizationClient._process = subprocess.Popen(client_cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, close_fds=ON_POSIX)
            evertims.enable_auralization_client = True

            return {'FINISHED'}

        # terminate Evertims raytracing client (subprocess)
        elif loadType == 'STOP':

            # terminate subprocess
            if self._process: # if process has been (e.g. manually) closed since
                self._process.terminate()
            evertims.enable_auralization_client = False

            return {'CANCELLED'}

class EVERTimsUtils(Operator):
    """Miscellaneous utilities"""
    bl_label = "Mist. utils operators"
    bl_idname = 'evert.misc_utils'
    bl_options = {'REGISTER'}

    arg = bpy.props.StringProperty()

    def invoke(self, context, event):
        """
        Method called when button attached to local bl_idname clicked
        """
        evertims = context.scene.evertims
        loadType = self.arg

        # flag that mat file needs update (will happend just before next auralization session)
        if loadType == 'FLAG_MAT_UPDATE':
            evertims.mat_list_need_update = True
            return {'FINISHED'}

# ############################################################
# Un/Registration
# ############################################################

classes = (
    EVERTimsImportObject,
    EVERTimsImportText,
    EVERTimsInBge,
    EVERTimsInEditMode,
    EVERTimsRaytracingClient,
    EVERTimsAuralizationClient,
    EVERTimsUtils
    )

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)


text:
CR_JumpToNamedMVCView
=====================

**WARNING**: This plugin has been made obsolete by functionality built into CodeRush. As a result, no release is being made available for this plugin. The source will remain as an example of how to achieve this sort of functionality.

Purpose
=======
This plugin provides a new NavigationProider to help you navigate to a razor view from a controller that calls it by name.

Usage
=====

 * Start off in an MVC Controller

![](./Screenshots/JumpToNamedMVCViewCustomerController.png)

![](./Screenshots/JumpToNamedMVCViewCustomerControllerFull.png)

 * Place your caret on the name of the View being called
 * Hit Ctrl+Alt+N

![](/Screenshots/JumpToNamedMVCViewCustomerControllerJumpToView.png)

 * Choose Named MVC View
 * CodeRush transports you to the correct view.

![](./Screenshots/JumpToNamedMVCViewCustomerListView.png)

Further Configuration
=====================

You want to, you could [bind this navigation directly to a keyboard shortcut](http://community.devexpress.com/blogs/rorybecker/archive/2010/10/05/binding-keys-in-coderush.aspx).

I suggest the F12 key, since this functionality is akin to GotoDefinition.

![](./Screenshots/JumpToNamedMVCViewShorctuts.png)
![](./Screenshots/JumpToNamedMVCViewShortcutDetail.png)

Limitations
===========
This version of the navigation can only find Razor views. ie vbhtml or cshtml files.


text:
'use strict';

var fs = require('fs'),
    _ = require('lodash'),
    async = require('async'),
    onFinished = require('on-finished');

function cleanupReqFiles(req, cb) {
    if (!req.files) {
        return cb();
    }

    var files = _.chain(req.files)
             .map(function(x) { return x; })
             .flatten()
             .value();

    async.each(files, function(file, callback) {
        fs.stat(file.path, function(err, stats) {
			if (err || !stats.isFile()) {
                return callback();
            }

            fs.unlink(file.path, function(e) {
                if (e) {
                    console.error(e);
                }

                callback();
            });
        });
    });
}

module.exports = function(req, res, next) {
	res.on('error', function() {
        cleanupReqFiles(req);
	});

    onFinished(res, function () {
        cleanupReqFiles(req);
    });

    next();
};


text:
package net.glowstone.net.codec.play.entity;

import com.flowpowered.network.Codec;
import io.netty.buffer.ByteBuf;
import net.glowstone.net.message.play.entity.AttachEntityMessage;

import java.io.IOException;

public final class AttachEntityCodec implements Codec<AttachEntityMessage> {

    @Override
    public AttachEntityMessage decode(ByteBuf buf) throws IOException {
        int attached = buf.readInt();
        int holding = buf.readInt();
        return new AttachEntityMessage(attached, holding);
    }

    @Override
    public ByteBuf encode(ByteBuf buf, AttachEntityMessage message) throws IOException {
        buf.writeInt(message.getAttached());
        buf.writeInt(message.getHolding());
        return buf;
    }
}


text:
#include <linux/io.h>
#include <linux/memblock.h>

#include <asm/trampoline.h>
#include <asm/cacheflush.h>
#include <asm/pgtable.h>

unsigned char *x86_trampoline_base;

void __init setup_trampolines(void)
{
	phys_addr_t mem;
	size_t size = PAGE_ALIGN(x86_trampoline_end - x86_trampoline_start);

	/* Has to be in very low memory so we can execute real-mode AP code. */
	mem = memblock_find_in_range(0, 1<<20, size, PAGE_SIZE);
	if (mem == MEMBLOCK_ERROR)
		panic("Cannot allocate trampoline\n");

	x86_trampoline_base = __va(mem);
	memblock_x86_reserve_range(mem, mem + size, "TRAMPOLINE");

	printk(KERN_DEBUG "Base memory trampoline at [%p] %llx size %zu\n",
	       x86_trampoline_base, (unsigned long long)mem, size);

	memcpy(x86_trampoline_base, x86_trampoline_start, size);
}

/*
 * setup_trampolines() gets called very early, to guarantee the
 * availability of low memory.  This is before the proper kernel page
 * tables are set up, so we cannot set page permissions in that
 * function.  Thus, we use an arch_initcall instead.
 */
static int __init configure_trampolines(void)
{
	size_t size = PAGE_ALIGN(x86_trampoline_end - x86_trampoline_start);

	set_memory_x((unsigned long)x86_trampoline_base, size >> PAGE_SHIFT);
	return 0;
}
arch_initcall(configure_trampolines);


text:
package org.apache.camel.component.jgroups.raft.cluster;

import java.util.Optional;

import org.apache.camel.util.ObjectHelper;
import org.jgroups.protocols.raft.RAFT;
import org.jgroups.protocols.raft.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClusterRoleChangeListener implements RAFT.RoleChange {
    private static final transient Logger LOG = LoggerFactory.getLogger(ClusterRoleChangeListener.class);

    private final JGroupsRaftClusterView jgroupsRaftClusterView;

    public ClusterRoleChangeListener(JGroupsRaftClusterView jgroupsRaftClusterView) {
        ObjectHelper.notNull(jgroupsRaftClusterView, "endpoint");

        this.jgroupsRaftClusterView = jgroupsRaftClusterView;
    }

    @Override
    public void roleChanged(Role role) {
        LOG.debug("Role received {}.", role);
        switch (role) {
            case Leader:
                if (!jgroupsRaftClusterView.isMaster()) {
                    jgroupsRaftClusterView.setMaster(true);
                    jgroupsRaftClusterView.fireLeadershipChangedEvent(Optional.ofNullable(jgroupsRaftClusterView.getLocalMember()));
                }
                break;
            case Follower:
                if (jgroupsRaftClusterView.isMaster()) {
                    jgroupsRaftClusterView.setMaster(false);
                    jgroupsRaftClusterView.fireLeadershipChangedEvent(Optional.empty());
                }
                break;
            case Candidate:
                if (jgroupsRaftClusterView.isMaster()) {
                    jgroupsRaftClusterView.setMaster(false);
                    jgroupsRaftClusterView.fireLeadershipChangedEvent(Optional.empty());
                }
                break;
            default:
                LOG.error("Role {} unknown.", role);
                throw new UnsupportedOperationException("Role " + role + " unknown.");
        }
    }
}


text:
#include <aws/kinesis/model/Consumer.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Kinesis
{
namespace Model
{

Consumer::Consumer() :
    m_consumerNameHasBeenSet(false),
    m_consumerARNHasBeenSet(false),
    m_consumerStatus(ConsumerStatus::NOT_SET),
    m_consumerStatusHasBeenSet(false),
    m_consumerCreationTimestampHasBeenSet(false)
{
}

Consumer::Consumer(JsonView jsonValue) :
    m_consumerNameHasBeenSet(false),
    m_consumerARNHasBeenSet(false),
    m_consumerStatus(ConsumerStatus::NOT_SET),
    m_consumerStatusHasBeenSet(false),
    m_consumerCreationTimestampHasBeenSet(false)
{
  *this = jsonValue;
}

Consumer& Consumer::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ConsumerName"))
  {
    m_consumerName = jsonValue.GetString("ConsumerName");

    m_consumerNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ConsumerARN"))
  {
    m_consumerARN = jsonValue.GetString("ConsumerARN");

    m_consumerARNHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ConsumerStatus"))
  {
    m_consumerStatus = ConsumerStatusMapper::GetConsumerStatusForName(jsonValue.GetString("ConsumerStatus"));

    m_consumerStatusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ConsumerCreationTimestamp"))
  {
    m_consumerCreationTimestamp = jsonValue.GetDouble("ConsumerCreationTimestamp");

    m_consumerCreationTimestampHasBeenSet = true;
  }

  return *this;
}

JsonValue Consumer::Jsonize() const
{
  JsonValue payload;

  if(m_consumerNameHasBeenSet)
  {
   payload.WithString("ConsumerName", m_consumerName);

  }

  if(m_consumerARNHasBeenSet)
  {
   payload.WithString("ConsumerARN", m_consumerARN);

  }

  if(m_consumerStatusHasBeenSet)
  {
   payload.WithString("ConsumerStatus", ConsumerStatusMapper::GetNameForConsumerStatus(m_consumerStatus));
  }

  if(m_consumerCreationTimestampHasBeenSet)
  {
   payload.WithDouble("ConsumerCreationTimestamp", m_consumerCreationTimestamp.SecondsWithMSPrecision());
  }

  return payload;
}

} // namespace Model
} // namespace Kinesis
} // namespace Aws


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['stableinterface'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: image_streamer_plan_script
short_description: Manage the Image Streamer Plan Script resources.
description:
    - "Provides an interface to manage the Image Streamer Plan Script. Can create, update, and remove."
version_added: "2.3"
requirements:
    - "python >= 2.7.9"
    - "hpeOneView >= 3.1.0"
author: "Gustavo Hennig (@GustavoHennig)"
options:
    state:
        description:
            - Indicates the desired state for the Plan Script resource.
              C(present) will ensure data properties are compliant with Synergy Image Streamer.
              C(absent) will remove the resource from Synergy Image Streamer, if it exists.
              C(differences_retrieved) will retrieve the modified contents of the Plan Script as per
              the selected attributes.
        choices: ['present', 'absent', 'differences_retrieved']
        required: true
    data:
        description:
            - List with Plan Script properties and its associated states.
        required: true

extends_documentation_fragment:
    - oneview
'''

EXAMPLES = '''
- name: Create a Plan Script
  image_streamer_plan_script:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 600
    image_streamer_hostname: 172.16.101.48
    state: present
    data:
      description: "Description of this plan script"
      name: 'Demo Plan Script'
      hpProvided: False
      planType: "deploy"
      content: 'echo "test script"'
  delegate_to: localhost

- name: Update the Plan Script
  image_streamer_plan_script:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 600
    image_streamer_hostname: 172.16.101.48
    state: present
    data:
      name: 'Demo Plan Script'
      newName:  'Demo Plan Script new name'
      description: "New description"
      content: 'echo "test script changed"'
  delegate_to: localhost

- name: Retrieve the Plan Script content differences
  image_streamer_plan_script:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 600
    image_streamer_hostname: 172.16.101.48
    state: differences_retrieved
    data:
      name: 'Demo Plan Script'
      content: 'echo "test script changed 2"'
  delegate_to: localhost
- debug: var=plan_script_differences

- name: Remove the Plan Script
  image_streamer_plan_script:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 600
    image_streamer_hostname: 172.16.101.48
    state: absent
    data:
        name: 'Demo Plan Script'
  delegate_to: localhost
'''

RETURN = '''
plan_script:
    description: Has the facts about the Image Streamer Plan Script.
    returned: On state 'present', but can be null.
    type: dict

plan_script_differences:
    description: Has the facts about the modified contents of the Plan Script as per the selected attributes.
    returned: On state 'differences_retrieved'.
    type: dict
'''

from ansible.module_utils.oneview import OneViewModuleBase, OneViewModuleValueError

class PlanScriptModule(OneViewModuleBase):
    MSG_CREATED = 'Plan Script created successfully.'
    MSG_UPDATED = 'Plan Script updated successfully.'
    MSG_ALREADY_PRESENT = 'Plan Script is already present.'
    MSG_DELETED = 'Plan Script deleted successfully.'
    MSG_ALREADY_ABSENT = 'Plan Script is already absent.'
    MSG_DIFFERENCES_RETRIEVED = 'Plan Script differences retrieved successfully.'
    MSG_CONTENT_ATTRIBUTE_MANDATORY = 'Missing mandatory attribute: data.content.'

    argument_spec = dict(
        state=dict(
            required=True,
            choices=['present', 'absent', 'differences_retrieved']
        ),
        data=dict(required=True, type='dict')
    )

    def __init__(self):
        super(PlanScriptModule, self).__init__(additional_arg_spec=self.argument_spec)
        self.i3s_client = self.oneview_client.create_image_streamer_client()
        self.resource_client = self.i3s_client.plan_scripts

    def execute_module(self):

        resource = self.get_by_name(self.data['name'])
        result = {}

        if self.state == 'present':
            result = self.resource_present(resource, 'plan_script')
        elif self.state == 'absent':
            result = self.resource_absent(resource)
        elif self.state == 'differences_retrieved':
            result = self.__retrieve_differences(self.data, resource)

        return result

    def __retrieve_differences(self, data, resource):
        if 'content' not in data:
            raise OneViewModuleValueError(self.MSG_CONTENT_ATTRIBUTE_MANDATORY)

        differences = self.i3s_client.plan_scripts.retrieve_differences(resource['uri'], data['content'])
        return dict(changed=False,
                    msg=self.MSG_DIFFERENCES_RETRIEVED,
                    ansible_facts=dict(plan_script_differences=differences))

def main():
    PlanScriptModule().run()

if __name__ == '__main__':
    main()