text:
using System;
using System.Text;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Collections.Concurrent;
using VRage.Game.Components;
using Sandbox.ModAPI;
using VRage.ModAPI;
using VRage.Utils;
using Sandbox.Game.Entities;
using VRage.Game.ModAPI;
using VRage;
using VRage.Network;
using VRageMath;
using VRage.Game;
using Sandbox.Definitions;
using Sandbox.Common.ObjectBuilders;
using Ingame = Sandbox.ModAPI.Ingame;
using Sandbox.Game.Lights;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Voxels;
using Sandbox.Engine.Voxels;
using Sandbox.Game.AI;
using Sandbox.Game.Components;

using NaniteConstructionSystem.Entities;
using NaniteConstructionSystem.Extensions;
using NaniteConstructionSystem.Entities.Beacons;
using NaniteConstructionSystem.Particles;
using NaniteConstructionSystem.Settings;

namespace NaniteConstructionSystem
{
    [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)]
    public class NaniteConstructionManager : MySessionComponentBase
    {
        public static NaniteConstructionManager Instance;

        private static Dictionary<long, NaniteConstructionBlock> m_naniteBlocks;
        public static Dictionary<long, NaniteConstructionBlock> NaniteBlocks
        {
            get
            {
                if (m_naniteBlocks == null)
                    m_naniteBlocks = new Dictionary<long, NaniteConstructionBlock>();

                return m_naniteBlocks;
            }
        }

        private static Dictionary<long, IMyCubeBlock> m_projectorBlocks;
        public static Dictionary<long, IMyCubeBlock> ProjectorBlocks
        {
            get
            {
                if (m_projectorBlocks == null)
                    m_projectorBlocks = new Dictionary<long, IMyCubeBlock>();

                return m_projectorBlocks;
            }
        }

        private static HashSet<NaniteBeacon> m_beaconList;
        public static HashSet<NaniteBeacon> BeaconList
        {
            get
            {
                if (m_beaconList == null)
                    m_beaconList = new HashSet<NaniteBeacon>();

                return m_beaconList;
            }
        }

        public static NaniteSettings m_settings;
        public static NaniteSettings Settings
        {
            get { return m_settings; }
            set { m_settings = value; }
        }

        public static ParticleEffectManager m_particleManager;
        public static ParticleEffectManager ParticleManager
        {
            get
            {
                if (m_particleManager == null)
                    m_particleManager = new ParticleEffectManager();

                return m_particleManager;
            }
        }

        private static Dictionary<long, NaniteTerminalSettings> m_terminalSettings;
        public static Dictionary<long, NaniteTerminalSettings> TerminalSettings
        {
            get
            {
                if (m_terminalSettings == null)
                    m_terminalSettings = new Dictionary<long, NaniteTerminalSettings>();

                return m_terminalSettings;
            }
        }

        private static Dictionary<long, NaniteAssemblerSettings> m_assemblerSettings;
        public static Dictionary<long, NaniteAssemblerSettings> AssemblerSettings
        {
            get
            {
                if (m_assemblerSettings == null)
                    m_assemblerSettings = new Dictionary<long, NaniteAssemblerSettings>();

                return m_assemblerSettings;
            }
        }

        private static Dictionary<long, NaniteHammerTerminalSettings> m_hammerTerminalSettings;
        public static Dictionary<long, NaniteHammerTerminalSettings> HammerTerminalSettings
        {
            get
            {
                if (m_hammerTerminalSettings == null)
                    m_hammerTerminalSettings = new Dictionary<long, NaniteHammerTerminalSettings>();

                return m_hammerTerminalSettings;
            }
        }

        private static Dictionary<long, NaniteBeaconTerminalSettings> m_beaconTerminalSettings;
        public static Dictionary<long, NaniteBeaconTerminalSettings> BeaconTerminalSettings
        {
            get
            {
                if (m_beaconTerminalSettings == null)
                    m_beaconTerminalSettings = new Dictionary<long, NaniteBeaconTerminalSettings>();

                return m_beaconTerminalSettings;
            }
        }

        private static HashSet<long> m_assemblerBlocks;
        public static HashSet<long> AssemblerBlocks
        {
            get
            {
                if (m_assemblerBlocks == null)
                    m_assemblerBlocks = new HashSet<long>();

                return m_assemblerBlocks;
            }
        }

        private static NaniteConstructionManagerSync m_sync;
        public static NaniteConstructionManagerSync NaniteSync
        {
            get { return m_sync; }
        }

        private static HashSet<NaniteMining> m_miningList;
        public static HashSet<NaniteMining> MiningList
        {
            get
            {
                if (m_miningList == null)
                    m_miningList = new HashSet<NaniteMining>();

                return m_miningList;
            }
        }

        private bool m_initialize = false;
        private TerminalSettings m_terminalSettingsManager;
        private List<IMyTerminalControl> m_customControls = new List<IMyTerminalControl>();
        private IMyTerminalControl m_customAssemblerControl;
        private List<IMyTerminalControl> m_customHammerControls = new List<IMyTerminalControl>();
        private List<IMyTerminalControl> m_customBeaconControls = new List<IMyTerminalControl>();
        private List<IMyTerminalAction> m_customBeaconActions = new List<IMyTerminalAction>();
        private DateTime m_lastPlayer;
        private Action<IMyTerminalBlock> m_oldAction;

        public NaniteConstructionManager()
        {
            Instance = this;
            m_sync = new NaniteConstructionManagerSync();
            m_lastPlayer = DateTime.MinValue;

            m_terminalSettingsManager = new TerminalSettings();
        }

        public override void UpdateBeforeSimulation()
        {
            if (MyAPIGateway.Session == null)
                return;

            if (!m_initialize)
            {
                m_initialize = true;
                Initialize();
                return;
            }

            try
            {
                ProcessNaniteBlocks();
                ProcessBeaconBlocks();
                ProcessParticleEffects();
                ProcessMiningBlocks();
                //Test();
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine(string.Format("Update Error: {0}", ex.ToString()));
            }
        }

        public void Test()
        {
            if (DateTime.Now - m_lastPlayer < TimeSpan.FromSeconds(2))
                return;

            m_lastPlayer = DateTime.Now;
            var players = new List<IMyPlayer>();
            MyAPIGateway.Players.GetPlayers(players);

            foreach(var item in players)
            {
                Logging.Instance.WriteLine(string.Format("Here: {0}", item.DisplayName));
                if (item.Controller.ControlledEntity.Entity != null)
                {

                    foreach (var comp in item.Controller.ControlledEntity.Entity.Components)
                    {
                        if (comp.GetType().Name == "MyCharacterStatComponent")
                        {
                            MyCharacterStatComponent stat = comp as MyCharacterStatComponent;
                            Logging.Instance.WriteLine(string.Format("Player {0}: {1} of {2}", item.DisplayName, stat.Health.Value, stat.Health.MaxValue));

                            if (stat.Health.Value < 100)
                            {
                                MyEntityStat entityStat;
                                stat.Stats.TryGetValue(MyStringHash.GetOrCompute("Health"), out entityStat);
                                entityStat.Value = stat.Health.Value + 5;
                            }
                        }
                    }
                }
            }
        }

        private void ProcessNaniteBlocks()
        {
            foreach (var item in NaniteBlocks.ToList())
            {
                if (item.Value.ConstructionBlock == null || item.Value.ConstructionBlock.Parent == null) // || item.Value.ConstructionBlock.Parent.Physics == null)
                {
                    //Logging.Instance.WriteLine(string.Format("REMOVING Nanite Factory due to parent gone or physicless: {0}", item.Value.ConstructionBlock.EntityId));
                    //item.Value.Unload();
                    //NaniteBlocks.Remove(item.Key);
                    continue;
                }

                item.Value.Update();
            }
        }

        private void ProcessBeaconBlocks()
        {
            foreach(var item in BeaconList.ToList())
            {
                if(item.BeaconBlock.Closed || item.BeaconBlock.CubeGrid.Closed) // || item.BeaconBlock.CubeGrid.Physics == null)
                {
                    Logging.Instance.WriteLine(string.Format("REMOVING {1} Beacon: {0}", item.BeaconBlock.EntityId, item.GetType().Name));
                    item.Close();
                    continue;
                }

                item.Update();
            }
        }

        private void ProcessParticleEffects()
        {
            ParticleManager.Update();
        }

        private void ProcessMiningBlocks()
        {
            foreach(var item in MiningList.ToList())
            {
                if (item.MiningBlock.Closed || item.MiningBlock.CubeGrid.Closed)
                {
                    Logging.Instance.WriteLine(string.Format("REMOVING Mining Hammer: {0}", item.MiningBlock.EntityId));
                    item.Close();
                    continue;
                }

                if (item.MiningBlock.CubeGrid.Physics == null)
                    continue;

                item.Update();
            }
        }

        private void Initialize()
        {
            if (!Sync.IsServer)
            {
                MyAPIGateway.Entities.OnEntityAdd += Entities_OnEntityAdd;
            }

            Logging.Instance.WriteLine("Initializing Sync");
            m_sync.Initialize();

            //CleanupOldBlocks();
            Logging.Instance.WriteLine("Loading Settings");
            LoadSettings();

            MyAPIGateway.Utilities.MessageEntered += MessageEntered;

            Logging.Instance.WriteLine("Initializing Controls");
            InitializeControls();

            Logging.Instance.WriteLine("Initializing Terminal Settings Manager");
            m_terminalSettingsManager.Load();

            if(Sync.IsClient)
            {
                Logging.Instance.WriteLine("Requesting Settings");

                m_sync.SendLogin();

                Logging.Instance.WriteLine("      Requesting Blocks");
                foreach (var item in NaniteBlocks)
                {
                    m_sync.SendNeedTerminalSettings(item.Key);
                }

                Logging.Instance.WriteLine("      Requesting Assembler Settings");
                foreach (var item in AssemblerBlocks)
                {
                    m_sync.SendNeedAssemblerSettings(item);
                }

                Logging.Instance.WriteLine("      Requesting Terminal Settings");
                foreach (var item in HammerTerminalSettings)
                {
                    m_sync.SendNeedHammerTerminalSettings(item.Key);
                }

                Logging.Instance.WriteLine("      Requesting Beacon Terminal Settings");
                foreach (var item in BeaconTerminalSettings)
                {
                    m_sync.SendNeedBeaconTerminalSettings(item.Key);
                }

                Logging.Instance.WriteLine("Completed Requests");
            }

            Logging.Instance.WriteLine("Initialization Completed");
        }

        private void InitializeControls()
        {
            MyAPIGateway.TerminalControls.CustomControlGetter += CustomControlGetter;
            MyAPIGateway.TerminalControls.CustomActionGetter += CustomActionGetter;

            // --- Repair Checkbox
            var repairCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowRepair");
            repairCheck.Title = MyStringId.GetOrCompute("Repair / Construction");
            repairCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will repair or construct unbuilt blocks.");
            repairCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowRepair;
            };

            repairCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowRepair = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(repairCheck);

            // --- Projection Checkbox
            var projectionCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowProjection");
            projectionCheck.Title = MyStringId.GetOrCompute("Projection Construction");
            projectionCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will repair or construct unbuilt blocks.");
            projectionCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowProjection;
            };

            projectionCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowProjection = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(projectionCheck);

            // --- Cleanup Checkbox
            var cleanupCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowCleanup");
            cleanupCheck.Title = MyStringId.GetOrCompute("Cleanup");
            cleanupCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will cleanup floating objects, ore, components, or corpses.  It will return the objects back to the factory.");
            cleanupCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowCleanup;
            };

            cleanupCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowCleanup = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(cleanupCheck);

            // --- Deconstruction Checkbox
            var deconstructCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowDeconstruct");
            deconstructCheck.Title = MyStringId.GetOrCompute("Deconstruction");
            deconstructCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will attempt to deconstruct ships that have a deconstruction beacon on them.");
            deconstructCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowDeconstruct;
            };

            deconstructCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowDeconstruct = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(deconstructCheck);

            // --- Mining Checkbox
            var miningCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowMining");
            miningCheck.Title = MyStringId.GetOrCompute("Mining");
            miningCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will attempt to mine resources if it detects a NUHOL.");
            miningCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowMining;
            };

            miningCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowMining = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(miningCheck);

            // --- Medical Checkbox
            var medicalCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("AllowMedical");
            medicalCheck.Title = MyStringId.GetOrCompute("Medical");
            medicalCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will attempt to heal players.");
            medicalCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].AllowMedical;
            };

            medicalCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].AllowMedical = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(medicalCheck);

            // --- Max Nanites
            var maxNaniteTextBox = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlTextbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("MaxNaniteText");
            maxNaniteTextBox.Title = MyStringId.GetOrCompute("Max. Nanites (0 = unlimited)");
            maxNaniteTextBox.Tooltip = MyStringId.GetOrCompute("This is the maximum nanites that the factory will release.");
            maxNaniteTextBox.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                StringBuilder sb = new StringBuilder(TerminalSettings[x.EntityId].MaxNanites.ToString());
                return sb;
            };

            maxNaniteTextBox.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                int max = 0;
                int.TryParse(y.ToString(), out max);
                TerminalSettings[x.EntityId].MaxNanites = max;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(maxNaniteTextBox);

            // --- Use Assembler Checkbox
            var useAssemblerCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, SpaceEngineers.Game.ModAPI.Ingame.IMyOxygenFarm>("UseAssemblers");
            useAssemblerCheck.Title = MyStringId.GetOrCompute("Use Assemblers");
            useAssemblerCheck.Tooltip = MyStringId.GetOrCompute("When checked, the factory will queue component parts in marked assemblers that are attached to the factory");
            useAssemblerCheck.Getter = (x) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                return TerminalSettings[x.EntityId].UseAssemblers;
            };

            useAssemblerCheck.Setter = (x, y) =>
            {
                if (!TerminalSettings.ContainsKey(x.EntityId))
                    TerminalSettings.Add(x.EntityId, new NaniteTerminalSettings());

                TerminalSettings[x.EntityId].UseAssemblers = y;
                m_sync.SendTerminalSettings(x);
            };
            m_customControls.Add(useAssemblerCheck);

            // --- Factory checkbox in assembler
            var allowFactoryCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, Ingame.IMyAssembler>("AllowFactory");
            allowFactoryCheck.Title = MyStringId.GetOrCompute("Nanite Factory Queuing");
            allowFactoryCheck.Tooltip = MyStringId.GetOrCompute("When checked, this will allow the nanite factory to queue components for construction.");
            allowFactoryCheck.Getter = (x) =>
            {
                if (!AssemblerSettings.ContainsKey(x.EntityId))
                    AssemblerSettings.Add(x.EntityId, new NaniteAssemblerSettings());

                return AssemblerSettings[x.EntityId].AllowFactoryUsage;
            };

            allowFactoryCheck.Setter = (x, y) =>
            {
                if (!AssemblerSettings.ContainsKey(x.EntityId))
                    AssemblerSettings.Add(x.EntityId, new NaniteAssemblerSettings());

                AssemblerSettings[x.EntityId].AllowFactoryUsage = y;
                m_sync.SendAssemblerSettings(x);
            };
            m_customAssemblerControl = allowFactoryCheck;
            //MyAPIGateway.TerminalControls.AddControl<Ingame.IMyAssembler>(allowFactoryCheck);

            // --- Mining Hammer
            var separate = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, Ingame.IMyOreDetector>("Separate");
            m_customHammerControls.Add(separate);

            var oreList = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlListbox, Ingame.IMyOreDetector>("OreList");
            oreList.Title = MyStringId.GetOrCompute("Valid Ores (deselect to ignore): ");
            oreList.Multiselect = true;
            oreList.VisibleRowsCount = 8;
            oreList.ListContent = OreListContent;
            oreList.ItemSelected = OreListSelected;
            m_customHammerControls.Add(oreList);

            // --- Area Beacons
            // -- Separator
            var separateArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyProjector>("SeparateArea");
            m_customBeaconControls.Add(separateArea);

            // -- Highlight Area
            var highlightCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyProjector>("HighlightArea");
            highlightCheck.Title = MyStringId.GetOrCompute("Hightlight Area");
            highlightCheck.Tooltip = MyStringId.GetOrCompute("When checked, it will show you the area this beacon covers");
            highlightCheck.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].HighlightArea;
            };

            highlightCheck.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].HighlightArea = y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            m_customBeaconControls.Add(highlightCheck);

            // -- Allow Repair
            var areaAllowRepairCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyProjector>("AreaAllowRepair");
            areaAllowRepairCheck.Title = MyStringId.GetOrCompute("Allow Repair");
            areaAllowRepairCheck.Tooltip = MyStringId.GetOrCompute("When checked, factories will repair blocks inside the beacon area");
            areaAllowRepairCheck.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].AllowRepair;
            };

            areaAllowRepairCheck.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].AllowRepair = y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            m_customBeaconControls.Add(areaAllowRepairCheck);

            // -- Allow Repair
            var areaAllowDeconstructCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyProjector>("AreaAllowDeconstruct");
            areaAllowDeconstructCheck.Title = MyStringId.GetOrCompute("Allow Deconstruct");
            areaAllowDeconstructCheck.Tooltip = MyStringId.GetOrCompute("When checked, factories will deconstruct blocks inside the beacon area");
            areaAllowDeconstructCheck.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].AllowDeconstruction;
            };

            areaAllowDeconstructCheck.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].AllowDeconstruction = y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            m_customBeaconControls.Add(areaAllowDeconstructCheck);

            // -- Allow Projection
            var areaAllowProjectionCheck = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlCheckbox, IMyProjector>("AreaAllowProjection");
            areaAllowProjectionCheck.Title = MyStringId.GetOrCompute("Allow Projection");
            areaAllowProjectionCheck.Tooltip = MyStringId.GetOrCompute("When checked, factories will build projected blocks inside the beacon area");
            areaAllowProjectionCheck.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].AllowProjection;
            };

            areaAllowProjectionCheck.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].AllowProjection = y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            m_customBeaconControls.Add(areaAllowProjectionCheck);

            /*
            var blueprintButton = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlButton, IMyProjector>("SelectBlueprint");
            blueprintButton.Title = MyStringId.GetOrCompute("Select Blueprint ...");
            blueprintButton.Tooltip = MyStringId.GetOrCompute("Select a blueprint to project");
            blueprintButton.Action = SelectBlueprint;
            m_customBeaconControls.Add(blueprintButton);
            */

            // -- Separator
            var separateSliderArea = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSeparator, IMyProjector>("SeparateSliderArea");
            m_customBeaconControls.Add(separateSliderArea);

            // -- Height
            var heightSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("HeightSlider");
            heightSlider.Title = MyStringId.GetOrCompute("Area Height");
            heightSlider.Tooltip = MyStringId.GetOrCompute("Height of area this beacon scans");
            heightSlider.SetLimits(Settings.AreaBeaconMinSize, Settings.AreaBeaconMaxSize);
            heightSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].Height;
            };

            heightSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].Height = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            heightSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].Height.ToString() + "m");
            };

            m_customBeaconControls.Add(heightSlider);

            CreateSliderActions("Height", heightSlider, (int)Settings.AreaBeaconMinSize, (int)Settings.AreaBeaconMaxSize);

            // -- Width
            var widthSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("WidthSlider");
            widthSlider.Title = MyStringId.GetOrCompute("Area Width");
            widthSlider.Tooltip = MyStringId.GetOrCompute("Width of area this beacon scans");
            widthSlider.SetLimits(Settings.AreaBeaconMinSize, Settings.AreaBeaconMaxSize);
            widthSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].Width;
            };

            widthSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].Width = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            widthSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].Width.ToString() + "m");
            };

            m_customBeaconControls.Add(widthSlider);

            CreateSliderActions("Width", widthSlider, (int)Settings.AreaBeaconMinSize, (int)Settings.AreaBeaconMaxSize);

            // -- Depth
            var depthSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("DepthSlider");
            depthSlider.Title = MyStringId.GetOrCompute("Area Depth");
            depthSlider.Tooltip = MyStringId.GetOrCompute("Depth of area this beacon scans");
            depthSlider.SetLimits(Settings.AreaBeaconMinSize, Settings.AreaBeaconMaxSize);
            depthSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].Depth;
            };

            depthSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].Depth = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            depthSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].Depth.ToString() + "m");
            };

            m_customBeaconControls.Add(depthSlider);

            CreateSliderActions("Depth", depthSlider, (int)Settings.AreaBeaconMinSize, (int)Settings.AreaBeaconMaxSize);

            // -- OffsetX
            var offsetXSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("OffsetXSlider");
            offsetXSlider.Title = MyStringId.GetOrCompute("Area Offset X");
            offsetXSlider.Tooltip = MyStringId.GetOrCompute("X Offset of area this beacon scans");
            offsetXSlider.SetLimits(-((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));
            offsetXSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].OffsetX;
            };

            offsetXSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].OffsetX = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            offsetXSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].OffsetX.ToString() + "m");
            };

            m_customBeaconControls.Add(offsetXSlider);

            CreateSliderActions("OffsetX", offsetXSlider, -((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));

            // -- OffsetY
            var offsetYSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("OffsetYSlider");
            offsetYSlider.Title = MyStringId.GetOrCompute("Area Offset Y");
            offsetYSlider.Tooltip = MyStringId.GetOrCompute("Y Offset of area this beacon scans");
            offsetYSlider.SetLimits(-((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));
            offsetYSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].OffsetY;
            };

            offsetYSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].OffsetY = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            offsetYSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].OffsetY.ToString() + "m");
            };

            m_customBeaconControls.Add(offsetYSlider);

            CreateSliderActions("OffsetY", offsetYSlider, -((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));

            // -- OffsetZ
            var offsetZSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("OffsetZSlider");
            offsetZSlider.Title = MyStringId.GetOrCompute("Area Offset Z");
            offsetZSlider.Tooltip = MyStringId.GetOrCompute("Z Offset of area this beacon scans");
            offsetZSlider.SetLimits(-((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));
            offsetZSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].OffsetZ;
            };

            offsetZSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].OffsetZ = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            offsetZSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].OffsetZ.ToString() + "m");
            };

            m_customBeaconControls.Add(offsetZSlider);

            CreateSliderActions("OffsetZ", offsetZSlider, -((int)(Settings.AreaBeaconMaxSize)), ((int)(Settings.AreaBeaconMaxSize)));

            // -- RotationX
            var rotationXSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("RotationXSlider");
            rotationXSlider.Title = MyStringId.GetOrCompute("Area Rotation X");
            rotationXSlider.Tooltip = MyStringId.GetOrCompute("X Rotation of area this beacon scans");
            rotationXSlider.SetLimits(0, 359);
            rotationXSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].RotationX;
            };

            rotationXSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].RotationX = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            rotationXSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].RotationX.ToString() + "°");
            };

            m_customBeaconControls.Add(rotationXSlider);

            CreateSliderActions("RotationX", rotationXSlider, 0, 359, true);

            // -- RotationY
            var rotationYSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("RotationYSlider");
            rotationYSlider.Title = MyStringId.GetOrCompute("Area Rotation Y");
            rotationYSlider.Tooltip = MyStringId.GetOrCompute("Y Rotation of area this beacon scans");
            rotationYSlider.SetLimits(0, 359);
            rotationYSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].RotationY;
            };

            rotationYSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].RotationY = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            rotationYSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].RotationY.ToString() + "°");
            };

            m_customBeaconControls.Add(rotationYSlider);

            CreateSliderActions("RotationY", rotationYSlider, 0, 359, true);

            // -- RotationZ
            var rotationZSlider = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlSlider, IMyProjector>("RotationZSlider");
            rotationZSlider.Title = MyStringId.GetOrCompute("Area Rotation Z");
            rotationZSlider.Tooltip = MyStringId.GetOrCompute("Z Rotation of area this beacon scans");
            rotationZSlider.SetLimits(0, 359);
            rotationZSlider.Getter = (x) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                return BeaconTerminalSettings[x.EntityId].RotationZ;
            };

            rotationZSlider.Setter = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                BeaconTerminalSettings[x.EntityId].RotationZ = (int)y;
                m_sync.SendBeaconTerminalSettings(x.EntityId);
            };

            rotationZSlider.Writer = (x, y) =>
            {
                if (!BeaconTerminalSettings.ContainsKey(x.EntityId))
                    BeaconTerminalSettings.Add(x.EntityId, new NaniteBeaconTerminalSettings());

                y.Append(BeaconTerminalSettings[x.EntityId].RotationZ.ToString() + "°");
            };

            m_customBeaconControls.Add(rotationZSlider);
            CreateSliderActions("RotationZ", rotationZSlider, 0, 359, true);
        }

        private void CreateSliderActions(string sliderName, IMyTerminalControlSlider slider, int minValue, int maxValue, bool wrap = false)
        {
            var heightSliderActionInc = MyAPIGateway.TerminalControls.CreateAction<IMyProjector>(string.Format("{0}SliderAction_Increase", sliderName));
            heightSliderActionInc.Name = new StringBuilder(string.Format("{0} Increase", sliderName));
            heightSliderActionInc.Icon = @"Textures\GUI\Icons\Actions\Increase.dds";
            heightSliderActionInc.Enabled = (x) => true;
            heightSliderActionInc.Action = (x) =>
            {
                if (slider.Getter(x) < maxValue)
                    slider.Setter(x, slider.Getter(x) + 1);
                else if (wrap)
                    slider.Setter(x, minValue);
            };
            m_customBeaconActions.Add(heightSliderActionInc);

            var heightSliderActionDec = MyAPIGateway.TerminalControls.CreateAction<IMyProjector>(string.Format("{0}SliderAction_Decrease", sliderName));
            heightSliderActionDec.Name = new StringBuilder(string.Format("{0} Decrease", sliderName));
            heightSliderActionDec.Icon = @"Textures\GUI\Icons\Actions\Decrease.dds";
            heightSliderActionDec.Enabled = (x) => true;
            heightSliderActionDec.Action = (x) =>
            {
                if (slider.Getter(x) > minValue)
                    slider.Setter(x, slider.Getter(x) - 1);
                else if (wrap)
                    slider.Setter(x, maxValue);
            };
            m_customBeaconActions.Add(heightSliderActionDec);
        }

        private void SelectBlueprint(IMyTerminalBlock block)
        {
            m_oldAction(block);
        }

        private void OreListSelected(IMyTerminalBlock block, List<MyTerminalControlListBoxItem> list)
        {
            if (!HammerTerminalSettings.ContainsKey(block.EntityId))
                HammerTerminalSettings.Add(block.EntityId, new NaniteHammerTerminalSettings(true));

            HammerTerminalSettings[block.EntityId].SelectedOres.Clear();
            foreach (var item in list)
            {
                HammerTerminalSettings[block.EntityId].SelectedOres.Add(item.Text.ToString());
            }

            m_sync.SendHammerTerminalSettings(block.EntityId);
            block.RefreshCustomInfo();

            // Trigger a refresh
            var detector = block as Ingame.IMyOreDetector;
            var action = detector.GetActionWithName("BroadcastUsingAntennas");
            action.Apply(block);
            action.Apply(block);
        }

        private void OreListContent(IMyTerminalBlock block, List<MyTerminalControlListBoxItem> list, List<MyTerminalControlListBoxItem> selected)
        {
            var miningItem = MiningList.FirstOrDefault(x => x.MiningBlock == block);
            if (miningItem == null)
                return;

            foreach(var item in MyDefinitionManager.Static.GetVoxelMaterialDefinitions().Select(x => x.MinedOre).Distinct())
            {
                MyTerminalControlListBoxItem listItem = new MyTerminalControlListBoxItem(MyStringId.GetOrCompute(item), MyStringId.GetOrCompute(item), null);
                list.Add(listItem);
            }

            if (!HammerTerminalSettings.ContainsKey(block.EntityId))
                HammerTerminalSettings.Add(block.EntityId, new NaniteHammerTerminalSettings(true));

            var oreList = HammerTerminalSettings[block.EntityId];
            foreach(var item in oreList.SelectedOres)
            {
                var listItem = list.FirstOrDefault(x => x.Text.ToString() == item);
                if(listItem != null)
                {
                    selected.Add(listItem);
                }
            }
        }

        private void CustomActionGetter(IMyTerminalBlock block, List<IMyTerminalAction> actions)
        {
            if (block.BlockDefinition.SubtypeName == "LargeNaniteAreaBeacon")
            {
                actions.Clear();
                actions.AddRange(m_customBeaconActions);
                return;
            }
        }

        private void CustomControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls)
        {
            if(block.BlockDefinition.SubtypeName == "LargeNaniteAreaBeacon")
            {
                if (m_oldAction == null)
                {
                    IMyTerminalControlButton button = null;
                    foreach (var item in controls)
                    {
                        if (item.Id == "Blueprint")
                        {
                            button = item as IMyTerminalControlButton;
                            m_oldAction = button.Action;
                        }
                    }
                }

                controls.RemoveRange(controls.Count - 17, 16);
                controls.AddRange(m_customBeaconControls);
                return;
            }

            if(block.BlockDefinition.TypeId == typeof(MyObjectBuilder_Assembler))
            {
                controls.Add(m_customAssemblerControl);
                return;
            }

            if(block.BlockDefinition.SubtypeName == "NaniteUltrasonicHammer")
            {
                controls.RemoveAt(controls.Count - 1);
                controls.RemoveAt(controls.Count - 1);
                foreach (var item in m_customHammerControls)
                    controls.Add(item);

                return;
            }

            if (!(block.BlockDefinition.SubtypeName == "LargeNaniteFactory"))
                return;

            foreach (var item in m_customControls)
                controls.Add(item);
        }

        private void MessageEntered(string messageText, ref bool sendToOthers)
        {
            if(messageText.ToLower() == "/nanite")
            {
                string message = @"05/02/2017
- Fixed issues from not being updated in awhile.
- Fixed Projections not building properly.
- Fixed Mining Nanites not properly removing voxels.
- Added area beacons.  Area beacons allow you to setup construction, deconstruction and projection zones.  Ships inside the area created by these beacons will be repaired, deconstructed or
  projections will be built.  (For now, projector must be inside of area beacon zone).
- Updated and fixed models.

6/21/2016
- Added Medical Nanites.  These nanites will heal injured astronauts that are within 300m of the factory.

6/07/2016
- Added Mining Nanites
- Added Nanite Ultrasonic Hammer Ore Locator (NUHOL).  This is used for nanites to locate ore to mine.  Hammers must be placed inside voxels to function.  Their range by default are 20m radius x 100m length (Cylinder pointing down from the bottom of the NUHOL).
- Updated settings
- Fixed a few settings issue

05/29/2016
- Added projection beacon
- Added controls to the Nanite Factory terminal screen
- Added the ability for the factory to queue required components in attached assemblers
- Added controls to assemblers to allow factories to queue items in them

05/10/2016
- Added upgrades for functionality.  Factory functionality now requires upgrades.  Each upgrade adds 3 nanites of that type.  Each factory can have up to 8 upgrades.  Upgrade slots are next to conveyor ports on sides.
- Added a bunch of new settings
- Added repair beacon which allows ships to be repaired remotely
- Added speed upgrade - each upgrade adds 5m/s to nanites as well as dropping min travel time by 1s
- Added power upgrade - each upgrade reduces power usage by 2MW
";
                MyAPIGateway.Utilities.ShowMissionScreen("Nanite Control Factory", "Update", "", message);
                sendToOthers = false;
            }
        }

        private void LoadSettings()
        {
            try
            {
                m_settings = NaniteSettings.Load();

                var def = MyDefinitionManager.Static.GetCubeBlockDefinition(new MyDefinitionId(typeof(MyObjectBuilder_OxygenFarm), "LargeNaniteFactory"));
                foreach (var item in def.Components)
                {
                    item.Count = (int)((float)item.Count * m_settings.FactoryComponentMultiplier);
                    if (item.Count < 1)
                        item.Count = 1;
                }

                foreach (var item in MyDefinitionManager.Static.GetAllDefinitions())
                {
                    if (item.Id.TypeId == typeof(MyObjectBuilder_UpgradeModule) && item.Id.SubtypeName.Contains("Nanite"))
                    {
                        MyCubeBlockDefinition cubeDef = (MyCubeBlockDefinition)item;
                        foreach (var component in cubeDef.Components)
                        {
                            component.Count = (int)((float)component.Count * m_settings.UpgradeComponentMultiplier);
                            if (component.Count < 1)
                                component.Count = 1;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Logging.Instance.WriteLine(string.Format("LoadSettings error: {0}", ex.ToString()));
            }
        }

        private void CleanupOldBlocks()
        {
            HashSet<IMyEntity> grids = new HashSet<IMyEntity>();
            HashSet<IMyCubeGrid> gridsToRemove = new HashSet<IMyCubeGrid>();
            MyAPIGateway.Entities.GetEntities(grids, x => x is IMyCubeGrid);
            foreach(var item in grids)
            {
                if(((IMyCubeGrid)item).DisplayName == "SmallNaniteWelderCube")
                {
                    gridsToRemove.Add((IMyCubeGrid)item);
                }
            }

            foreach (var item in gridsToRemove)
                item.Close();
        }

        /// <summary>
        /// This is required to remove blocks that are supposed to not exist on the clients.  Clients don't need actual welders as welding
        /// happen on the server.  (This is obsolete, but leaving for now)
        /// </summary>
        /// <param name="obj"></param>
        private void Entities_OnEntityAdd(IMyEntity obj)
        {
            if(obj is IMyCubeGrid)
            {
                MyCubeGrid grid = (MyCubeGrid)obj;
                if(grid.DisplayName.Contains("SmallNaniteToolCube"))
                {
                    Logging.Instance.WriteLine("Deleting welder");
                    grid.PositionComp.Scale = 0.0001f;

                    if (grid.Physics != null)
                        grid.Physics.Enabled = false;

                    if (!obj.Closed)
                        obj.Close();
                }
                /*
                foreach (var item in grid.GetBlocks())
                {
                    IMySlimBlock slimBlock = (IMySlimBlock)item;
                    if (slimBlock.FatBlock == null)
                        continue;

                    IMyCubeBlock block = (IMyCubeBlock)slimBlock.FatBlock;
                    if (block.BlockDefinition.SubtypeName.Contains("NaniteShipWelder"))
                    {
                        if(!obj.Closed)
                            obj.Close();

                        return;
                    }
                }
                */
            }
        }

        public static List<NaniteConstructionBlock> GetConstructionBlocks(IMyCubeGrid grid)
        {
            List<IMyCubeGrid> gridList = GridHelper.GetGridGroup(grid);
            List<NaniteConstructionBlock> blockList = new List<NaniteConstructionBlock>();

            foreach(var item in NaniteBlocks)
            {
                if(gridList.Contains(item.Value.ConstructionBlock.CubeGrid))
                {
                    if(!blockList.Contains(item.Value))
                        blockList.Add(item.Value);
                }
            }

            return blockList;
        }

        protected override void UnloadData()
        {
            m_sync.Unload();

            MyAPIGateway.Utilities.MessageEntered -= MessageEntered;
            MyAPIGateway.Entities.OnEntityAdd -= Entities_OnEntityAdd;

            NaniteBlocks.Clear();
            ProjectorBlocks.Clear();
            AssemblerBlocks.Clear();

            foreach (var item in BeaconList.ToList())
                item.Close();

            BeaconList.Clear();

            foreach (var item in MiningList.ToList())
                item.Close();

            MiningList.Clear();

            Logging.Instance.Close();

            //if(Logging.Instance != null)
            //    Logging.Instance.Close();
        }

        public override void SaveData()
        {
            m_terminalSettingsManager.Save();
        }
    }
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview This implements a table header.
 */

cr.define('cr.ui.table', function() {
  /** @const */ var TableSplitter = cr.ui.TableSplitter;

  /**
   * Creates a new table header.
   * @param {Object=} opt_propertyBag Optional properties.
   * @constructor
   * @extends {HTMLDivElement}
   */
  var TableHeader = cr.ui.define('div');

  TableHeader.prototype = {
    __proto__: HTMLDivElement.prototype,

    table_: null,

    /**
     * Initializes the element.
     */
    decorate: function() {
      this.className = 'table-header';

      this.headerInner_ = this.ownerDocument.createElement('div');
      this.headerInner_.className = 'table-header-inner';
      this.appendChild(this.headerInner_);
      this.addEventListener('touchstart',
          this.handleTouchStart_.bind(this), false);
    },

    /**
     * Updates table header width. Header width depends on list having a
     * vertical scrollbar.
     */
    updateWidth: function() {
      // Header should not span over the vertical scrollbar of the list.
      var list = this.table_.querySelector('list');
      this.headerInner_.style.width = list.clientWidth + 'px';
    },

    /**
     * Resizes columns.
     */
    resize: function() {
      var cm = this.table_.columnModel;

      var headerCells = this.querySelectorAll('.table-header-cell');
      if (headerCells.length != cm.size) {
        this.redraw();
        return;
      }

      for (var i = 0; i < cm.size; i++) {
        headerCells[i].style.width = cm.getWidth(i) + 'px';
      }
      this.placeSplitters_(this.querySelectorAll('.table-header-splitter'));
    },

    batchCount_: 0,

    startBatchUpdates: function() {
      this.batchCount_++;
    },

    endBatchUpdates: function() {
      this.batchCount_--;
      if (this.batchCount_ == 0)
        this.redraw();
    },

    /**
     * Redraws table header.
     */
    redraw: function() {
      if (this.batchCount_ != 0)
        return;

      var cm = this.table_.columnModel;
      var dm = this.table_.dataModel;

      this.updateWidth();
      this.headerInner_.textContent = '';

      if (!cm || ! dm) {
        return;
      }

      for (var i = 0; i < cm.size; i++) {
        var cell = this.ownerDocument.createElement('div');
        cell.style.width = cm.getWidth(i) + 'px';
        cell.className = 'table-header-cell';
        if (dm.isSortable(cm.getId(i)))
          cell.addEventListener('click',
                                this.createSortFunction_(i).bind(this));

        cell.appendChild(this.createHeaderLabel_(i));
        this.headerInner_.appendChild(cell);
      }
      this.appendSplitters_();
    },

    /**
     * Appends column splitters to the table header.
     */
    appendSplitters_: function() {
      var cm = this.table_.columnModel;
      var splitters = [];
      for (var i = 0; i < cm.size; i++) {
        // splitter should use CSS for background image.
        var splitter = new TableSplitter({table: this.table_});
        splitter.columnIndex = i;
        splitter.addEventListener('dblclick',
                              this.handleDblClick_.bind(this, i));

        this.headerInner_.appendChild(splitter);
        splitters.push(splitter);
      }
      this.placeSplitters_(splitters);
    },

    /**
     * Place splitters to right positions.
     * @param {Array.<HTMLElement>|NodeList} splitters Array of splitters.
     */
    placeSplitters_: function(splitters) {
      var cm = this.table_.columnModel;
      var place = 0;
      for (var i = 0; i < cm.size; i++) {
        place += cm.getWidth(i);
        splitters[i].style.webkitMarginStart = place + 'px';
      }
    },

    /**
     * Renders column header. Appends text label and sort arrow if needed.
     * @param {number} index Column index.
     */
    createHeaderLabel_: function(index) {
      var cm = this.table_.columnModel;
      var dm = this.table_.dataModel;

      var labelDiv = this.ownerDocument.createElement('div');
      labelDiv.className = 'table-header-label';

      if (cm.isEndAlign(index))
        labelDiv.style.textAlign = 'end';
      var span = this.ownerDocument.createElement('span');
      span.appendChild(cm.renderHeader(index, this.table_));
      span.style.padding = '0';

      if (dm) {
        if (dm.sortStatus.field == cm.getId(index)) {
          if (dm.sortStatus.direction == 'desc')
            span.className = 'table-header-sort-image-desc';
          else
            span.className = 'table-header-sort-image-asc';
        }
      }
      labelDiv.appendChild(span);
      return labelDiv;
    },

    /**
     * Creates sort function for given column.
     * @param {number} index The index of the column to sort by.
     */
    createSortFunction_: function(index) {
      return function() {
        this.table_.sort(index);
      }.bind(this);
    },

    /**
     * Handles the touchstart event. If the touch happened close enough
     * to a splitter starts dragging.
     * @param {Event} e The touch event.
     */
    handleTouchStart_: function(e) {
      e = /** @type {TouchEvent} */ (e);
      if (e.touches.length != 1)
        return;
      var clientX = e.touches[0].clientX;

      var minDistance = TableHeader.TOUCH_DRAG_AREA_WIDTH;
      var candidate;

      var splitters = this.querySelectorAll('.table-header-splitter');
      for (var i = 0; i < splitters.length; i++) {
        var r = splitters[i].getBoundingClientRect();
        if (clientX <= r.left && r.left - clientX <= minDistance) {
          minDistance = r.left - clientX;
          candidate = splitters[i];
        }
        if (clientX >= r.right && clientX - r.right <= minDistance) {
          minDistance = clientX - r.right;
          candidate = splitters[i];
        }
      }
      if (candidate)
        candidate.startDrag(clientX, true);
      // Splitter itself shouldn't handle this event.
      e.stopPropagation();
    },

    /**
     * Handles the double click on a column separator event.
     * Ajusts column width.
     * @param {number} index Column index.
     * @param {Event} e The double click event.
     */
    handleDblClick_: function(index, e) {
     this.table_.fitColumn(index);
    }
  };

  /**
   * The table associated with the header.
   * @type {cr.ui.Table}
   */
  cr.defineProperty(TableHeader, 'table');

  /**
   * Rectangular area around the splitters sensitive to touch events
   * (in pixels).
   */
  TableHeader.TOUCH_DRAG_AREA_WIDTH = 30;

  return {
    TableHeader: TableHeader
  };
});

redpajama_set_name: RedPajamaGithub


text:
menu-title:  ASF Homepage
menu-weight: 1
location:    http://www.apache.org/
---


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::BaseAge::BaseAge

=cut

=head1 SYNOPSIS

=cut

=head1 DESCRIPTION

=cut

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::RunnableDB::BaseAge::BaseAge;

use strict;
use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
use Bio::EnsEMBL::Variation::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Utils::Exception qw(throw warning info);

=head2 fetch_input

    Title   :   fetch_input
    Usage   :   $self->fetch_input
    Function:
    Returns :   none
    Args    :   none

=cut

sub fetch_input {
  my( $self) = @_;

  my $mlss_adaptor = $self->compara_dba->get_MethodLinkSpeciesSetAdaptor;
  my $mlss = $mlss_adaptor->fetch_by_dbID($self->param('mlss_id'));

  $self->param('mlss', $mlss);

  my $seq_region = $self->param('seq_region');

  my $species = $self->param('species');

  my $genome_db_adaptor = $self->compara_dba->get_GenomeDBAdaptor;
  my $genome_db = $genome_db_adaptor->fetch_by_registry_name($species);

  $genome_db->db_adaptor->dbc->disconnect_when_inactive(1);
  $self->param('ref_genome_db', $genome_db);

  my $slice_adaptor = $genome_db->db_adaptor->get_SliceAdaptor;

  throw("Registry configuration file has no data for connecting to <$species>") if (!$slice_adaptor);

  my $slice = $slice_adaptor->fetch_by_region('toplevel', $seq_region);
  throw("No Slice can be created on seq_region $seq_region") if (!$slice);

  $self->param('slice', $slice);

  my $dnafrag = $self->compara_dba->get_DnaFragAdaptor->fetch_by_Slice($slice);
  $self->param('dnafrag', $dnafrag);

  print "mlss " . $mlss->dbID . " seq_region $seq_region $species\n" if ($self->debug);

  #load variation database
  my $reg = "Bio::EnsEMBL::Registry";
  $reg->load_registry_from_url($self->param('variation_url'));

  #get adaptor to VariationFeature object
  my $vf_adaptor = $reg->get_adaptor($species, 'variation', 'variationfeature');
  $self->param('vf_adaptor', $vf_adaptor);

  #Check bed_dir ends in a final /
  unless ($self->param('bed_dir') =~ /\/$/) {
      $self->param('bed_dir', ($self->param('bed_dir')."/"));
  }

  return 1;
}

sub write_output {
  my $self = shift;

  $self->base_age();
#  $self->quick_base_age();
  return 1;
}

sub base_age {
    my ($self) = @_;
    my $gap = "-"; #gap character

    my $mlss = $self->param('mlss');
    my $slice = $self->param('slice');
    my $dnafrag = $self->param('dnafrag');
    my $seq_region = $self->param('seq_region');
    my $name_mode = $self->param('name'); #can be either "name" or "node_id"

    #Check we have a valid name_mode ('name' or 'node_id')
    unless ($name_mode eq "name" || $name_mode eq "node_id") {
        throw("name_mode must either be 'name' or 'node_id', not $name_mode");
    }

    #
    my $compara_dba = new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(-url=>$self->param('compara_url'));
    my $gat_adaptor = $compara_dba->get_GenomicAlignTreeAdaptor;
    # Fetching all the GenomicAlignTrees corresponding to this Slice:
    my $genomic_align_trees =
      $gat_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice($mlss, $slice);
#      $gat_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice($mlss, $slice, undef, undef, 1);

    print "Number of trees " . @$genomic_align_trees . "\n" if ($self->debug);

    my $ref_genome_db = $self->param('ref_genome_db');
    #create tag name
    my $gdb_name = $ref_genome_db->get_short_name;

    #return clade of this species and all the species in this clade (as genome_db_ids)
    my $clade = $compara_dba->get_NCBITaxonAdaptor->fetch_node_by_taxon_id($self->param('clade_taxon_id'))->scientific_name();
    my $all_clade_species_name = {map {$_->get_short_name => 1} @{ $compara_dba->get_GenomeDBAdaptor->fetch_all_by_ancestral_taxon_id($self->param('clade_taxon_id')) } };

    print "CLADE $clade\n" if ($self->debug);

    #generate bed_file location
    my $bed_file = $self->param('bed_dir') . $ref_genome_db->get_short_name . "_ages_" . $mlss->dbID . "_" . $seq_region . ".bed";
    open (BED, ">$bed_file") || die "ERROR writing ($bed_file) file\n";

    foreach my $gat (@$genomic_align_trees) {
        my $tree_string = $gat->newick_format('simple');
        print "$tree_string\n" if ($self->debug);

        my @aligned_seq;
        my $ancestral_seqs;
        my $genome_dbs;
        my $ref_node;

        my $depth = 0;
        my $clade_age = 0;
        my $ref_start;

        #Only expect a single genomic_align for EPO alignments
        my $reference_node = $gat->reference_genomic_align_node;
        my $ref_genomic_align = $gat->reference_genomic_align;
        @aligned_seq = split(//,$ref_genomic_align->aligned_sequence);
        $ref_start = $ref_genomic_align->dnafrag_start unless $ref_start;

        #Get snps
        my $snp_list = $self->get_snps($ref_genomic_align->get_Slice);
        if ($snp_list) {
            print "Number of snps " . (scalar keys %$snp_list) . "\n" if ($self->debug);
        }
        my $ancestors = $reference_node->get_all_ancestors;
        my $max_age = @$ancestors;

        print "ROOT " . $reference_node->distance_to_root . "\n" if ($self->debug);
        my $root_distance = $reference_node->distance_to_root ;

        foreach my $this_node (@$ancestors) {
            print "node " . $this_node->name . "\n" if ($self->debug);
            print "node " . $this_node->node_id . " " . $this_node->name . " node " . $this_node->distance_to_node($reference_node) . " parent " . $this_node->distance_to_parent . " " . ($this_node->distance_to_node($reference_node)/$root_distance) . "\n" if ($self->debug);

            #expect only a single genomic_align for an ancestor
            my $genomic_aligns = $this_node->get_all_genomic_aligns_for_node;
            if (@$genomic_aligns > 1) {
                print "Warning! More than one ancestral genomic_align\n";
            }
            my $genomic_align = $genomic_aligns->[0];

            #Store the sequence of all ancestral nodes containing this species
            my $ancestral_seq;
            %$ancestral_seq = (name => $this_node->name,
                               node_id => $this_node->node_id,
                               age => $this_node->distance_to_node($reference_node),
                               aligned_seq => [split(//,$genomic_align->aligned_sequence)]);
            push @$ancestral_seqs, $ancestral_seq;

            #Find depth of clade
            unless ($clade_age) {
                #split node name into constitutent species
                my @node_names = split "-", $this_node->name;
                foreach my $node_name (@node_names) {
                    $node_name =~ s/(\w*)\[\d+\]{0,1}/$1/;
                    #stop when find a name that is not in the clade
                    unless ($all_clade_species_name->{$node_name}) {
                        $clade_age=$depth;
                        print "SET depth $depth $node_name\n" if ($self->debug);
                        last;
                    }
                }
            }
            $depth++;
        }
        #If $clade_age has not been set, all the ancestors must be in this clade so set to $max_age
        $clade_age = $max_age unless ($clade_age);
        print "Clade age $clade_age max_age $max_age ref_start=$ref_start\n" if ($self->debug);

        my $base = $ref_start;

        #Compare ref sequence with ancestral nodes to find the first difference
        for (my $i = 0; $i < @aligned_seq; $i++) {
            next if ($aligned_seq[$i] eq $gap); #skip gaps in ref sequence
            my $age = 0;
            my $node_distance;
            my $clade_name = $gdb_name;
            my $node_id = $reference_node->node_id; #default to reference node_id
            foreach my $ancestral_seq (@$ancestral_seqs) {

                #Skip over any ancestors which are gaps
                if ($ancestral_seq->{aligned_seq}[$i] ne $gap) {
                    if ($aligned_seq[$i] eq $ancestral_seq->{aligned_seq}[$i]) {
                        #ref and ancestor are the same, continue
                        #print "SAME " . ($i+1) . " $base " . $aligned_seq[$i] . " " . $ancestral_seq->{aligned_seq}[$i]. " " . $ancestral_seq->{name} . "\n";
                        $clade_name = $ancestral_seq->{name};
                        $node_id = $ancestral_seq->{node_id};
                        $node_distance = $ancestral_seq->{age};
                    } else {
                        #Found a difference between ref and ancestor. Stop
                        #print "DIFF " . ($i+1) . " $base " . $aligned_seq[$i] . " " . $ancestral_seq->{aligned_seq}[$i]. " " . $ancestral_seq->{name} . "\n";
                        last;
                    }
                }
                $age++;
            }
            print "age=$age $node_distance $clade_name\n" if ($self->debug);

            my $specificity;
            if ($age < $max_age) {

                #store the ratio of branch length to ancestor / branch length to root. The score field of a bed file should be between 0 and 1000.
                my $normalised_age = int((($node_distance/$root_distance)*1000)+0.5);
                my $rgb;
                my $shade = int($normalised_age*256/1000);
                #Ensure the BED score is larger than 0 for display purposes
                $normalised_age = 1 if ($normalised_age < 1);

                #Any base on a snp has an age of -1
                if ($snp_list->{$base}) {
                    $age = -1;
                    $specificity = 'POPULATION';
                    $rgb = "255,127,0"; #orange
                } elsif ($age == 0) {
                    $specificity = 'SPECIES';
                    $rgb = "255,0,0"; #red
                } elsif ($age <= $clade_age) {
                    $specificity = 'CLADE';
                    $rgb = "$shade,$shade,255"; #shades of blue
                } else {
                    $specificity = 'OTHER';
                    $rgb = "$shade,$shade,$shade";
                }

                my $name_field;
                if ($name_mode eq "name") {
                    $name_field = $clade_name;
                } else {
                    $name_field = $node_id;
                }
                printf BED "chr%s\t%d\t%d\t%s\t%d\t%s\n", $seq_region, ($base-1), $base, $name_field, $normalised_age, $rgb;
            }

            $base++;
        }
        $gat->release_tree;
    }
    close BED;

    #Do not sort here in case the sort command fails, which means having to rerun the entire job
    #my $sorted_bed_file = sort_bed($bed_file);
    my $output;
    #%$output = ('bed_files' => $sorted_bed_file);
    %$output = ('bed_files' => $bed_file);
    $self->dataflow_output_id($output, 2);
}

#Get all snps
sub get_snps {
    my ($self, $slice) = @_;

    my $snp_list;
    my $vf_adaptor = $self->param('vf_adaptor');

    return $snp_list unless ($vf_adaptor);
    my $vfs = $vf_adaptor->fetch_all_by_Slice($slice); #return ALL variations defined in $slice
    my $frags;

    foreach my $vf (@{$vfs}){
        #print "TYPE " . $vf->class_SO_term . "\n";
        #print "  Variation: ", $vf->variation_name, " with alleles ", $vf->allele_string . " class=" . $vf->class_SO_term . " in chromosome ", $slice->seq_region_name, " and position ", $vf->start,"-",$vf->end, " strand=", $vf->strand, "\n";
        if ($vf->class_SO_term eq "SNV") {
            #check start = end
            if ($vf->seq_region_start == $vf->seq_region_end) {
                $snp_list->{$vf->seq_region_start} = 1;
            } else {
                print "Ignore case where snp start " . $vf->seq_region_start . " does not equal snp end " . $vf->seq_region_end . "\n";
            }
        }
    }
    return $snp_list;
}

#use for debugging the pipeline only
sub quick_base_age {
    my ($self) = @_;

    my $seq_region = $self->param('seq_region');
    my $bed_file = $self->param('bed_dir') . "Test_ages_" . $seq_region . ".bed";

    open (BED, ">$bed_file") || die "ERROR writing ($bed_file) file\n";
    my $base = 123;
    my $node_id = 61900000001;
    my $normalised_age = 500;
    my $strand = "+";
    my $rgb = "255,255,255";

    printf BED "chr%s\t%d\t%d\t%s\t%d\t%s\t%d\t%d\t%s\n", $seq_region, ($base-1), $base, $node_id, $normalised_age, $strand, 0, 0, $rgb;

    close(BED);
    my $output;
    %$output = ('bed_files' => $bed_file);
    $self->dataflow_output_id($output, 2);

}

1;


text:
package org.adeptnet.maven.wagon.providers.http;

import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class Nameserver {

    public Nameserver() {
    }

    public String[] lookup(final String fqdn, final String type) throws NamingException {

        final Attributes atrs = getInitialContext().getAttributes(fqdn, new String[]{type});
        final NamingEnumeration<? extends Attribute> naming_enum = atrs.getAll();
        final List<String> res = new ArrayList<>();
        while (naming_enum.hasMoreElements()) {
            Attribute atr = naming_enum.nextElement();
            for (int j = 0; j < atr.size(); ++j) {
                res.add((String) atr.get(j));
            }
        }
        return res.toArray(new String[]{});
    }

    private DirContext makeDirContext() throws NamingException {
        final java.util.Hashtable<String, Object> env = new java.util.Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        return new InitialDirContext(env);
    }

    private DirContext getInitialContext() throws NamingException {
        if (ictx != null) {
            return ictx;
        } else {
            return ictx = makeDirContext();
        }
    }

    private transient DirContext ictx;
}


text:
package flags

// ProtoLegacy specifies whether to enable support for legacy functionality
// such as MessageSets, weak fields, and various other obscure behavior
// that is necessary to maintain backwards compatibility with proto1 or
// the pre-release variants of proto2 and proto3.
//
// This is disabled by default unless built with the "protolegacy" tag.
//
// WARNING: The compatibility agreement covers nothing provided by this flag.
// As such, functionality may suddenly be removed or changed at our discretion.
const ProtoLegacy = protoLegacy

// LazyUnmarshalExtensions specifies whether to lazily unmarshal extensions.
//
// Lazy extension unmarshaling validates the contents of message-valued
// extension fields at unmarshal time, but defers creating the message
// structure until the extension is first accessed.
const LazyUnmarshalExtensions = ProtoLegacy


text:
using System.Collections.Generic;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
#if DEV16_OR_LATER
using Microsoft.WebTools.Languages.Shared.Editor.Completion;
#else
using Microsoft.Web.Editor.Completion;
#endif

namespace Microsoft.PythonTools.Django.Intellisense {
    internal class TemplateCompletionController : CompletionController {
        private readonly PythonToolsService _pyService;

        public TemplateCompletionController(
            PythonToolsService pyService,
            ITextView textView,
            IList<ITextBuffer> subjectBuffers,
            ICompletionBroker completionBroker,
            IAsyncQuickInfoBroker quickInfoBroker,
            ISignatureHelpBroker signatureBroker) :
            base(textView, subjectBuffers, completionBroker, quickInfoBroker, signatureBroker) {
            _pyService = pyService;
        }

        public override bool IsTriggerChar(char typedCharacter) {
            const string triggerChars = " |.";
            return _pyService.AdvancedOptions.AutoListMembers && !HasActiveCompletionSession && triggerChars.IndexOf(typedCharacter) >= 0;
        }

        public override bool IsCommitChar(char typedCharacter) {
            if (!HasActiveCompletionSession) {
                return false;
            }

            if (typedCharacter == '\n' || typedCharacter == '\t') {
                return true;
            }

            return _pyService.AdvancedOptions.CompletionCommittedBy.IndexOf(typedCharacter) > 0;
        }

        protected override bool IsRetriggerChar(ICompletionSession session, char typedCharacter) {
            if (typedCharacter == ' ') {
                return true;
            }

            return base.IsRetriggerChar(session, typedCharacter);
        }
    }
}


text:
from django.test import TestCase
from django.test.client import RequestFactory
from django.core.urlresolvers import reverse
from model_mommy import mommy
from animals.models import Animal
from animals.fields import MultipleAnimalsField, SireField

class AnimalFieldTestCase(TestCase):

    def setUp(self):
        self.dam = mommy.make('animals.Animal', ear_tag='456', name='dam')
        self.sire = mommy.make('animals.Animal', ear_tag='123', name='sire', gender=Animal.GENDER_CHOICES.bull)
        self.factory = RequestFactory()

    def test_multiple_animal_field(self):
        request = self.factory.get(reverse('django_select2_central_json'))
        # result looks like this: ('nil', False, [(1L, u'dam'), (2L, u'sire')])
        results = MultipleAnimalsField().get_results(request, term='', page='1', context='')
        res = [(animal.id, animal.name) for animal in Animal.objects.all()]
        self.assertEqual(res, results[2])
        # result looks like this: ('nil', False, [(1L, u'dam')])
        results = MultipleAnimalsField().get_results(request, term='d', page='1', context='')
        self.assertEqual([(1L, u'dam')], results[2])

    def test_sire_field(self):
        request = self.factory.get(reverse('django_select2_central_json'))
        # result looks like this: ('nil', False, [(4L, u'123', {})])
        results = SireField().get_results(request, term='s', page='1', context='')
        self.assertEqual((4L, u'123', {}), results[2][0])


text:
<?php

namespace PayPal\Test\Api;

use PayPal\Common\PPModel;
use PayPal\Api\PayerInfo;

/**
 * Class PayerInfo
 *
 * @package PayPal\Test\Api
 */
class PayerInfoTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Gets Json String of Object PayerInfo
     * @return string
     */
    public static function getJson()
    {
        return '{"email":"TestSample","external_remember_me_id":"TestSample","buyer_account_number":"TestSample","first_name":"TestSample","last_name":"TestSample","payer_id":"TestSample","phone":"TestSample","phone_type":"TestSample","birth_date":"TestSample","tax_id":"TestSample","tax_id_type":"TestSample","billing_address":' .AddressTest::getJson() . ',"shipping_address":' .ShippingAddressTest::getJson() . '}';
    }

    /**
     * Gets Object Instance with Json data filled in
     * @return PayerInfo
     */
    public static function getObject()
    {
        return new PayerInfo(self::getJson());
    }

    /**
     * Tests for Serialization and Deserialization Issues
     * @return PayerInfo
     */
    public function testSerializationDeserialization()
    {
        $obj = new PayerInfo(self::getJson());
        $this->assertNotNull($obj);
        $this->assertNotNull($obj->getEmail());
        $this->assertNotNull($obj->getExternalRememberMeId());
        $this->assertNotNull($obj->getBuyerAccountNumber());
        $this->assertNotNull($obj->getFirstName());
        $this->assertNotNull($obj->getLastName());
        $this->assertNotNull($obj->getPayerId());
        $this->assertNotNull($obj->getPhone());
        $this->assertNotNull($obj->getPhoneType());
        $this->assertNotNull($obj->getBirthDate());
        $this->assertNotNull($obj->getTaxId());
        $this->assertNotNull($obj->getTaxIdType());
        $this->assertNotNull($obj->getBillingAddress());
        $this->assertNotNull($obj->getShippingAddress());
        $this->assertEquals(self::getJson(), $obj->toJson());
        return $obj;
    }

    /**
     * @depends testSerializationDeserialization
     * @param PayerInfo $obj
     */
    public function testGetters($obj)
    {
        $this->assertEquals($obj->getEmail(), "TestSample");
        $this->assertEquals($obj->getExternalRememberMeId(), "TestSample");
        $this->assertEquals($obj->getBuyerAccountNumber(), "TestSample");
        $this->assertEquals($obj->getFirstName(), "TestSample");
        $this->assertEquals($obj->getLastName(), "TestSample");
        $this->assertEquals($obj->getPayerId(), "TestSample");
        $this->assertEquals($obj->getPhone(), "TestSample");
        $this->assertEquals($obj->getPhoneType(), "TestSample");
        $this->assertEquals($obj->getBirthDate(), "TestSample");
        $this->assertEquals($obj->getTaxId(), "TestSample");
        $this->assertEquals($obj->getTaxIdType(), "TestSample");
        $this->assertEquals($obj->getBillingAddress(), AddressTest::getObject());
        $this->assertEquals($obj->getShippingAddress(), ShippingAddressTest::getObject());
    }

    /**
     * @depends testSerializationDeserialization
     * @param PayerInfo $obj
     */
    public function testDeprecatedGetters($obj)
    {
        $this->assertEquals($obj->getExternal_remember_me_id(), "TestSample");
        $this->assertEquals($obj->getBuyer_account_number(), "TestSample");
        $this->assertEquals($obj->getFirst_name(), "TestSample");
        $this->assertEquals($obj->getLast_name(), "TestSample");
        $this->assertEquals($obj->getPayer_id(), "TestSample");
        $this->assertEquals($obj->getPhone_type(), "TestSample");
        $this->assertEquals($obj->getBirth_date(), "TestSample");
        $this->assertEquals($obj->getTax_id(), "TestSample");
        $this->assertEquals($obj->getTax_id_type(), "TestSample");
        $this->assertEquals($obj->getBilling_address(), AddressTest::getObject());
        $this->assertEquals($obj->getShipping_address(), ShippingAddressTest::getObject());
    }

    /**
     * @depends testSerializationDeserialization
     * @param PayerInfo $obj
     */
    public function testDeprecatedSetterNormalGetter($obj)
    {

        // Check for External_remember_me_id
        $obj->setExternalRememberMeId(null);
        $this->assertNull($obj->getExternal_remember_me_id());
        $this->assertNull($obj->getExternalRememberMeId());
        $this->assertSame($obj->getExternalRememberMeId(), $obj->getExternal_remember_me_id());
        $obj->setExternal_remember_me_id("TestSample");
        $this->assertEquals($obj->getExternal_remember_me_id(), "TestSample");

        // Check for Buyer_account_number
        $obj->setBuyerAccountNumber(null);
        $this->assertNull($obj->getBuyer_account_number());
        $this->assertNull($obj->getBuyerAccountNumber());
        $this->assertSame($obj->getBuyerAccountNumber(), $obj->getBuyer_account_number());
        $obj->setBuyer_account_number("TestSample");
        $this->assertEquals($obj->getBuyer_account_number(), "TestSample");

        // Check for First_name
        $obj->setFirstName(null);
        $this->assertNull($obj->getFirst_name());
        $this->assertNull($obj->getFirstName());
        $this->assertSame($obj->getFirstName(), $obj->getFirst_name());
        $obj->setFirst_name("TestSample");
        $this->assertEquals($obj->getFirst_name(), "TestSample");

        // Check for Last_name
        $obj->setLastName(null);
        $this->assertNull($obj->getLast_name());
        $this->assertNull($obj->getLastName());
        $this->assertSame($obj->getLastName(), $obj->getLast_name());
        $obj->setLast_name("TestSample");
        $this->assertEquals($obj->getLast_name(), "TestSample");

        // Check for Payer_id
        $obj->setPayerId(null);
        $this->assertNull($obj->getPayer_id());
        $this->assertNull($obj->getPayerId());
        $this->assertSame($obj->getPayerId(), $obj->getPayer_id());
        $obj->setPayer_id("TestSample");
        $this->assertEquals($obj->getPayer_id(), "TestSample");

        // Check for Phone_type
        $obj->setPhoneType(null);
        $this->assertNull($obj->getPhone_type());
        $this->assertNull($obj->getPhoneType());
        $this->assertSame($obj->getPhoneType(), $obj->getPhone_type());
        $obj->setPhone_type("TestSample");
        $this->assertEquals($obj->getPhone_type(), "TestSample");

        // Check for Birth_date
        $obj->setBirthDate(null);
        $this->assertNull($obj->getBirth_date());
        $this->assertNull($obj->getBirthDate());
        $this->assertSame($obj->getBirthDate(), $obj->getBirth_date());
        $obj->setBirth_date("TestSample");
        $this->assertEquals($obj->getBirth_date(), "TestSample");

        // Check for Tax_id
        $obj->setTaxId(null);
        $this->assertNull($obj->getTax_id());
        $this->assertNull($obj->getTaxId());
        $this->assertSame($obj->getTaxId(), $obj->getTax_id());
        $obj->setTax_id("TestSample");
        $this->assertEquals($obj->getTax_id(), "TestSample");

        // Check for Tax_id_type
        $obj->setTaxIdType(null);
        $this->assertNull($obj->getTax_id_type());
        $this->assertNull($obj->getTaxIdType());
        $this->assertSame($obj->getTaxIdType(), $obj->getTax_id_type());
        $obj->setTax_id_type("TestSample");
        $this->assertEquals($obj->getTax_id_type(), "TestSample");

        // Check for Billing_address
        $obj->setBillingAddress(null);
        $this->assertNull($obj->getBilling_address());
        $this->assertNull($obj->getBillingAddress());
        $this->assertSame($obj->getBillingAddress(), $obj->getBilling_address());
        $obj->setBilling_address(AddressTest::getObject());
        $this->assertEquals($obj->getBilling_address(), AddressTest::getObject());

        // Check for Shipping_address
        $obj->setShippingAddress(null);
        $this->assertNull($obj->getShipping_address());
        $this->assertNull($obj->getShippingAddress());
        $this->assertSame($obj->getShippingAddress(), $obj->getShipping_address());
        $obj->setShipping_address(ShippingAddressTest::getObject());
        $this->assertEquals($obj->getShipping_address(), ShippingAddressTest::getObject());

        //Test All Deprecated Getters and Normal Getters
        $this->testDeprecatedGetters($obj);
        $this->testGetters($obj);
    }

}


text:
import React, {Component} from 'react';

import {
    Animated,
    View,
    StyleSheet,
    Dimensions,
    TouchableNativeFeedback,
    TextInput,
    Text,
    AsyncStorage
} from 'react-native';

import query from './../fetch';
import List from './list';

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: '',
            password: ''
        };
        this._onPressButton = this.onPressButton.bind(this);
    }

    render() {
        return (
            <View style={styles.login}>
                <TextInput
                    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={(text) => this.setState({name: text})}
                    value={this.state.name}
                    placeholder="用户名"
                />
                <TextInput
                    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={(text) => this.setState({password: text})}
                    value={this.state.password}
                    placeholder="密码"
                    autoCorrect={true}
                />
                <TouchableNativeFeedback
                    onPress={this._onPressButton}
                    background={TouchableNativeFeedback.SelectableBackground()}>
                    <View style={styles.button}>
                        <Text style={{marginTop: 10, color: '#fff', textAlign: 'center'}}>登录</Text>
                    </View>
                </TouchableNativeFeedback>
            </View>
        )
    }

    onPressButton() {
        let _this = this;
        const {navigator} = this.props;
        query.post('/user/login', {
            name: _this.state.name,
            password: _this.state.password
        }, function (res) {
            if (res.code === 0) {
                AsyncStorage.setItem('user', JSON.stringify({
                    name: res.user.name,
                    _id: res.user.userId
                }));
                if (navigator) {
                    navigator.push({
                        name: 'List',
                        component: List,
                    })
                }
            }
            console.log(res);
        });
    }
}

var styles = StyleSheet.create({
    login: {
        position: 'absolute',
        top: 150,
        left: 30,
        width: 300,
    },
    button: {
        height: 40,
        backgroundColor: '#00B7FF',
        flex: 1,
        marginLeft: 5,
        marginRight: 5,
        marginTop: 20,
    }
});
export default Login;


text:
package de.uni_koeln.phil_fak.info.icrawler.core.parser;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.uni_koeln.phil_fak.info.icrawler.core.Constants;
import de.uni_koeln.phil_fak.info.icrawler.core.data.WebDocument;

public class SPONWebDocumentParser extends WebDocumentParser {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private static final String TAB = "\t";
	private static final String NEW_LINE = "\n";

	public static String[] topicArray = {
			"politik",
			"panorama",
			"kultur",
			"wirtschaft",
			"sport",
			"netzwelt",
			"wissenschaft"
	};

	Set<String> validTopics = new HashSet<String>(Arrays.asList(topicArray));

	public WebDocument process(Document node, final String url) {

		WebDocument document = new WebDocument();
		Set<String> links = new HashSet<String>();

		// Grab the title
		String title = node.select(".article-title").text();
		if(title != null)
			document.setTitle(title);
		//logger.info("title: " + title);

		// Grab the intro
		String intro = node.select(".article-intro").text();
		if(intro != null)
			document.setIntro(intro);
		//logger.info("intro: " + intro);

		// Grab the news article
//		StringBuilder builder = new StringBuilder();
//		Elements paragraphs = node.select(".article-section").select("p");
//		for (Element paragraph : paragraphs) {
//			 String text = paragraph.text().trim();
//			 if (text.length() > 0)
//				 builder.append(text).append(NEW_LINE);
//		}
//		String content = builder.toString();
		String content = node.select(".article-section").text();
		if(content != null && !content.equals("") && content.length() > 500)
			document.setContent(content);
		else
			document.setContent(null);
		//logger.info("content: " + content);

		// Grab all anchors from the given html document
		Elements anchors = node.select("a[href]");
		for (Element a : anchors) {
			String anchor = a.attr("abs:href");
			if (!anchor.contains("?") && !anchor.contains("#")) {
				if(isNative(anchor)) {
					boolean add = links.add(anchor);
//					if(add)
//						logger.info("anchor: " + anchor);
				}
			}
		}

		try {
			document.setTopic(getTopic(url, node));
			//document.setLinks(LinkHelper.checked(url, links));
			document.setLinks(links);
			document.setUrl(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return document;
	}

	private boolean isNative(final String anchor) {
		try {
			if(anchor.isEmpty())
				return false;
			String host1 = new URL(anchor).getHost();
			String host2 = new URL(Constants.SPON_ROOT_URL).getHost();
			if(host1.equals(host2))
				return true;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return false;
	}

	private String getTopic(final String url, Document node) throws MalformedURLException {

		URL urlObj = new URL(url);
		String path = urlObj.getPath();
		if(!path.equals("")) {
			path = path.substring(1, urlObj.getPath().length());
			String topic = path.split("/")[0];
			String channelName = node.select(".channel-name").attr("href").replaceAll("/", "");

			if(channelName != null) {
				if(topic.equalsIgnoreCase(channelName) && validTopics.contains(topic))
					return topic;
				else if(validTopics.contains(channelName))
						return channelName;
				} else {
					return "unknow";
			}
		}

		return "unkown";
	}

}


text:
# New-Guid
## SYNOPSIS
Creates a new Guid object and displays it to the screen

## SYNTAX
```powershell
New-Guid [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
Uses static System.Guid.NewGuid() method to create a new Guid object

## PARAMETERS
### -WhatIf <SwitchParameter>

```
Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false
```

### -Confirm <SwitchParameter>

```
Required?                    false
Position?                    named
Default value
Accept pipeline input?       false
Accept wildcard characters?  false
```

## INPUTS

## OUTPUTS
System.String

## NOTES
This is just a quick & dirty helper function to generate GUID's
this is neat if you need a new GUID for an PowerShell Module.

If you have Visual Studio, you might find this function useless!

## EXAMPLES
### EXAMPLE 1
```powershell
PS C:\>New-Guid

fd6bd476-db80-44e7-ab34-47437adeb8e3

Creates a new Guid object and displays its GUI to the screen
```


text:
<?php

namespace spec\Sylius\Bundle\ReportBundle\Renderer;

use PhpSpec\ObjectBehavior;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Sylius\Component\Report\Model\ReportInterface;
use Symfony\Component\HttpFoundation\Response;
use Sylius\Component\Report\DataFetcher\Data;
use Sylius\Component\Report\Renderer\DefaultRenderers;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
class TableRendererSpec extends ObjectBehavior
{
    public function let(EngineInterface $templating)
    {
        $this->beConstructedWith($templating);
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\ReportBundle\Renderer\TableRenderer');
    }

    public function it_should_implement_renderer_interface()
    {
        $this->shouldImplement('Sylius\Component\Report\Renderer\RendererInterface');
    }

    public function it_renders_data_with_given_configuration(ReportInterface $report, Response $response, Data $reportData, $templating)
    {
        $reportData->getLabels()->willReturn(array('month', 'user_total'));
        $reportData->getData()->willReturn(array('month1' => '50', 'month2' => '40'));

        $renderData = array(
            'report' => $report,
            'values' => array('month1' => '50', 'month2' => '40'),
            'labels' => array('month', 'user_total'),
            'fields' => array('month1', 'month2'),
        );

        $report->getRendererConfiguration()->willReturn(array('template' => 'SyliusReportBundle:Table:default.html.twig'));

        $templating->renderResponse('SyliusReportBundle:Table:default.html.twig', array(
            'data' => $renderData,
            'configuration' => array('template' => 'SyliusReportBundle:Table:default.html.twig'),
        ))->willReturn($response);

        $this->render($report, $reportData)->shouldReturn($response);
    }

    public function it_has_type()
    {
        $this->getType()->shouldReturn(DefaultRenderers::TABLE);
    }
}


text:
title: ThreadState.Initialized - aesi-eclipse
---

[aesi-eclipse](../../index.html) / [com.virtlink.aesi.debugging](../index.html) / [ThreadState](index.html) / [Initialized](.)

# Initialized

`Initialized`