text:
using System;
using System.IO;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Policy;
using System.Reflection;
using System.Globalization;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Amib.Threading;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.EventQueue;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Region.ScriptEngine.Shared.CodeTools;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Interfaces;

namespace OpenSim.Region.ScriptEngine.XEngine
{
    public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
    {
        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private SmartThreadPool m_ThreadPool;
        private int m_MaxScriptQueue;
        private Scene m_Scene;
        private IConfig m_ScriptConfig = null;
        private IConfigSource m_ConfigSource = null;
        private ICompiler m_Compiler;
        private int m_MinThreads;
        private int m_MaxThreads ;
        private int m_IdleTimeout;
        private int m_StackSize;
        private int m_SleepTime;
        private int m_SaveTime;
        private ThreadPriority m_Prio;
        private bool m_Enabled = false;
        private bool m_InitialStartup = true;
        private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
        private string m_ScriptErrorMessage;

// disable warning: need to keep a reference to XEngine.EventManager
// alive to avoid it being garbage collected
#pragma warning disable 414
        private EventManager m_EventManager;
#pragma warning restore 414
        private IXmlRpcRouter m_XmlRpcRouter;
        private int m_EventLimit;
        private bool m_KillTimedOutScripts;

        private static List<XEngine> m_ScriptEngines =
                new List<XEngine>();

        // Maps the local id to the script inventory items in it

        private Dictionary<uint, List<UUID> > m_PrimObjects =
                new Dictionary<uint, List<UUID> >();

        // Maps the UUID above to the script instance

        private Dictionary<UUID, IScriptInstance> m_Scripts =
                new Dictionary<UUID, IScriptInstance>();

        // Maps the asset ID to the assembly

        private Dictionary<UUID, string> m_Assemblies =
                new Dictionary<UUID, string>();

        private Dictionary<string, int> m_AddingAssemblies =
                new Dictionary<string, int>();

        // This will list AppDomains by script asset

        private Dictionary<UUID, AppDomain> m_AppDomains =
                new Dictionary<UUID, AppDomain>();

        // List the scripts running in each appdomain

        private Dictionary<UUID, List<UUID> > m_DomainScripts =
                new Dictionary<UUID, List<UUID> >();

        private Queue m_CompileQueue = new Queue(100);
        IWorkItemResult m_CurrentCompile = null;

        public string ScriptEngineName
        {
            get { return "XEngine"; }
        }

        public Scene World
        {
            get { return m_Scene; }
        }

        public static List<XEngine> ScriptEngines
        {
            get { return m_ScriptEngines; }
        }

        public IScriptModule ScriptModule
        {
            get { return this; }
        }

        // private struct RezScriptParms
        // {
        //     uint LocalID;
        //     UUID ItemID;
        //     string Script;
        // }

        public IConfig Config
        {
            get { return m_ScriptConfig; }
        }

        public IConfigSource ConfigSource
        {
            get { return m_ConfigSource; }
        }

        public event ScriptRemoved OnScriptRemoved;
        public event ObjectRemoved OnObjectRemoved;

        //
        // IRegionModule functions
        //
        public void Initialise(IConfigSource configSource)
        {
            if (configSource.Configs["XEngine"] == null)
                return;

            m_ScriptConfig = configSource.Configs["XEngine"];
            m_ConfigSource = configSource;
        }

        public void AddRegion(Scene scene)
        {
            if (m_ScriptConfig == null)
                return;
            m_ScriptFailCount = 0;
            m_ScriptErrorMessage = String.Empty;

            if (m_ScriptConfig == null)
            {
//                m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
                return;
            }

            m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);

            if (!m_Enabled)
                return;

            AppDomain.CurrentDomain.AssemblyResolve +=
                OnAssemblyResolve;

            m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
                             scene.RegionInfo.RegionName);
            m_Scene = scene;

            m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
            m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
            m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
            string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
            m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
            m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
            m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;

            m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
            m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
            m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;

            m_Prio = ThreadPriority.BelowNormal;
            switch (priority)
            {
                case "Lowest":
                    m_Prio = ThreadPriority.Lowest;
                    break;
                case "BelowNormal":
                    m_Prio = ThreadPriority.BelowNormal;
                    break;
                case "Normal":
                    m_Prio = ThreadPriority.Normal;
                    break;
                case "AboveNormal":
                    m_Prio = ThreadPriority.AboveNormal;
                    break;
                case "Highest":
                    m_Prio = ThreadPriority.Highest;
                    break;
                default:
                    m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
                    break;
            }

            lock (m_ScriptEngines)
            {
                m_ScriptEngines.Add(this);
            }

            // Needs to be here so we can queue the scripts that need starting
            //
            m_Scene.EventManager.OnRezScript += OnRezScript;

            // Complete basic setup of the thread pool
            //
            SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
                        m_MaxScriptQueue, m_StackSize);

            m_Scene.StackModuleInterface<IScriptModule>(this);

            m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
            if (m_XmlRpcRouter != null)
            {
                OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
                OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
            }
        }

        public void RemoveRegion(Scene scene)
        {
            lock (m_Scripts)
            {
                foreach (IScriptInstance instance in m_Scripts.Values)
                {
                    // Force a final state save
                    //
                    if (m_Assemblies.ContainsKey(instance.AssetID))
                    {
                        string assembly = m_Assemblies[instance.AssetID];
                        instance.SaveState(assembly);
                    }

                    // Clear the event queue and abort the instance thread
                    //
                    instance.ClearQueue();
                    instance.Stop(0);

                    // Release events, timer, etc
                    //
                    instance.DestroyScriptInstance();

                    // Unload scripts and app domains
                    // Must be done explicitly because they have infinite
                    // lifetime
                    //
                    m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
                    if (m_DomainScripts[instance.AppDomain].Count == 0)
                    {
                        m_DomainScripts.Remove(instance.AppDomain);
                        UnloadAppDomain(instance.AppDomain);
                    }
                }
                m_Scripts.Clear();
                m_PrimObjects.Clear();
                m_Assemblies.Clear();
                m_DomainScripts.Clear();
            }
            lock (m_ScriptEngines)
            {
                m_ScriptEngines.Remove(this);
            }
        }

        public void RegionLoaded(Scene scene)
        {
            if (!m_Enabled)
                return;

            m_EventManager = new EventManager(this);

            m_Compiler = new Compiler(this);

            m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
            m_Scene.EventManager.OnScriptReset += OnScriptReset;
            m_Scene.EventManager.OnStartScript += OnStartScript;
            m_Scene.EventManager.OnStopScript += OnStopScript;
            m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
            m_Scene.EventManager.OnShutdown += OnShutdown;

            if (m_SleepTime > 0)
            {
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
                                           new Object[]{ m_SleepTime });
            }

            if (m_SaveTime > 0)
            {
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
                                           new Object[] { m_SaveTime });
            }

            m_ThreadPool.Start();
        }

        public void Close()
        {
            lock (m_ScriptEngines)
            {
                if (m_ScriptEngines.Contains(this))
                    m_ScriptEngines.Remove(this);
            }
        }

        public object DoBackup(object o)
        {
            Object[] p = (Object[])o;
            int saveTime = (int)p[0];

            if (saveTime > 0)
                System.Threading.Thread.Sleep(saveTime);

//            m_log.Debug("[XEngine] Backing up script states");

            List<IScriptInstance> instances = new List<IScriptInstance>();

            lock (m_Scripts)
            {
                foreach (IScriptInstance instance in m_Scripts.Values)
                    instances.Add(instance);
            }

            foreach (IScriptInstance i in instances)
            {
                string assembly = String.Empty;

                lock (m_Scripts)
                {
                    if (!m_Assemblies.ContainsKey(i.AssetID))
                        continue;
                    assembly = m_Assemblies[i.AssetID];
                }

                i.SaveState(assembly);
            }

            instances.Clear();

            if (saveTime > 0)
                m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
                                           new Object[] { saveTime });

            return 0;
        }

        public object DoMaintenance(object p)
        {
            object[] parms = (object[])p;
            int sleepTime = (int)parms[0];

            foreach (IScriptInstance inst in m_Scripts.Values)
            {
                if (inst.EventTime() > m_EventLimit)
                {
                    inst.Stop(100);
                    if (!m_KillTimedOutScripts)
                        inst.Start();
                }
            }

            System.Threading.Thread.Sleep(sleepTime);

            m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
                                       new Object[]{ sleepTime });

            return 0;
        }

        public Type ReplaceableInterface
        {
            get { return null; }
        }

        public string Name
        {
            get { return "XEngine"; }
        }

        public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
        {
            if (script.StartsWith("//MRM:"))
                return;

            List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());

            List<string> names = new List<string>();
            foreach (IScriptModule m in engines)
                names.Add(m.ScriptEngineName);

            int lineEnd = script.IndexOf('\n');

            if (lineEnd > 1)
            {
                string firstline = script.Substring(0, lineEnd).Trim();

                int colon = firstline.IndexOf(':');
                if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
                {
                    string engineName = firstline.Substring(2, colon-2);

                    if (names.Contains(engineName))
                    {
                        engine = engineName;
                        script = "//" + script.Substring(script.IndexOf(':')+1);
                    }
                    else
                    {
                        if (engine == ScriptEngineName)
                        {
                            SceneObjectPart part =
                                    m_Scene.GetSceneObjectPart(
                                    localID);

                            TaskInventoryItem item =
                                    part.Inventory.GetInventoryItem(itemID);

                            ScenePresence presence =
                                    m_Scene.GetScenePresence(
                                    item.OwnerID);

                            if (presence != null)
                            {
                               presence.ControllingClient.SendAgentAlertMessage(
                                        "Selected engine unavailable. "+
                                        "Running script on "+
                                        ScriptEngineName,
                                        false);
                            }
                        }
                    }
                }
            }

            if (engine != ScriptEngineName)
                return;

            Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};

            if (stateSource == (int)StateSource.ScriptedRez)
            {
                DoOnRezScript(parms);
            }
            else
            {
                lock (m_CompileQueue)
                {
                    m_CompileQueue.Enqueue(parms);

                    if (m_CurrentCompile == null)
                    {
                        m_CurrentCompile = m_ThreadPool.QueueWorkItem(
                                new WorkItemCallback(this.DoOnRezScriptQueue),
                                new Object[0]);
                    }
                }
            }
        }

        public Object DoOnRezScriptQueue(Object dummy)
        {
            if (m_InitialStartup)
            {
                m_InitialStartup = false;
                System.Threading.Thread.Sleep(15000);
                lock (m_CompileQueue)
                {
                    if (m_CompileQueue.Count==0)
                        // No scripts on region, so won't get triggered later
                        // by the queue becoming empty so we trigger it here
                        m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
                }
            }

            Object o;
            lock (m_CompileQueue)
            {
                o = m_CompileQueue.Dequeue();
                if (o == null)
                {
                    m_CurrentCompile = null;
                    return null;
                }
            }

            DoOnRezScript(o);

            lock (m_CompileQueue)
            {
                if (m_CompileQueue.Count > 0)
                {
                    m_CurrentCompile = m_ThreadPool.QueueWorkItem(
                            new WorkItemCallback(this.DoOnRezScriptQueue),
                            new Object[0]);
                }
                else
                {
                    m_CurrentCompile = null;
                    m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
                                                                        m_ScriptErrorMessage);
                    m_ScriptFailCount = 0;
                }
            }
            return null;
        }

        private bool DoOnRezScript(object parm)
        {
            Object[] p = (Object[])parm;
            uint localID = (uint)p[0];
            UUID itemID = (UUID)p[1];
            string script =(string)p[2];
            int startParam = (int)p[3];
            bool postOnRez = (bool)p[4];
            StateSource stateSource = (StateSource)p[5];

            // Get the asset ID of the script, so we can check if we
            // already have it.

            // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
            // m_parts lock on SOG.  At the same time, a scene object that is being deleted will take the m_parts lock
            // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
            SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
            if (part == null)
            {
                m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
                m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
                m_ScriptFailCount++;
                return false;
            }

            TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
            if (item == null)
            {
                m_ScriptErrorMessage += "Can't find script inventory item.\n";
                m_ScriptFailCount++;
                return false;
            }

            UUID assetID = item.AssetID;

            //m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
            //        item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);

            ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);

            string assembly = "";

            CultureInfo USCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = USCulture;

            Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;

            try
            {
                lock (m_AddingAssemblies)
                {
                    assembly = (string)m_Compiler.PerformScriptCompile(script,
                            assetID.ToString(), item.OwnerID);
                    if (!m_AddingAssemblies.ContainsKey(assembly)) {
                        m_AddingAssemblies[assembly] = 1;
                    } else {
                        m_AddingAssemblies[assembly]++;
                    }
                    linemap = m_Compiler.LineMap();
                }

                string[] warnings = m_Compiler.GetWarnings();

                if (warnings != null && warnings.Length != 0)
                {
                    foreach (string warning in warnings)
                    {
                        try
                        {
                            // DISPLAY WARNING INWORLD
                            string text = "Warning:\n" + warning;
                            if (text.Length > 1000)
                                text = text.Substring(0, 1000);
                            if (!ShowScriptSaveResponse(item.OwnerID,
                                    assetID, text, true))
                            {
                                if (presence != null && (!postOnRez))
                                    presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);

                                World.SimChat(Utils.StringToBytes(text),
                                              ChatTypeEnum.DebugChannel, 2147483647,
                                              part.AbsolutePosition,
                                              part.Name, part.UUID, false);
                            }
                        }
                        catch (Exception e2) // LEGIT: User Scripting
                        {
                            m_log.Error("[XEngine]: " +
                                    "Error displaying warning in-world: " +
                                    e2.ToString());
                            m_log.Error("[XEngine]: " +
                                    "Warning:\r\n" +
                                    warning);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                try
                {
                    // DISPLAY ERROR INWORLD
                    m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();

                    m_ScriptFailCount++;
                    string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
                    if (text.Length > 1000)
                        text = text.Substring(0, 1000);
                    if (!ShowScriptSaveResponse(item.OwnerID,
                            assetID, text, false))
                    {
                        if (presence != null && (!postOnRez))
                            presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
                        World.SimChat(Utils.StringToBytes(text),
                                      ChatTypeEnum.DebugChannel, 2147483647,
                                      part.AbsolutePosition,
                                      part.Name, part.UUID, false);
                    }
                }
                catch (Exception e2) // LEGIT: User Scripting
                {
                    m_log.Error("[XEngine]: "+
                            "Error displaying error in-world: " +
                            e2.ToString());
                    m_log.Error("[XEngine]: " +
                            "Errormessage: Error compiling script:\r\n" +
                            e.Message.ToString());
                }

                return false;
            }

            lock (m_Scripts)
            {
                ScriptInstance instance = null;
                // Create the object record

                if ((!m_Scripts.ContainsKey(itemID)) ||
                    (m_Scripts[itemID].AssetID != assetID))
                {
                    UUID appDomain = assetID;

                    if (part.ParentGroup.IsAttachment)
                        appDomain = part.ParentGroup.RootPart.UUID;

                    if (!m_AppDomains.ContainsKey(appDomain))
                    {
                        try
                        {
                            AppDomainSetup appSetup = new AppDomainSetup();
//                            appSetup.ApplicationBase = Path.Combine(
//                                    "ScriptEngines",
//                                    m_Scene.RegionInfo.RegionID.ToString());

                            Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
                            Evidence evidence = new Evidence(baseEvidence);

                            AppDomain sandbox =
                                AppDomain.CreateDomain(
                                    m_Scene.RegionInfo.RegionID.ToString(),
                                    evidence, appSetup);
/*
                            PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
                            AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
                            PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
                            PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
                            CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
                            sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
                            sandbox.SetAppDomainPolicy(sandboxPolicy);
*/
                            m_AppDomains[appDomain] = sandbox;

                            m_AppDomains[appDomain].AssemblyResolve +=
                                new ResolveEventHandler(
                                    AssemblyResolver.OnAssemblyResolve);
                            m_DomainScripts[appDomain] = new List<UUID>();
                        }
                        catch (Exception e)
                        {
                            m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
                            m_ScriptErrorMessage += "Exception creating app domain:\n";
                            m_ScriptFailCount++;
                            lock (m_AddingAssemblies)
                            {
                                m_AddingAssemblies[assembly]--;
                            }
                            return false;
                        }
                    }
                    m_DomainScripts[appDomain].Add(itemID);

                    instance = new ScriptInstance(this, part,
                                                  itemID, assetID, assembly,
                                                  m_AppDomains[appDomain],
                                                  part.ParentGroup.RootPart.Name,
                                                  item.Name, startParam, postOnRez,
                                                  stateSource, m_MaxScriptQueue);

                    m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
                            part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());

                    if (presence != null)
                    {
                        ShowScriptSaveResponse(item.OwnerID,
                                assetID, "Compile successful", true);
                    }

                    instance.AppDomain = appDomain;
                    instance.LineMap = linemap;

                    m_Scripts[itemID] = instance;
                }

                lock (m_PrimObjects)
                {
                    if (!m_PrimObjects.ContainsKey(localID))
                        m_PrimObjects[localID] = new List<UUID>();

                    if (!m_PrimObjects[localID].Contains(itemID))
                        m_PrimObjects[localID].Add(itemID);

                }

                if (!m_Assemblies.ContainsKey(assetID))
                    m_Assemblies[assetID] = assembly;

                lock (m_AddingAssemblies)
                {
                    m_AddingAssemblies[assembly]--;
                }

                if (instance!=null)
                    instance.Init();
            }
            return true;
        }

        public void OnRemoveScript(uint localID, UUID itemID)
        {
            lock (m_Scripts)
            {
                // Do we even have it?
                if (!m_Scripts.ContainsKey(itemID))
                    return;

                IScriptInstance instance=m_Scripts[itemID];
                m_Scripts.Remove(itemID);

                instance.ClearQueue();
                instance.Stop(0);

                SceneObjectPart part =
                    m_Scene.GetSceneObjectPart(localID);

                if (part != null)
                    part.RemoveScriptEvents(itemID);

//                bool objectRemoved = false;

                lock (m_PrimObjects)
                {
                    // Remove the script from it's prim
                    if (m_PrimObjects.ContainsKey(localID))
                    {
                        // Remove inventory item record
                        if (m_PrimObjects[localID].Contains(itemID))
                            m_PrimObjects[localID].Remove(itemID);

                        // If there are no more scripts, remove prim
                        if (m_PrimObjects[localID].Count == 0)
                        {
                            m_PrimObjects.Remove(localID);
//                            objectRemoved = true;
                        }
                    }
                }

                instance.RemoveState();
                instance.DestroyScriptInstance();

                m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
                if (m_DomainScripts[instance.AppDomain].Count == 0)
                {
                    m_DomainScripts.Remove(instance.AppDomain);
                    UnloadAppDomain(instance.AppDomain);
                }

                instance = null;

                ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
                if (handlerObjectRemoved != null)
                    handlerObjectRemoved(part.UUID);

                CleanAssemblies();
            }

            ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
            if (handlerScriptRemoved != null)
                handlerScriptRemoved(itemID);
        }

        public void OnScriptReset(uint localID, UUID itemID)
        {
            ResetScript(itemID);
        }

        public void OnStartScript(uint localID, UUID itemID)
        {
            StartScript(itemID);
        }

        public void OnStopScript(uint localID, UUID itemID)
        {
            StopScript(itemID);
        }

        private void CleanAssemblies()
        {
            List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);

            foreach (IScriptInstance i in m_Scripts.Values)
            {
                if (assetIDList.Contains(i.AssetID))
                    assetIDList.Remove(i.AssetID);
            }

            lock (m_AddingAssemblies)
            {
                foreach (UUID assetID in assetIDList)
                {
                    // Do not remove assembly files if another instance of the script
                    // is currently initialising
                    if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
                        || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
                    {
//                        m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
                        try
                        {
                            if (File.Exists(m_Assemblies[assetID]))
                                File.Delete(m_Assemblies[assetID]);

                            if (File.Exists(m_Assemblies[assetID]+".text"))
                                File.Delete(m_Assemblies[assetID]+".text");

                            if (File.Exists(m_Assemblies[assetID]+".mdb"))
                                File.Delete(m_Assemblies[assetID]+".mdb");

                            if (File.Exists(m_Assemblies[assetID]+".map"))
                                File.Delete(m_Assemblies[assetID]+".map");
                        }
                        catch (Exception)
                        {
                        }
                        m_Assemblies.Remove(assetID);
                    }
                }
            }
        }

        private void UnloadAppDomain(UUID id)
        {
            if (m_AppDomains.ContainsKey(id))
            {
                AppDomain domain = m_AppDomains[id];
                m_AppDomains.Remove(id);

                AppDomain.Unload(domain);
                domain = null;
//                m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
            }
        }

        //
        // Start processing
        //
        private void SetupEngine(int minThreads, int maxThreads,
                                 int idleTimeout, ThreadPriority threadPriority,
                                 int maxScriptQueue, int stackSize)
        {
            m_MaxScriptQueue = maxScriptQueue;

            STPStartInfo startInfo = new STPStartInfo();
            startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
            startInfo.MaxWorkerThreads = maxThreads;
            startInfo.MinWorkerThreads = minThreads;
            startInfo.ThreadPriority = threadPriority;
            startInfo.StackSize = stackSize;
            startInfo.StartSuspended = true;

            m_ThreadPool = new SmartThreadPool(startInfo);
        }

        //
        // Used by script instances to queue event handler jobs
        //
        public IScriptWorkItem QueueEventHandler(object parms)
        {
            return new XWorkItem(m_ThreadPool.QueueWorkItem(
                                     new WorkItemCallback(this.ProcessEventHandler),
                                     parms));
        }

        /// <summary>
        /// Process a previously posted script event.
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        private object ProcessEventHandler(object parms)
        {
            CultureInfo USCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture = USCulture;

            IScriptInstance instance = (ScriptInstance) parms;

            //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);

            return instance.EventProcessor();
        }

        /// <summary>
        /// Post event to an entire prim
        /// </summary>
        /// <param name="localID"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public bool PostObjectEvent(uint localID, EventParams p)
        {
            bool result = false;

            lock (m_PrimObjects)
            {
                if (!m_PrimObjects.ContainsKey(localID))
                    return false;

                foreach (UUID itemID in m_PrimObjects[localID])
                {
                    if (m_Scripts.ContainsKey(itemID))
                    {
                        IScriptInstance instance = m_Scripts[itemID];
                        if (instance != null)
                        {
                            instance.PostEvent(p);
                            result = true;
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Post an event to a single script
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public bool PostScriptEvent(UUID itemID, EventParams p)
        {
            if (m_Scripts.ContainsKey(itemID))
            {
                IScriptInstance instance = m_Scripts[itemID];
                if (instance != null)
                    instance.PostEvent(p);
                return true;
            }
            return false;
        }

        public bool PostScriptEvent(UUID itemID, string name, Object[] p)
        {
            Object[] lsl_p = new Object[p.Length];
            for (int i = 0; i < p.Length ; i++)
            {
                if (p[i] is int)
                    lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
                else if (p[i] is string)
                    lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
                else if (p[i] is Vector3)
                    lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
                else if (p[i] is Quaternion)
                    lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
                else if (p[i] is float)
                    lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
                else
                    lsl_p[i] = p[i];
            }

            return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
        }

        public bool PostObjectEvent(UUID itemID, string name, Object[] p)
        {
            SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
            if (part == null)
                return false;

            Object[] lsl_p = new Object[p.Length];
            for (int i = 0; i < p.Length ; i++)
            {
                if (p[i] is int)
                    lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
                else if (p[i] is string)
                    lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
                else if (p[i] is Vector3)
                    lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
                else if (p[i] is Quaternion)
                    lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
                else if (p[i] is float)
                    lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
                else
                    lsl_p[i] = p[i];
            }

            return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
        }

        public Assembly OnAssemblyResolve(object sender,
                                          ResolveEventArgs args)
        {
            if (!(sender is System.AppDomain))
                return null;

            string[] pathList = new string[] {"bin", "ScriptEngines",
                                              Path.Combine("ScriptEngines",
                                                           m_Scene.RegionInfo.RegionID.ToString())};

            string assemblyName = args.Name;
            if (assemblyName.IndexOf(",") != -1)
                assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));

            foreach (string s in pathList)
            {
                string path = Path.Combine(Directory.GetCurrentDirectory(),
                                           Path.Combine(s, assemblyName))+".dll";

                if (File.Exists(path))
                    return Assembly.LoadFrom(path);
            }

            return null;
        }

        private IScriptInstance GetInstance(UUID itemID)
        {
            IScriptInstance instance;
            lock (m_Scripts)
            {
                if (!m_Scripts.ContainsKey(itemID))
                    return null;
                instance = m_Scripts[itemID];
            }
            return instance;
        }

        public void SetScriptState(UUID itemID, bool running)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
            {
                if (running)
                    instance.Start();
                else
                    instance.Stop(100);
            }
        }

        public bool GetScriptState(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.Running;
            return false;
        }

        public void ApiResetScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.ApiResetScript();
        }

        public void ResetScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.ResetScript();
        }

        public void StartScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.Start();
        }

        public void StopScript(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.Stop(0);
        }

        public DetectParams GetDetectParams(UUID itemID, int idx)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.GetDetectParams(idx);
            return null;
        }

        public void SetMinEventDelay(UUID itemID, double delay)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                instance.MinEventDelay = delay;
        }

        public UUID GetDetectID(UUID itemID, int idx)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance != null)
                return instance.GetDetectID(idx);
            return UUID.Zero;
        }

        public void SetState(UUID itemID, string newState)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return;
            instance.SetState(newState);
        }
        public string GetState(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return "default";
            return instance.State;
        }

        public int GetStartParameter(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return 0;
            return instance.StartParam;
        }

        public void OnShutdown()
        {
            List<IScriptInstance> instances = new List<IScriptInstance>();

            lock (m_Scripts)
            {
                foreach (IScriptInstance instance in m_Scripts.Values)
                    instances.Add(instance);
            }

            foreach (IScriptInstance i in instances)
            {
                // Stop the script, even forcibly if needed. Then flag
                // it as shutting down and restore the previous run state
                // for serialization, so the scripts don't come back
                // dead after region restart
                //
                bool prevRunning = i.Running;
                i.Stop(50);
                i.ShuttingDown = true;
                i.Running = prevRunning;
            }

            DoBackup(new Object[] {0});
        }

        public IScriptApi GetApi(UUID itemID, string name)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return null;
            return instance.GetApi(name);
        }

        public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return;
            IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
            if (eq == null)
            {
                controllingClient.SendScriptRunningReply(objectID, itemID,
                        GetScriptState(itemID));
            }
            else
            {
                eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
                           controllingClient.AgentId);
            }
        }

        public string GetAssemblyName(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return "";
            return instance.GetAssemblyName();
        }

        public string GetXMLState(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return "";
            return instance.GetXMLState();
        }

        public bool CanBeDeleted(UUID itemID)
        {
            IScriptInstance instance = GetInstance(itemID);
            if (instance == null)
                return true;

            return instance.CanBeDeleted();
        }

        private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
        {
            return false;
        }
    }
}


text:
package org.hisp.dhis.helpers.config;

/**
 * @author Gintare Vilkelyte <vilkelyte.gintare@gmail.com>
 */
@org.aeonbits.owner.Config.LoadPolicy( org.aeonbits.owner.Config.LoadType.MERGE )
@Config.Sources( { "system:properties", "system:env", "classpath:config.properties" } )
public interface Config
    extends org.aeonbits.owner.Config
{
    @Key( "instance.url" )
    String baseUrl();

    @Key( "user.super.password" )
    String superUserPassword();

    @Key( "user.super.username" )
    String superUserUsername();

    @Key( "user.default.username" )
    String defaultUserUsername();

    @Key( "user.default.password" )
    String defaultUSerPassword();

    @Key( "user.admin.username" )
    String adminUserUsername();

    @Key( "user.admin.password" )
    String adminUserPassword();

    @Key( "test.cleanup" )
    Boolean shouldCleanUp();
}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Flora myc. Belg. , Suppl. 1 58 (1887)

#### Original name
Russula flavovirens J. Bommer & M. Rousseau, 1887

### Remarks
null


text:
package org.slieb.soy.model;

import com.google.template.soy.data.SoyList;
import com.google.template.soy.data.SoyListData;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.SoyValueProvider;

import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.function.Supplier;

@ParametersAreNonnullByDefault
public class LazySoyList extends LazySoyValue<SoyListData> implements SoyList {

    public LazySoyList(Supplier<SoyListData> supplier) {
        super(supplier);
    }

    @Override
    public int length() {
        return container.get().length();
    }

    @Nonnull
    @Override
    public List<? extends SoyValueProvider> asJavaList() {
        return container.get().asJavaList();
    }

    @Nonnull
    @Override
    public List<? extends SoyValue> asResolvedJavaList() {
        return container.get().asResolvedJavaList();
    }

    @Override
    public SoyValue get(final int index) {
        return container.get().get(index);
    }

    @Override
    public SoyValueProvider getProvider(final int index) {
        return container.get().getProvider(index);
    }

    @Override
    public int getItemCnt() {
        return 0;
    }

    @Nonnull
    @Override
    public Iterable<? extends SoyValue> getItemKeys() {
        return container.get().getItemKeys();
    }

    @Override
    public boolean hasItem(final SoyValue key) {
        return container.get().hasItem(key);
    }

    @Override
    public SoyValue getItem(final SoyValue key) {
        return container.get().getItem(key);
    }

    @Override
    public SoyValueProvider getItemProvider(final SoyValue key) {
        return container.get().getItemProvider(key);
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ShardingWrappperActor.cs" company="KlusterKite">
//   All rights reserved
// </copyright>
// <summary>
//   Wraps sharding into well known path
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace KlusterKite.Core
{
    using System;
    using System.Linq;
#if CORECLR
    using System.Reflection;
#endif

    using Akka.Actor;
    using Akka.Cluster.Sharding;
    using Akka.Configuration;
    using Akka.DI.Core;
    using Akka.Event;

    using Autofac;

    /// <summary>
    /// Wraps sharding into well known path
    /// </summary>
    public class ShardingWrappperActor : ReceiveActor
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardingWrappperActor"/> class.
        /// </summary>
        /// <param name="container">
        /// The dependency resolver.
        /// </param>
        /// <param name="shardingConfig">
        /// The sharding config.
        /// </param>
        public ShardingWrappperActor(IComponentContext container, Config shardingConfig)
        {
            var shardingTypeName = shardingConfig.GetString("type-name");
            if (string.IsNullOrWhiteSpace(shardingTypeName))
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: type-name was not defined for actor {PathString}",
                        this.GetType().Name,
                        this.Self.Path.ToString());
                return;
            }

            var role = shardingConfig.GetString("role");
            if (string.IsNullOrWhiteSpace(role))
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: role was not defined for actor {PathString}",
                        this.GetType().Name,
                        this.Self.Path.ToString());
                return;
            }

            var childTypeName = shardingConfig.GetString("type");
            if (string.IsNullOrWhiteSpace(childTypeName))
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: Type was not defined for actor {PathString}",
                        this.GetType().Name,
                        this.Self.Path.ToString());
                return;
            }

            var type = Type.GetType(childTypeName);
            if (type == null)
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: {ClassTypeString} was not found for actor{PathString}",
                        this.GetType().Name,
                        childTypeName,
                        this.Self.Path.ToString());
                return;
            }

            var messageExtractorTypeName = shardingConfig.GetString("message-extractor");
            if (string.IsNullOrWhiteSpace(messageExtractorTypeName))
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: message-extractor was not defined for actor {PathString}",
                        this.GetType().Name,
                        this.Self.Path.ToString());
                return;
            }

            var messageExtractorType = Type.GetType(messageExtractorTypeName);
            if (messageExtractorType == null)
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: {ClassTypeString} was not found for actor {PathString}",
                        this.GetType().Name,
                        messageExtractorTypeName,
                        this.Self.Path.ToString());
                return;
            }

            if (messageExtractorType.GetInterfaces().All(t => t != typeof(IMessageExtractor)))
            {
                Context.GetLogger()
                    .Error(
                        "{Type}: {ClassTypeString} defined in {PathString} does not implements IMessageExtractor",
                        this.GetType().Name,
                        messageExtractorTypeName,
                        this.Self.Path.ToString());
                return;
            }

            Context.GetLogger()
                   .Info(
                       "{Type}: initializing Sharding manager on {PathString}",
                       typeof(NameSpaceActor).Name,
                       this.Self.Path.ToString());

            var shardingRegion = ClusterSharding.Get(Context.System)
                .Start(
                    shardingTypeName,
                    Context.System.DI().Props(type),
                    ClusterShardingSettings.Create(Context.System).WithRole(role),
                    (IMessageExtractor)container.Resolve(messageExtractorType));

            this.Receive<object>(m => shardingRegion.Tell(m, this.Sender));
        }
    }
}


text:
Erizo is a project that aims to implement a library able to communicate with WebRTC (http://www.webrtc.org) browser clients in order to provide advanced communication services. With ErizoAPI you can use easily erizo in your Node.js projects.

## Requirements

You must have built erizo in your computer in order to use erizoAPI.

You can find erizo code at http://github.com/ging/erizo

## Building Instructions

1- Export the paths to get the source code and the library of erizo:

    - Main path to erizo
      export ERIZO_HOME=path/to/erizo
    - Path to liberizo.so
      export LD\_LIBRARY\_PATH=path/to/erizo/build/erizo

2- Execute build.sh

##Usage

With erizo you can publish and subscribe to WebRTC streams.

First get the erizoAPI module.

    var erizo = require('./path/to/erizoAPI/build/Release/addon');

OneToManyProcessor is the muxer that gets the published stream and sends it to the subscribers. With more than one OneToManyProcessor you can make multiconference services.

    var muxer = new erizo.OneToManyProcessor();

Also you need a WebRtcConnection for each participant (publisher or subscriber).

    var wrtc = new erizo.WebRtcConnection();

Start the ICE negotiation and check periodically its state (the negotiation is asynchronous). When candidates are gathered (state > 0) set the client SDP.

    wrtc.init();

    var intervarId = setInterval(function() {

        var state = wrtc.getCurrentState();

        if(state > 0) {

            wrtc.setRemoteSdp(remoteSdp);

            var localSdp = wrtc.getLocalSdp();

            //Return localSdp to the client

            clearInterval(intervarId);
        }

    }, 100);

Finally return the local SDP to the client and the connection is stablished.

Note that the way to interchange the SDPs between the client and erizo is out of the scope of this project.

###Publishing a stream

To publish a stream add the publisher WebRtcConnection to the OneToManyProcessor

    wrtc.setAudioReceiver(muxer);
    wrtc.setVideoReceiver(muxer);
    muxer.setPublisher(wrtc);

###Subscribing to a stream

To subscribe to a stream add a subscriber WebRtcConnection to the OneToManyProcessor. OneToManyProcessor needs an unique peer identifier for each subscriber.

    muxer.addSubscriber(wrtc, peerId);

In order to start correctly the communication send a FIR packet to the publisher. Make sure the ICE state is READY (wrtc.getCurrentState() > 2)

    muxer.sendFIR();

Also you can remove a determined subscriber from the muxer

    muxer.removeSubscriber(peerId);

## License

The MIT License

Copyright (C) 2012 Universidad Politecnica de Madrid.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
public class Entrenador extends SeleccionFutbol {

   static String idFederacion;

	public void planificarEntrenamiento() {
		System.out.println("Planificar un Entrenamiento");
	}

	@Override
	public void concentrarce() {
		// TODO Auto-generated method stub

	}

	@Override
	public void viajar() {
		// TODO Auto-generated method stub
	}
	}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_configure_locale"
        android:showAsAction="collapseActionView"
        android:title="@string/menu_configure_locale" />

</menu>


text:
package cache

import (
	"testing"
	"time"

	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/watch"
)

func TestMutationDetector(t *testing.T) {
	fakeWatch := watch.NewFake()
	lw := &testLW{
		WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
			return fakeWatch, nil
		},
		ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
			return &v1.PodList{}, nil
		},
	}
	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:   "anything",
			Labels: map[string]string{"check": "foo"},
		},
	}
	stopCh := make(chan struct{})
	defer close(stopCh)
	mutationFound := make(chan bool)

	informer := NewSharedInformer(lw, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer)
	detector := &defaultCacheMutationDetector{
		name:           "name",
		period:         1 * time.Second,
		retainDuration: 2 * time.Minute,
		failureFunc: func(message string) {
			mutationFound <- true
		},
	}
	informer.cacheMutationDetector = detector
	go informer.Run(stopCh)

	fakeWatch.Add(pod)

	wait.PollImmediate(100*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) {
		detector.addedObjsLock.Lock()
		defer detector.addedObjsLock.Unlock()
		return len(detector.addedObjs) > 0, nil
	})

	detector.compareObjectsLock.Lock()
	pod.Labels["change"] = "true"
	detector.compareObjectsLock.Unlock()

	select {
	case <-mutationFound:
	case <-time.After(wait.ForeverTestTimeout):
		t.Fatalf("failed waiting for mutating detector")
	}

}


text:
const
	$ = require('./ecQuery');

var tabSize = 4, tab = '    ';
var keyLowercase = true;

function traverse(phrases, curIdx) {
	var root = phrases[curIdx];
	var node = curIdx === 0 ? $('Program'):$('ExpressionStatement', root);

	var i = curIdx+1, len = phrases.length;

	while(i < len) {
		var next = phrases[i];

		if( next.level - root.level > 1 ) { // error
			throw new Error('Invalid indent.');
		}

		else if( next.level <= root.level ) {// end
			break;
		}

		var res = traverse(phrases, i);

		node.insert(res[0]);

		i = res[1];
	}

	return [node, i];
}

function splitLines(str) {
	return str
	.replace(/\r\n/g,'\n') //for window
	.split('\n');
}

//TODO allow leading spaces also
function lineToPhrase(line) {
	var tabs = 0;

	var match = line.match(/^[\t]+/); 		// find leading tabs
	if( match !== null ) tabs = match[0].length;

	var contents = line.substr(tabs);		// exclude leading tabs
	if( contents === '' ) return; 			// ignore empty line

	if( contents[0] === '#' ) return;			// ignore comment

	var colonIdx = contents.indexOf(':'); //find first colon
	if( colonIdx === -1 ) throw new Error('Invalid line.');

	var key = contents.substr(0, colonIdx).trim(),
		value = contents.substr(colonIdx+1).trim();

	if( key === '' ) throw new Error('Invalid line.');

	key = keyLowercase ? key.toLowerCase() : key;
	return {
		level: tabs,
		key: key,
		value: value
	};
}

function parse(str) {
	var lines = splitLines(str);
	var phrases = lines.map(lineToPhrase).filter((val) => { return val !== void 0; });

	phrases.unshift({level: -1});	// root
	return traverse(phrases, 0)[0];
}

exports.parse = parse;


text:
namespace RenderCore { namespace Assets { class ModelCache; class DelayedDrawCall; enum class DelayStep : unsigned; } }
namespace RenderCore { namespace Techniques { class ParsingContext; } }
namespace Utility { class OutputStream; template<typename CharType> class InputStreamFormatter; }
namespace Assets { class DirectorySearchRules; }

namespace SceneEngine
{
    class WorldPlacementsConfig
    {
    public:
        class Cell
        {
        public:
            Float3 _offset;
            Float3 _mins, _maxs;
            ::Assets::ResChar _file[MaxPath];
        };
        std::vector<Cell> _cells;

        WorldPlacementsConfig(
            Utility::InputStreamFormatter<utf8>& formatter,
            const ::Assets::DirectorySearchRules& searchRules);
        WorldPlacementsConfig();
    };

    class PlacementsRenderer;
    class PlacementsIntersections;
    class PlacementsEditor;
    class PlacementsQuadTree;
    class DynamicImposters;

    /// A collection of cells
    ///
    class PlacementCellSet
    {
    public:
        PlacementCellSet(const WorldPlacementsConfig& cfg, const Float3& worldOffset);
        ~PlacementCellSet();

        class Pimpl;
        std::unique_ptr<Pimpl> _pimpl;
    };

    /// Manages stream and organization of object placements
    /// In this context, placements are static objects placed in the world. Most
    /// scenes will have a large number of essentially static objects. This object
    /// manages a large continuous world of these kinds of objects.
    class PlacementsManager : public std::enable_shared_from_this<PlacementsManager>
    {
    public:
        const std::shared_ptr<PlacementsRenderer>& GetRenderer();
        const std::shared_ptr<PlacementsIntersections>& GetIntersections();
        std::shared_ptr<PlacementsEditor> CreateEditor(const std::shared_ptr<PlacementCellSet>& cellSet);

        PlacementsManager(std::shared_ptr<RenderCore::Assets::ModelCache> modelCache);
        ~PlacementsManager();
    protected:
        class Pimpl;
        std::unique_ptr<Pimpl> _pimpl;

        friend class PlacementsEditor;
    };

    class PlacementCell;
    class PlacementsCache;
    class PreparedScene;
    typedef std::pair<uint64, uint64> PlacementGUID;

    class PlacementsRenderer
    {
    public:
            // -------------- Rendering --------------
        void Render(
            RenderCore::Metal::DeviceContext* context,
            RenderCore::Techniques::ParsingContext& parserContext,
            unsigned techniqueIndex,
            const PlacementCellSet& cellSet);
        void Render(
            RenderCore::Metal::DeviceContext* context,
            RenderCore::Techniques::ParsingContext& parserContext,
            PreparedScene& preparedScene,
            unsigned techniqueIndex,
            const PlacementCellSet& cellSet);
        void CommitTransparent(
            RenderCore::Metal::DeviceContext* context,
            RenderCore::Techniques::ParsingContext& parserContext,
            unsigned techniqueIndex, RenderCore::Assets::DelayStep delayStep);
        bool HasPrepared(RenderCore::Assets::DelayStep delayStep);

            // -------------- Cull --------------
        void CullToPreparedScene(
            PreparedScene& preparedScene,
            RenderCore::Techniques::ParsingContext& parserContext,
            const PlacementCellSet& cellSet);

            // -------------- Render filtered --------------
        using DrawCallPredicate = std::function<bool(const RenderCore::Assets::DelayedDrawCall&)>;
        void RenderFiltered(
            RenderCore::Metal::DeviceContext* context,
            RenderCore::Techniques::ParsingContext& parserContext,
            unsigned techniqueIndex,
            const PlacementCellSet& cellSet,
            const PlacementGUID* begin, const PlacementGUID* end,
            const DrawCallPredicate& predicate = DrawCallPredicate(nullptr));

            // -------------- Utilities --------------
        auto GetVisibleQuadTrees(const PlacementCellSet& cellSet, const Float4x4& worldToClip) const
            -> std::vector<std::pair<Float3x4, const PlacementsQuadTree*>>;

        struct ObjectBoundingBoxes { const std::pair<Float3, Float3> * _boundingBox; unsigned _stride; unsigned _count; };
        auto GetObjectBoundingBoxes(const PlacementCellSet& cellSet, const Float4x4& worldToClip) const
            -> std::vector<std::pair<Float3x4, ObjectBoundingBoxes>>;

        void SetImposters(std::shared_ptr<DynamicImposters> imposters);

        PlacementsRenderer(
            std::shared_ptr<PlacementsCache> placementsCache,
            std::shared_ptr<RenderCore::Assets::ModelCache> modelCache);
        ~PlacementsRenderer();
    protected:
        class Pimpl;
        std::unique_ptr<Pimpl> _pimpl;
    };

    class PlacementsIntersections
    {
    public:
                // -------------- Intersections --------------
        class IntersectionDef
        {
        public:
            Float3x4    _localToWorld;
            std::pair<Float3, Float3> _localSpaceBoundingBox;
            uint64      _model;
            uint64      _material;
        };

        std::vector<PlacementGUID> Find_BoxIntersection(
            const PlacementCellSet& cellSet,
            const Float3& worldSpaceMins, const Float3& worldSpaceMaxs,
            const std::function<bool(const IntersectionDef&)>& predicate);

        std::vector<PlacementGUID> Find_RayIntersection(
            const PlacementCellSet& cellSet,
            const Float3& rayStart, const Float3& rayEnd,
            const std::function<bool(const IntersectionDef&)>& predicate);

        std::vector<PlacementGUID> Find_FrustumIntersection(
            const PlacementCellSet& cellSet,
            const Float4x4& worldToProjection,
            const std::function<bool(const IntersectionDef&)>& predicate);

        PlacementsIntersections(
            std::shared_ptr<PlacementsCache> placementsCache,
            std::shared_ptr<RenderCore::Assets::ModelCache> modelCache);
        ~PlacementsIntersections();
    protected:
        class Pimpl;
        std::unique_ptr<Pimpl> _pimpl;
    };

    class PlacementsEditor
    {
    public:
        typedef Float3x4 PlacementsTransform;

        class ObjTransDef
        {
        public:
            Float3x4        _localToWorld;
            std::string     _model;
            std::string     _material;
            std::string     _supplements;

            ObjTransDef() {}
            ObjTransDef(const Float3x4& localToWorld, const std::string& model, const std::string& material, const std::string& supplements)
                : _localToWorld(localToWorld), _model(model), _material(material), _supplements(supplements), _transaction(Error) {}

            enum TransactionType { Unchanged, Created, Deleted, Modified, Error };
            TransactionType _transaction;
        };

            // -------------- transactions --------------
        class ITransaction
        {
        public:
            virtual const ObjTransDef&  GetObject(unsigned index) const = 0;
            virtual const ObjTransDef&  GetObjectOriginalState(unsigned index) const = 0;
            virtual PlacementGUID       GetGuid(unsigned index) const = 0;
            virtual PlacementGUID       GetOriginalGuid(unsigned index) const = 0;
            virtual unsigned            GetObjectCount() const = 0;
            virtual auto                GetLocalBoundingBox(unsigned index) const -> std::pair<Float3, Float3> = 0;
            virtual auto                GetWorldBoundingBox(unsigned index) const -> std::pair<Float3, Float3> = 0;
            virtual std::string         GetMaterialName(unsigned objectIndex, uint64 materialGuid) const = 0;

            virtual void    SetObject(unsigned index, const ObjTransDef& newState) = 0;
            virtual bool    Create(const ObjTransDef& newState) = 0;
            virtual bool    Create(PlacementGUID guid, const ObjTransDef& newState) = 0;
            virtual void    Delete(unsigned index) = 0;

            virtual void    Commit() = 0;
            virtual void    Cancel() = 0;
            virtual void    UndoAndRestart() = 0;
        };

        struct TransactionFlags {
            enum Flags { IgnoreIdTop32Bits = 1<<1 };
            typedef unsigned BitField;
        };
        std::shared_ptr<ITransaction> Transaction_Begin(
            const PlacementGUID* placementsBegin, const PlacementGUID* placementsEnd,
            TransactionFlags::BitField transactionFlags = 0);

        uint64  CreateCell(const ::Assets::ResChar name[], const Float2& mins, const Float2& maxs);
        bool    RemoveCell(uint64 id);
        static uint64 GenerateObjectGUID();
        void    PerformGUIDFixup(PlacementGUID* begin, PlacementGUID* end) const;

        std::pair<Float3, Float3> CalculateCellBoundary(uint64 cellId) const;

        std::string GetMetricsString(uint64 cellId) const;
        void WriteAllCells();
        void WriteCell(uint64 cellId, const Assets::ResChar destinationFile[]) const;

        std::pair<Float3, Float3> GetModelBoundingBox(const Assets::ResChar modelName[]) const;

        std::shared_ptr<PlacementsManager> GetManager();
        const PlacementCellSet& GetCellSet() const;

        PlacementsEditor(
            std::shared_ptr<PlacementCellSet> cellSet,
            std::shared_ptr<PlacementsManager> manager,
            std::shared_ptr<PlacementsCache> placementsCache,
            std::shared_ptr<RenderCore::Assets::ModelCache> modelCache);
        ~PlacementsEditor();
    protected:
        class Pimpl;
        std::unique_ptr<Pimpl> _pimpl;

        friend class Transaction;
    };

}


text:
using System;
using System.ComponentModel;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

using Shadowsocks.Util;

namespace Shadowsocks.Controller
{
    public class Logging
    {
        public static string LogFilePath;

        private static FileStream _fs;
        private static StreamWriterWithTimestamp _sw;

        public static bool OpenLogFile()
        {
            try
            {
                LogFilePath = Utils.GetTempPath("shadowsocks.log");

                _fs = new FileStream(LogFilePath, FileMode.Append);
                _sw = new StreamWriterWithTimestamp(_fs);
                _sw.AutoFlush = true;
                Console.SetOut(_sw);
                Console.SetError(_sw);

                return true;
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                return false;
            }
        }

        private static void WriteToLogFile(object o)
        {
            try {
                Console.WriteLine(o);
            } catch(ObjectDisposedException) {
            }
        }

        public static void Error(object o)
        {
            WriteToLogFile("[E] " + o);
        }

        public static void Info(object o)
        {
            WriteToLogFile(o);
        }

        public static void Clear() {
            _sw.Close();
            _sw.Dispose();
            _fs.Close();
            _fs.Dispose();
            File.Delete(LogFilePath);
            OpenLogFile();
        }

        [Conditional("DEBUG")]
        public static void Debug(object o)
        {
            WriteToLogFile("[D] " + o);
        }

        [Conditional("DEBUG")]
        public static void Debug(EndPoint local, EndPoint remote, int len, string header = null, string tailer = null)
        {
            if (header == null && tailer == null)
                Debug($"{local} => {remote} (size={len})");
            else if (header == null && tailer != null)
                Debug($"{local} => {remote} (size={len}), {tailer}");
            else if (header != null && tailer == null)
                Debug($"{header}: {local} => {remote} (size={len})");
            else
                Debug($"{header}: {local} => {remote} (size={len}), {tailer}");
        }

        [Conditional("DEBUG")]
        public static void Debug(Socket sock, int len, string header = null, string tailer = null)
        {
            Debug(sock.LocalEndPoint, sock.RemoteEndPoint, len, header, tailer);
        }

        public static void LogUsefulException(Exception e)
        {
            // just log useful exceptions, not all of them
            if (e is SocketException)
            {
                SocketException se = (SocketException)e;
                if (se.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    // closed by browser when sending
                    // normally happens when download is canceled or a tab is closed before page is loaded
                }
                else if (se.SocketErrorCode == SocketError.ConnectionReset)
                {
                    // received rst
                }
                else if (se.SocketErrorCode == SocketError.NotConnected)
                {
                    // The application tried to send or receive data, and the System.Net.Sockets.Socket is not connected.
                }
                else if (se.SocketErrorCode == SocketError.HostUnreachable)
                {
                    // There is no network route to the specified host.
                }
                else if (se.SocketErrorCode == SocketError.TimedOut)
                {
                    // The connection attempt timed out, or the connected host has failed to respond.
                }
                else
                {
                    Info(e);
                }
            }
            else if (e is ObjectDisposedException)
            {
            }
            else if (e is Win32Exception)
            {
                var ex = (Win32Exception) e;

                // Win32Exception (0x80004005): A 32 bit processes cannot access modules of a 64 bit process.
                if ((uint) ex.ErrorCode != 0x80004005)
                {
                    Info(e);
                }
            }
            else
            {
                Info(e);
            }
        }
    }

    // Simply extended System.IO.StreamWriter for adding timestamp workaround
    public class StreamWriterWithTimestamp : StreamWriter
    {
        public StreamWriterWithTimestamp(Stream stream) : base(stream)
        {
        }

        private string GetTimestamp()
        {
            return "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ";
        }

        public override void WriteLine(string value)
        {
            base.WriteLine(GetTimestamp() + value);
        }

        public override void Write(string value)
        {
            base.Write(GetTimestamp() + value);
        }
    }

}


text:
<component name="libraryTable">
  <library name="SBT: org.apache.httpcomponents:httpcore:4.2.4:jar">
    <CLASSES>
      <root url="jar://G:/.ivy2/cache/org.apache.httpcomponents/httpcore/jars/httpcore-4.2.4.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://G:/.ivy2/cache/org.apache.httpcomponents/httpcore/srcs/httpcore-4.2.4-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#0000ff">

    <Button
        android:id="@+id/left_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:background="@mipmap/icon"/>

    <TextView
        android:id="@+id/title_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="这是标题"
        android:textColor="#ffffff"
        android:textSize="20sp"/>

</RelativeLayout>


text:
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to you 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.
-->

<faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
  version="1.2">
  <application>
    <action-listener>action-listener1</action-listener>
    <action-listener>action-listener2</action-listener>
    <default-render-kit-id>default-render-kit-id</default-render-kit-id>
    <locale-config>
      <default-locale>aa</default-locale>
      <supported-locale>aa</supported-locale>
      <supported-locale>bb</supported-locale>
    </locale-config>
    <message-bundle>message-bundle</message-bundle>
    <navigation-handler>navigation-handler</navigation-handler>
    <property-resolver>property-resolver</property-resolver>
    <state-manager>state-manager</state-manager>
    <variable-resolver>variable-resolver</variable-resolver>
    <view-handler>view-handler</view-handler>

    <!-- 1.2 specific -->
    <el-resolver>el-resolver</el-resolver>
    <resource-bundle>
      <base-name>base-name</base-name>
      <var>var</var>
    </resource-bundle>
  </application>
</faces-config>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

<title>NUnit - ContextMenu</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta http-equiv="Content-Language" content="en-US">
<link rel="stylesheet" type="text/css" href="nunit.css">
<link rel="shortcut icon" href="favicon.ico">

    NUnit
    Documentation

Context Menu

The context menu is displayed when one of the tree nodes is right-clicked.

Run

Runs the selected test - disabled if a test is running.

Run All

Runs all the tests.

Run Failed

Runs only the tests that failed on the previous run.

Show Checkboxes

Turns the display of checkboxes in the tree on or off. The checkboxes may
   be used to select multiple tests for running.

Expand

Expands the selected test node – invisible if the node is expanded or has no children.

Collapse

Collapses the selected test node – invisible if the node is collapsed or has no children.

Expand All

Expands all nodes of the tree.

Collapse All

Collapses all nodes in the tree to the root.

Load Fixture

Reloads only the currently selected fixture or namespace. The fixture,
once loaded, remains in effect through any subsequent reloads. This generally
results in substantial reduction in load time.

Clear Fixture

Reloads all the tests, clearing the currently loaded fixture.

Properties

Displays the Test Properties for the selected test node.

NUnit 2.4.8

Getting Started

Assertions

Attributes

Console Runner

Gui Runner

Command-Line

Main Menu

Context Menu

Options Dialog

Addins Dialog

Test Properties

Configuration Editor

Project Editor

Other Features

Release Notes

Samples

License

  Copyright © 2008 Charlie Poole. All Rights Reserved.


text:
package ru.stqa.pft.addressbook.tests;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.thoughtworks.xstream.XStream;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.Contactdata;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import ru.stqa.pft.addressbook.model.Groups;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class ContactCreationTests extends TestBase {

  @DataProvider
  public Iterator<Object []> validContactsFromXml () throws IOException {
   try (BufferedReader reader = new BufferedReader
           (new FileReader(new File ("src/test/resources/contact.xml")))) {
     String xml = "";
     String line = reader.readLine();
     while (line != null) {
       xml += line;
       line = reader.readLine();
     }
     XStream xstream = new XStream();
     xstream.processAnnotations(Contactdata.class);
     List<Contactdata> contacts = (List<Contactdata>) xstream.fromXML(xml);
     return contacts.stream().map((g) -> new Object[]{g}).collect(Collectors.toList()).iterator();
   }
  }
  @DataProvider
  public Iterator<Object []> validContactsFromJson () throws IOException {
   try  (BufferedReader reader = new BufferedReader
           (new FileReader(new File ("src/test/resources/contact.json")))) {
    String json = "";
    String line = reader.readLine();
    while (line != null) {
      json += line;
      line = reader.readLine();
    }
    Gson gson = new Gson();
    List<Contactdata> contacts = gson.fromJson(json,new TypeToken<List<Contactdata>>() {}.getType ());
    return contacts.stream().map((g) -> new Object[] {g}).collect(Collectors.toList()).iterator();
   }
  }
  @BeforeMethod
  public void ensurePreconditions () {
    if (app.db().groups().size() == 0) {
      app.goTo().GroupPage();
      app.group().create(new GroupData().withName("Test1"));

    }
  }

  @Test (dataProvider = "validContactsFromJson")
  public void ContactCreationTests(Contactdata contact) {
      Groups groups = app.db().groups();
       File photo = new File("src/test/resources/WIN_20171006_09_52_45_Pro.jpg");
       Contactdata newContact = new Contactdata().withFirstname("Katya").withLastname("Ivanova").withPhoto(photo)
               .inGroup(groups.iterator().next());
       app.goTo().HomePage();
      Contacts before = app.db().contacts();
      app.contact().createС(newContact, true);
      app.goTo().HomePage();
      assertThat(app.contact().count(), equalTo(before.size() + 1));
      Contacts after = app.db().contacts();
      assertThat( after, equalTo(before
              .withAdded(contact.withId(after.stream()
                      .mapToInt((g) -> g.getId()).max().getAsInt()))));
  }

  @Test (enabled = false)
  public void ContactBadCreationTests() {
    Groups groups = app.db().groups();
    app.goTo().HomePage();
    Contacts before = app.db().contacts();
    Contactdata contact = new Contactdata().withFirstname("Elena'").withLastname("Voskresenskaya")
            .withAddress("Lvovskaya Street, 15").withHomePhone("7472304").withMobilePhone("0966514669")
            .withWorkPhone("353748").withEmail("skyLena1@ya.ru")
            .inGroup(groups.iterator().next());
    app.contact().createС(contact, true);
    app.goTo().HomePage();
    assertThat (app.contact().count(), equalTo(before.size()));
    Contacts after = app.db().contacts();
    assertThat (after, equalTo(before));
    verifyContactsListInUi();
  }

  @Test (enabled = false)
  public void testCurrentDir () {
    File currentDir = new File (".");
    System.out.println(currentDir.getAbsolutePath());
    File photo = new File ("src/test/resources/WIN_20171006_09_52_45_Pro.jpg");
    System.out.println(photo.getAbsolutePath());
    System.out.println(photo.exists());
  }
}


text:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-26564585-4']);
_gaq.push(['_trackPageview']);

var service = analytics.getService('Postman - REST Client (Packaged app)');
var tracker = service.getTracker('UA-43979731-6');
// TODO - add permission for tracking users.
tracker.sendAppView('MainView');


text:
<!doctype html>

    <meta charset="utf-8">

<title>ServiceComb Service-Center Downloads - Apache ServiceComb (incubating)</title>

<meta name="description" content="ServiceComb Service-Center Downloads">

<meta name="author" content="">

<meta property="og:locale" content="cn">
<meta property="og:site_name" content="Apache ServiceComb (incubating)">
<meta property="og:title" content="ServiceComb Service-Center Downloads">

  <link rel="canonical" href="http://github.com/pages/apache/incubator-servicecomb-website/cn/release/service-center-downloads/">
  <meta property="og:url" content="http://github.com/pages/apache/incubator-servicecomb-website/cn/release/service-center-downloads/">

  <meta property="og:description" content="ServiceComb Service-Center Downloads">

  <meta name="twitter:site" content="@ServiceComb">
  <meta name="twitter:title" content="ServiceComb Service-Center Downloads">
  <meta name="twitter:description" content="ServiceComb Service-Center Downloads">
  <meta name="twitter:url" content="">

    <meta name="twitter:card" content="summary">

  <meta name="google-site-verification" content="HvJjNd7vvJ-yjSTHlBiIWEYxp_Hrz-PYEY5Idz9LRcA" />

<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="Apache ServiceComb (incubating) Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<link rel="stylesheet" href="/assets/css/main.css">
<link rel="stylesheet" href="/assets/vendor/prism/prism.css">

<meta http-equiv="cleartype" content="on">

<link href="https://fonts.cat.net/css?family=Roboto:400,500,700|Source+Code+Pro" rel="stylesheet">

                快速入门

                用户手册

                开发者手册

                博文

                常见问题

                下载

        <button>

</button>

            English

首页 > ServiceComb

  <input id="ac-toc" name="accordion-toc" type="checkbox" />
  切换菜单

          Service-Center

发布说明

发布包

          Java-Chassis

发布说明

发布包

          Saga

发布说明

发布包

    <meta itemprop="headline" content="ServiceComb Service-Center Downloads">
    <meta itemprop="description" content="ServiceComb Service-Center Downloads">

    <meta itemprop="dateModified" content="March 28, 2018">

ServiceComb Service-Center Downloads

Releases

Apache ServiceComb (incubating) Service-Center 1.0.0-m1

Source [src] [asc] [sha512]

Windows [Binary] [asc] [sha512]

Linux [Binary] [asc] [sha512]

Verifying the release

It is essential that you verify the integrity of the downloaded files using the PGP or SHA signatures.
 The PGP signatures can  be verified using GPG or PGP.
 Please download the KEYS as well as the asc signature files for relevant distribution. It is recommended to get these files from the main distribution directory and not from the mirrors.

 gpg -i KEYS

 or

 pgpk -a KEYS

 or

 pgp -ka KEYS

To verify the binaries/sources you can download the relevant asc files for it from main distribution directory and follow the below guide.

gpg --verify apache-servicecomb-incubating-service-center-********.asc apache-servicecomb-incubating-service-center-*********

or

pgpv apache-servicecomb-incubating-service-center-********.asc

or

pgp apache-servicecomb-incubating-service-center-********.asc

Alternatively you can download the SHA signatures from main distribution repo and verify the downloads using sha512sum.

资源

快速入门

用户指南

资料

常见问题

贡献

报告本网页问题

在Github上编辑此页

代码提交指南

社区

            邮件列表

            Github

            Twitter

            Feed

© 2018 Apache ServiceComb (incubating). 技术来自于 Jekyll & Minimal Mistakes.


text:
<?php

require_once 'modules/WSAPP/synclib/models/BaseModel.php';

class WSAPP_SyncStateModel extends WSAPP_BaseModel{

	// Represents the module which will the synchronize will happen
	protected $type;

	public function getLastSyncTime(){
		return $this->get('lastSyncTime');
	}

	public function setLastSyncTime($lastSyncTime){
		return $this->set('lastSyncTime',$lastSyncTime);
	}

	public function setMoreRecords($more){
		return $this->set('more',$more);
	}

	public function hasMoreRecords(){
		return ($this->get('more')==1) ? true : false;
	}

	public function getSyncTrackerId(){
		return $this->get('synctrackerid');
	}

	public function setSyncTrackerId($value){
		return $this->set('synctrackerid',$value);
	}

	public function getSyncToken(){
		return $this->get('synctoken');
	}

	public function setSyncToken($syncToken){
		return $this->set('synctoken',$syncToken);
	}

	public function setType($type){
		$this->type = $type;
		return $this;
	}

	public function getType(){
		return $this->type;
	}

	public function getInstanceFromSyncResult($syncResult){
		$model = new self();
		return $model->setLastSyncTime($syncResult['lastModifiedTime'])->setMoreRecords($syncResult['more']);
	}

	public function getInstanceFromQueryResult($rowData){
		$model = new self();
		return $model->setData($rowData);
	}

}

?>