text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using com.calitha.goldparser;
using Epi.Core.EnterInterpreter.Rules;
using EpiInfo.Plugin;
using Epi.FormMetadata.DataStructures.Interfaces;

namespace Epi.Core.EnterInterpreter
{
    public class Rule_Context : ICommandContext
    {
        public IEnterInterpreterHost EnterCheckCodeInterface;
        public StringBuilder ProgramText;
        /*public System.Collections.Specialized.NameValueCollection PermanantVariables;
public System.Collections.Specialized.NameValueCollection GlobalVariables;*/
        public System.Collections.Generic.Dictionary<string, string> StandardVariables;
        public System.Collections.Generic.Dictionary<string, string> AssignVariableCheck;
        public Dictionary<string, List<string>> GroupVariableList;
        //private IMemoryRegion memoryRegion;
        private IScope currentScope;

        public Rule_DefineVariables_Statement DefineVariablesCheckcode;
        public Rule_View_Checkcode_Statement View_Checkcode;
        public Rule_Record_Checkcode_Statement Record_Checkcode;

        public System.Collections.Generic.Dictionary<string, IDLLClass> DLLClassList;

        public System.Collections.Generic.Dictionary<string, EnterRule> Page_Checkcode;
        public System.Collections.Generic.Dictionary<string, EnterRule> Field_Checkcode;

        public System.Collections.Generic.Dictionary<string, EnterRule> BeforeCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> AfterCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> PageBeforeCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> PageAfterCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> FieldBeforeCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> FieldAfterCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> FieldClickCheckCode;
        public System.Collections.Generic.Dictionary<string, EnterRule> Subroutine;
        public System.Collections.Generic.Dictionary<string, EnterRule> OuterSubroutine;

        public System.Text.StringBuilder JavaScriptVariableDefinitions;

        public List<string> _HiddenFieldList;
        public List<string> _HighlightedFieldList;
        public List<string> _DisabledFieldList;
        public List<string> _RequiredFieldList;

        public string HiddenFieldList
        {
            get
            {
                StringBuilder result = new StringBuilder();
                foreach (string s in _HiddenFieldList)
                {
                    result.Append(s);
                    result.Append(',');
                }
                return result.ToString();
            }
            set
            {
                string[] list = value.Split(',');
                _HiddenFieldList.Clear();
                foreach (string s in list)
                {
                    _HiddenFieldList.Add(s.ToLower());
                }
            }
        }

        public string HighlightedFieldList
        {
            get
            {
                StringBuilder result = new StringBuilder();
                foreach (string s in _HighlightedFieldList)
                {
                    result.Append(s);
                    result.Append(',');
                }
                return result.ToString();
            }
            set
            {
                string[] list = value.Split(',');
                _HighlightedFieldList.Clear();
                foreach (string s in list)
                {
                    _HighlightedFieldList.Add(s.ToLower());
                }
            }
        }

        public string DisabledFieldList
        {
            get
            {
                StringBuilder result = new StringBuilder();
                foreach (string s in _DisabledFieldList)
                {
                    result.Append(s);
                    result.Append(',');
                }
                return result.ToString();
            }
            set
            {
                string[] list = value.Split(',');
                _DisabledFieldList.Clear();
                foreach (string s in list)
                {
                    _DisabledFieldList.Add(s.ToLower());
                }
            }
        }

        public string RequiredFieldList
        {
            get
            {
                StringBuilder result = new StringBuilder();
                foreach (string s in _RequiredFieldList)
                {
                    result.Append(s);
                    result.Append(',');
                }
                return result.ToString();
            }
            set
            {
                string[] list = value.Split(',');
                _RequiredFieldList.Clear();
                foreach (string s in list)
                {
                    _RequiredFieldList.Add(s.ToLower());
                }
            }
        }

        private string[] parseGetCommandSearchText(string pSearchText)
        {
            string[] result = null;

            string[] temp = pSearchText.Split('&');
            result = new string[temp.Length];
            for (int i = 0; i < temp.Length; i++)
            {
                result[i] = temp[i].Split('=')[1];
            }

            return result;
        }

        public IScope Scope { get { return this.currentScope; } }

        public ICommand GetCommand(string pSearchText)
        {
            ICommand result = null;
            string Level = null;
            string Event = null;
            string Identifier = null;

            //string SearchRule = null;

            string[] Parameters = parseGetCommandSearchText(pSearchText);
            Level = Parameters[0].ToLower();
            Event = Parameters[1].ToLower();
            Identifier = Parameters[2].ToLower();

            switch (Level.ToLower())
            {
                case "view":
                    if (Event.ToLower() == "")
                    {
                        result = this.View_Checkcode;
                    }
                    else
                    if (Event.ToLower() == "before")
                    {
                        if (this.BeforeCheckCode.ContainsKey("view"))
                        {
                            result = this.BeforeCheckCode["view"];
                        }
                    }
                    else if (Event.ToLower() == "after")
                    {
                        if (this.AfterCheckCode.ContainsKey("view"))
                        {
                            result = this.AfterCheckCode["view"];
                        }
                    }
                    break;
                case "record":
                    if (Event.ToLower() == "")
                    {
                        result = this.Record_Checkcode;
                    }
                    else
                    if (Event.ToLower() == "before")
                    {
                        if (this.BeforeCheckCode.ContainsKey("record"))
                        {
                            result = this.BeforeCheckCode["record"];
                        }
                    }
                    else if (Event.ToLower() == "after")
                    {
                        if (this.AfterCheckCode.ContainsKey("record"))
                        {
                            result = this.AfterCheckCode["record"];
                        }
                    }
                    break;
                case "page":
                    if (Event.ToLower() == "")
                    {
                        if (this.Page_Checkcode.ContainsKey(Identifier))
                        {
                            result = this.Page_Checkcode[Identifier];
                        }
                    }
                    else
                    if (Event.ToLower() == "before")
                    {
                        if (this.PageBeforeCheckCode.ContainsKey(Identifier))
                        {
                            result = this.PageBeforeCheckCode[Identifier];
                        }
                    }
                    else if (Event.ToLower() == "after")
                    {
                        if (this.PageAfterCheckCode.ContainsKey(Identifier))
                        {
                            result = this.PageAfterCheckCode[Identifier];
                        }
                    }
                    break;
                case "field":
                    if (Event.ToLower() == "")
                    {
                        if (this.Field_Checkcode.ContainsKey(Identifier))
                        {
                            result = this.Field_Checkcode[Identifier];
                        }
                    }
                    else
                    if (Event.ToLower() == "before")
                    {
                        if (this.FieldBeforeCheckCode.ContainsKey(Identifier))
                        {
                            result = this.FieldBeforeCheckCode[Identifier];
                        }
                    }
                    else if (Event.ToLower() == "after")
                    {
                        if (this.FieldAfterCheckCode.ContainsKey(Identifier))
                        {
                            result = this.FieldAfterCheckCode[Identifier];
                        }
                    }
                    else if (Event.ToLower() == "click")
                    {
                        if (this.FieldClickCheckCode.ContainsKey(Identifier))
                        {
                            result = this.FieldClickCheckCode[Identifier];
                        }
                    }
                    break;
                case "sub":
                    if (this.Subroutine.ContainsKey(Event))
                    {
                        result = this.Subroutine[Event];
                    }
                    break;
                case "definevariables":
                    result = this.DefineVariablesCheckcode;
                    break;
            }

            return result;
        }

        public IScope CurrentScope
        {
            get { return this.currentScope; }
        }
        /*
        public IMemoryRegion MemoryRegion
        {
            get
            {
                return this.memoryRegion;
            }

            set { this.memoryRegion = value; }
        }*/

        public Rule_Context()
        {
            this.currentScope = new cSymbolTable("global", null);
            //Rule_Context.LoadPermanentVariables(this.currentScope);
            this.Initialize();
        }

        public Rule_Context(IScope pScope)
        {
            this.currentScope = new cSymbolTable(pScope);
            this.Initialize();
        }

        private void Initialize()
        {
            //this.memoryRegion = new MemoryRegion();

            //this.currentScope = new cSymbolTable(null);

            this.ProgramText = new StringBuilder();
            this.JavaScriptVariableDefinitions = new StringBuilder();
            this.DLLClassList = new Dictionary<string, IDLLClass>(StringComparer.OrdinalIgnoreCase);

            this._HiddenFieldList = new List<string>();
            this._HighlightedFieldList = new List<string>();
            this._DisabledFieldList = new List<string>();
            this._RequiredFieldList = new List<string>();

            //this.DefineVariablesCheckCode = new Rule_DefineVariables_Statement();
            this.GroupVariableList = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);

            this.Page_Checkcode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.Field_Checkcode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);

            this.BeforeCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.AfterCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.PageBeforeCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.PageAfterCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.FieldBeforeCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.FieldAfterCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.FieldClickCheckCode = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.Subroutine = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);
            this.OuterSubroutine = new Dictionary<string, EnterRule>(StringComparer.OrdinalIgnoreCase);

        }

        /*
        public static void DeletePermanentVariable(string variableName)
        {

            Configuration config = Configuration.GetNewInstance();
            DataRow[] result = config.PermanentVariables.Select("Name='" + variableName + "'");
            if (result.Length != 1)
            {
                throw new ConfigurationException(ConfigurationException.ConfigurationIssue.ContentsInvalid);
            }
            result[0].Delete();
            Configuration.Save(config);
        }

        public static void UpdatePermanentVariable(EpiInfo.Plugin.IVariable variable)
        {

            Configuration config = Configuration.GetNewInstance();
            DataRow[] result = config.PermanentVariables.Select("Name='" + variable.Name + "'");
            if (result.Length < 1)
            {
                config.PermanentVariables.AddPermanentVariableRow(
                   variable.Name,
                   variable.Expression ?? "",
                    (int)variable.DataType,
                   config.ParentRowPermanentVariables);
            }
            else if (result.Length == 1)
            {
                ((DataSets.Config.PermanentVariableRow)result[0]).DataValue = variable.Expression ?? "";
                ((DataSets.Config.PermanentVariableRow)result[0]).DataType = (int)variable.DataType;
            }
            else
            {
                throw new ConfigurationException(ConfigurationException.ConfigurationIssue.ContentsInvalid, "Duplicate permanent variable rows encountered.");
            }

            Configuration.Save(config);
        }

        public static void LoadPermanentVariables(IScope pScope)
        {
            //lock (syncLock)
            //{

                Configuration config = Configuration.GetNewInstance();
                foreach (Epi.DataSets.Config.PermanentVariableRow row in config.PermanentVariables)
                {
                    EpiInfo.Plugin.IVariable var = new PluginVariable(row.Name, (EpiInfo.Plugin.DataType)row.DataType, VariableScope.Permanent, row.DataValue);
                    pScope.define(var);
                }
            //}
        }*/

        public object GetVariable(string name)
        {
            object result = null;
            //result = StandardVariables[name];
            result = this.currentScope.resolve(name);
            return result;
        }

        public bool SetVariable(string name, object setValue)//, Epi.VariableType pType)
        {
            bool result = false;
            string value = setValue.ToString();
            if (StandardVariables.ContainsKey(name))
            {
                StandardVariables[name] = value;
            }
            else
            {
                StandardVariables.Add(name, setValue.ToString());
            }

            return result;
        }

        /// <summary>
        /// Clears the session state
        /// </summary>
        public void ClearState()
        {
            this.currentScope.RemoveVariablesInScope(EpiInfo.Plugin.VariableScope.Standard, this.Scope.Name);
            //this.currentScope.RemoveVariablesInScope(EpiInfo.Plugin.VariableScope.Global);
            this.DefineVariablesCheckcode = null;
            this.View_Checkcode = null;
            this.Record_Checkcode = null;
            this.Page_Checkcode.Clear();
            this.Field_Checkcode.Clear();

            //this.MemoryRegion.RemoveVariablesInScope(VariableType.DataSource);
            //this.MemoryRegion.RemoveVariablesInScope(VariableType.DataSourceRedefined);

            //VariableCollection vars = module.Processor.GetVariablesInScope(VariableType.DataSource | VariableType.Standard | VariableType.DataSourceRedefined);
            //foreach (IVariable var in vars)
            //{
            //    module.Processor.UndefineVariable(var.Name);
            //}

            // Remove the current DataSourceInfo object and create a new one.
            this.BeforeCheckCode.Clear();
            this.AfterCheckCode.Clear();
            this.PageBeforeCheckCode.Clear();
            this.PageAfterCheckCode.Clear();
            this.FieldBeforeCheckCode.Clear();
            this.FieldAfterCheckCode.Clear();
            this.FieldClickCheckCode.Clear();
            this.Subroutine.Clear();
            //this.ProgramText.Length = 0;
        }

        public List<EpiInfo.Plugin.IVariable> GetVariablesInScope()
        {
            return this.currentScope.FindVariables(VariableScope.DataSource | VariableScope.DataSourceRedefined | VariableScope.Global | VariableScope.Permanent | VariableScope.Standard | VariableScope.System | VariableScope.Undefined);
        }

        public List<EpiInfo.Plugin.IVariable> GetVariablesInScope(VariableScope scopeCombination)
        {
            return this.currentScope.FindVariables(scopeCombination);
        }

        public bool TryGetVariable(string p, out EpiInfo.Plugin.IVariable var)
        {
            bool result = false;
            var = null;

            var = this.currentScope.resolve(p);

            if (var != null)
            {
                result = true;
            }
            return result;
        }

        public void RemoveVariablesInScope(VariableScope varTypes)
        {
            this.currentScope.RemoveVariablesInScope(varTypes);
        }

        public void DefineVariable(EpiInfo.Plugin.IVariable variable)
        {
            this.currentScope.define(variable);
        }

        public void UndefineVariable(string varName)
        {
            this.currentScope.undefine(varName);
        }

        private NonterminalToken FindBlock(NonterminalToken pT, string pSearchRule, string pIdentifier)
        {
            NonterminalToken result = null;
            NonterminalToken currentToken = pT;

            while (currentToken != null)
            {
                if (currentToken.Rule.Lhs.ToString().ToLower() == pSearchRule.ToLower())
                {
                    switch (pSearchRule)
                    {
                        case "<Field_Checkcode_Statement>":
                        case "<Page_Checkcode_Statement>":
                        case "<Subroutine_Statement>":
                            if (currentToken.Tokens[1].ToString().ToLower() == pIdentifier.ToLower())
                            {
                                result = currentToken;
                                return result;
                            }
                            break;
                        default:
                            result = currentToken;
                            return result;
                    }
                }

                if (currentToken.Tokens[0] is NonterminalToken)
                {
                    switch (currentToken.Rule.Rhs[0].ToString())
                    {
                        case "<Statements>":
                            currentToken = (NonterminalToken)currentToken.Tokens[1];
                            break;
                        case "<Statement>":
                        default:
                            currentToken = (NonterminalToken)currentToken.Tokens[0];
                            break;
                    }
                }
                else
                {
                    break;
                }
            }
            return result;
        }

        public void CheckAssignedVariables()
        {
            foreach (System.Collections.Generic.KeyValuePair<string, string> i in this.AssignVariableCheck)
            {
                if (this.currentScope.resolve(i.Key) == null)
                {
                    //throw new Exception(string.Format("variable {0} assigned but NOT defined", i.Key));
                }
            }
        }

        public IScope GetNewScope(string pName, IScope pParent)
        {
            return new cSymbolTable(pName, pParent);
        }

        public void LoadTemplate(IEnumerable<IAbridgedFieldInfo> fields, Dictionary<string, string> responseQA)
        {
            string pageNumber = "";

            foreach (var field in fields)
            {
                PluginVariable var = new PluginVariable();
                var.Name = field.FieldName;
                var.VariableScope = VariableScope.DataSource;
                var.PageNumber = pageNumber;

                if (responseQA != null && responseQA.Count > 0)
                {
                    var.Expression = GetControlValue(responseQA, var.Name);
                }

                switch ((int)field.FieldType)
                {
                    case 1: // textbox
                        var.DataType = DataType.Text;
                        var.ControlType = "textbox";
                        break;

                    case 2://Label/Title
                        var.DataType = DataType.Text;
                        var.ControlType = "label";
                        break;

                    case 3://Label
                        var.DataType = DataType.Text;
                        var.ControlType = "label";
                        continue;

                    case 4://MultiLineTextBox
                        var.DataType = DataType.Text;
                        var.ControlType = "multiline";
                        break;

                    case 5://NumericTextBox
                        var.DataType = DataType.Number;
                        var.ControlType = "numeric";
                        break;

                    case 7:// 7 DatePicker
                        var.DataType = DataType.Date;
                        var.ControlType = "datepicker";
                        break;

                    case 8: //TimePicker
                        var.DataType = DataType.Time;
                        var.ControlType = "timepicker";
                        break;

                    case 10://CheckBox
                        var.DataType = DataType.Boolean;
                        var.ControlType = "checkbox";
                        break;

                    case 11://DropDown Yes/No
                        var.DataType = DataType.Boolean;
                        var.ControlType = "yesno";
                        break;

                    case 12://RadioButton
                        var.DataType = DataType.Number;
                        var.ControlType = "radiobutton";
                        break;

                    case 17://DropDown LegalValues
                        var.DataType = DataType.Text;
                        var.ControlType = "legalvalues";
                        break;

                    case 18://DropDown Codes
                        var.DataType = DataType.Text;
                        var.ControlType = "codes";
                        break;

                    case 19://DropDown CommentLegal
                        var.DataType = DataType.Text;
                        var.ControlType = "commentlegal";
                        break;
                    case 20://Relate Button
                        var.DataType = DataType.Text;
                        var.ControlType = "relatebutton";
                        //JavaScriptVariableDefinitions.AppendLine(string.Format(defineFormat, _FieldTypeID.Attribute("Name").Value, "commentlegal", "datasource", var.Expression));
                        break;
                    case 21://GroupBox
                        var.DataType = DataType.Unknown;
                        var.ControlType = "groupbox";
                        var.Expression = field.List;
                        string[] IdentifierList = var.Expression.Split(',');
                        string Identifier = field.FieldName;
                        if (this.GroupVariableList.ContainsKey(Identifier))
                        {
                            this.GroupVariableList[Identifier].Clear();
                        }
                        else
                        {
                            this.GroupVariableList.Add(Identifier, new List<string>());
                        }

                        foreach (string s in IdentifierList)
                        {
                            this.GroupVariableList[Identifier].Add(s);
                            this.GroupVariableList[Identifier].Add(Identifier);
                        }

                        break;
                }
                this.DefineVariable(var);
            }
        }

        public static string GetControlValue(Dictionary<string, string> qaResponse, string controlName)
        {
            string controlValue = null;
            qaResponse.TryGetValue(controlName, out controlValue);
            return controlValue ?? string.Empty;
        }

        public void GetVariableJavaScript(StringBuilder pJavaScriptBuilder)
        {
            string defineFormat = "cce_Context.define(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\");";
            string defineNumberFormat = "cce_Context.define(\"{0}\", \"{1}\", \"{2}\", \"{3}\", new Number({4}));";

            foreach (PluginVariable var in this.CurrentScope.FindVariables(VariableScope.DataSource | VariableScope.Global | VariableScope.Permanent | VariableScope.Standard))
            {
                string DataSource;
                switch (var.VariableScope)
                {
                    case VariableScope.DataSource:
                        DataSource = "datasource";
                        break;
                    case VariableScope.Global:
                        DataSource = "global";
                        break;
                    case VariableScope.Permanent:
                        DataSource = "permanent";
                        break;
                    case VariableScope.Standard:
                    default:
                        DataSource = "standard";
                        break;

                }

                switch (var.ControlType)
                {
                    case "checkbox":
                    case "yesno":
                        pJavaScriptBuilder.AppendLine(string.Format(defineFormat, var.Name, var.ControlType, DataSource, var.PageNumber, var.Expression));
                        break;

                    case "numeric":
                        pJavaScriptBuilder.AppendLine(string.Format(defineNumberFormat, var.Name, var.ControlType, DataSource, var.PageNumber, var.Expression));
                        break;
                    case "groupbox":
                        pJavaScriptBuilder.AppendLine(string.Format(defineFormat, var.Name, var.ControlType, DataSource, var.PageNumber, var.Expression));
                        break;
                    case "commentlegal":
                    case "codes":
                    case "legalvalues":
                    case "datepicker":
                    case "timepicker":
                    case "multiline":
                       //// pJavaScriptBuilder.AppendLine(string.Format(defineFormat, var.Name, var.ControlType, DataSource, var.PageNumber, var.Expression.Replace("\n", " ")));
                       // break;
                    case "textbox":

                    default:
                        pJavaScriptBuilder.AppendLine(string.Format(defineFormat, var.Name, var.ControlType, DataSource, var.PageNumber, var.Expression));
                        break;
                }

            }
        }

        public void ExpandGroupVariables(List<string> pIdentifierList, ref bool pIsExceptionList)
        {
            List<string> result = new List<string>();
            List<EpiInfo.Plugin.IVariable> List = this.Scope.FindVariables(VariableScope.DataSource | VariableScope.Standard);

            for (int i = 0; i < pIdentifierList.Count; i++)
            {
                pIdentifierList[i] = pIdentifierList[i].ToUpper();
            }

            if (pIdentifierList.Count == 1 && pIdentifierList[0] == "*")
            {
                pIdentifierList.Clear();

                foreach (DataColumn C in List)
                {
                    pIdentifierList.Add(C.ColumnName.ToUpper());
                }
            }

            if (pIsExceptionList)
            {
                List<string> List2 = new List<string>();

                foreach (DataColumn C in List)
                {
                    List2.Add(C.ColumnName.ToUpper());
                }

                foreach (string s in pIdentifierList)
                {
                    if (this.GroupVariableList.ContainsKey(s))
                    {
                        List<string> GroupVarList = this.GroupVariableList[s];
                        foreach (string Variable in GroupVarList)
                        {
                            if (List2.Contains(Variable.ToUpper()))
                            {
                                List2.Remove(Variable.ToUpper());
                            }
                        }
                    }
                    else
                    {
                        if (List2.Contains(s.ToUpper()))
                        {

                            List2.Remove(s.ToUpper());
                        }
                    }
                }
                pIdentifierList.Clear();

                foreach (string s in List2)
                {
                    pIdentifierList.Add(s);
                }

                pIsExceptionList = false;
            }
            else
            {
                foreach (KeyValuePair<string, List<string>> GroupVarList in this.GroupVariableList)
                {
                    if (pIdentifierList.Contains(GroupVarList.Key.ToUpper()))
                    {
                        pIdentifierList.Remove(GroupVarList.Key.ToUpper());

                        foreach (string Variable in GroupVarList.Value)
                        {
                            if (!pIdentifierList.Contains(Variable.ToUpper()))
                            {
                                pIdentifierList.Add(Variable.ToUpper());
                            }

                        }
                    }
                }
            }
        }

        public void GetSubroutineJavaScript(StringBuilder pJavaScriptBuilder)
        {
            foreach (KeyValuePair<string, EnterRule> kvp in this.OuterSubroutine)
            {
                kvp.Value.ToJavaScript(pJavaScriptBuilder);
            }
        }
    }
}


text:
describe('moveTo()', () => {
    before(() => {
        return coreReady;
    });

    afterEach(() => {
        return Promise.all([gtf.windows.closeAllOtherWindows(), gtf.windows.resetWindowDimensions()]);
    });

    it('Should throw an error when top isn\'t of type number.', (done) => {
        glue.windows.open(gtf.windows.getWindowName(), gtf.windows.SUPPORT_DETAILS.url)
            .then((newlyOpenedWindow) => newlyOpenedWindow.moveTo('42', 42))
            .then(() => done('moveTo() should have thrown an error because top isn\'t of type number!'))
            .catch((error) => {
                try {
                    expect(error.message).to.equal('expected a number, got a string');

                    done();
                } catch (err) {
                    done(err);
                }
            });
    });

    it('Should throw an error when left isn\'t of type number.', (done) => {
        glue.windows.open(gtf.windows.getWindowName(), gtf.windows.SUPPORT_DETAILS.url)
            .then((newlyOpenedWindow) => newlyOpenedWindow.moveTo(42, '42'))
            .then(() => done('moveTo() should have thrown an error because left isn\'t of type number!'))
            .catch((error) => {
                try {
                    expect(error.message).to.equal('expected a number, got a string');

                    done();
                } catch (err) {
                    done(err);
                }
            });
    });

    it('Should throw an error when trying to move the Platform.', (done) => {
        let platformWindow;
        const [top, left] = [95, 105];

        gtf.windows.getPlatformWindow()
            .then((platformWin) => {
                platformWindow = platformWin;

                return platformWindow.moveTo(top, left);
            })
            .then(() => done('moveTo() should have thrown an error because the Platform can\'t be moved!'))
            .catch((error) => {
                try {
                    expect(error.message).to.equal(`Internal Platform Communication Error. Attempted operation: "moveResize" with data: {"top":${top},"left":${left},"windowId":"${platformWindow.id}","relative":true}.  -> Inner message: The platform rejected operation moveResize for domain: windows with reason: "Move-resizing the main application is not allowed"`);

                    done();
                } catch (err) {
                    done(err);
                }
            });
    });
});

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import hasLocalStorage from 'has-localstorage';

if (hasLocalStorage()) {
  module.exports.storage = {
    type: 'localStorage',
    add: (key, value) => localStorage.setItem(key, value),
    get: (key) => localStorage.getItem(key),
    remove: (key) => localStorage.removeItem(key)
  };
} else if (chrome.storage) {
  module.exports.storage = {
    type: 'chromeOrWebExt',
    add: (key, value) => chrome.storage.sync.set({key, value}),
    get: (key) => chrome.storage.sync.set(key),
    remove: (key) => chrome.storage.sync.remove(key)
  };
}


text:
package com.twitter.server.handler

import com.twitter.finagle.Service
import com.twitter.finagle.http.MediaType
import com.twitter.finagle.http.Request
import com.twitter.finagle.http.Response
import com.twitter.finagle.http.Uri
import com.twitter.finagle.stats.HistogramDetail
import com.twitter.finagle.stats.WithHistogramDetails
import com.twitter.io.Buf
import com.twitter.server.util.HttpUtils.newResponse
import com.twitter.server.util.AdminJsonConverter
import com.twitter.server.util.MetricSource
import com.twitter.util.Future

/**
 * A handler which accepts metrics metadata queries via http query strings and returns
 * json encoded metrics with their types and an indicator of whether or not counters are latched.
 *
 * This is a temporary endpoint which will be replaced by a more fleshed out metadata endpoint.
 *
 * @note When passing an explicit histogram metric via ?m=, users must provide the raw histogram
 *       name, no percentile (eg, .p99) appended.
 *
 * Example Request:
 * http://$HOST:$PORT/admin/exp/metric_metadata?m=srv/http/requests&m=srv/http/pending&m=srv/mux/framer/write_stream_bytes
 *
 * Response:
 * {
 *   "latched" : true,
 *   "metrics" : [
 *     {
 *       "name" : "srv/http/requests",
 *       "kind" : "counter"
 *     },
 *     {
 *       "name" : "srv/http/pending",
 *       "kind" : "gauge"
 *     },
 *     {
 *       "name" : "srv/mux/framer/write_stream_bytes",
 *       "kind" : "histogram"
 *     }
 *   ]
 * }
 */
class MetricTypeQueryHandler(
  source: MetricSource = new MetricSource,
  details: Option[WithHistogramDetails] = None)
    extends Service[Request, Response] {

  protected def histograms: Map[String, HistogramDetail] =
    details match {
      case Some(histos) => histos.histogramDetails
      case None => Map.empty
    }

  protected def query(keys: Iterable[String]): Iterable[MetricSource.MetricTypeInfo] =
    for (k <- keys; e <- source.getType(k)) yield e

  protected def getHistos(): Iterable[MetricSource.MetricTypeInfo] = {
    histograms.map {
      case (name, _) => MetricSource.MetricTypeInfo(name, "histogram")
    }
  }

  protected def queryHistos(keys: Set[String]): Iterable[MetricSource.MetricTypeInfo] = {
    histograms.filterKeys(keys.contains).map {
      case (name, _) => MetricSource.MetricTypeInfo(name, "histogram")
    }
  }

  def apply(req: Request): Future[Response] = {
    val uri = Uri.fromRequest(req)

    val latched = source.hasLatchedCounters
    val keysParam = uri.params.getAll("m")

    val metrics =
      if (keysParam.isEmpty) source.typeMap ++ getHistos()
      else query(keysParam) ++ queryHistos(keysParam.toSet)

    newResponse(
      contentType = MediaType.JsonUtf8,
      content = Buf.Utf8(
        AdminJsonConverter.writeToString(
          Map(
            "latched" -> latched,
            "metrics" -> metrics
          )))
    )
  }
}


text:
import { dispatch } from '../dispatcher/ActorAppDispatcher';
import { ActionTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
import ComposeActionCreators from '../actions/ComposeActionCreators';
import ProfileStore from '../stores/ProfileStore';
import linq from 'Linq';
import $ from 'jquery';

var interval = null;

function getGroup(uid, callback) {
  console.log('getRroup uid', uid);
  var spapdata = `<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
                    <v:Header />
                    <v:Body>
                        <n0:queryGroup id="o0" c:root="1" xmlns:n0="http://eaglesoft">
                            <id i:type="d:string">${ uid }</id>
                        </n0:queryGroup>
                    </v:Body>
                </v:Envelope>`;
  var method = 'queryGroup';
  $.ajax({
      url: 'http://61.175.100.14:8012/ActorServices-Maven/services/ActorService',
      type: 'post',
      data: spapdata,
      beforeSend(request) {
          console.log('beforeSend', request);
          request.setRequestHeader('Content-Type', 'text/xml;charset=UTF-8');
          request.setRequestHeader('SOAPActrin', 'http://eaglesoft/' + method);
      },
      success: (res) => {
        if (res && res.nodeName) {
          callback(JSON.parse($(res).find('return').html()))
        }
      }
  });
}

var QuickSearchActionCreators = {
  show() {
    dispatch(ActionTypes.QUICK_SEARCH_SHOW);
    ComposeActionCreators.toggleAutoFocus(false);
  },

  hide() {
    dispatch(ActionTypes.QUICK_SEARCH_HIDE);
    ComposeActionCreators.toggleAutoFocus(true);
  },

  setQuickSearchList(list) {
    // 过滤系统管理员,过滤群组
    list = linq.from(list).where('$.peerInfo.title.indexOf("系统管理员") == -1 && $.peerInfo.title.indexOf("账号已删除") == -1 && $.peerInfo.peer.type !== "group"').toArray();
    dispatch(ActionTypes.QUICK_SEARCH_CHANGED_USER, { list });
    // 从另外的接口获取群组数据更新
    clearInterval(interval);
    var time = 0;
    interval = setInterval(group, 100);
    function group() {
      time++;
      if (ProfileStore.getProfile()) {
        QuickSearchActionCreators.setGroupList();
        clearInterval(interval);
      } else if (time === 100) {
        clearInterval(interval);
      }
    }
    group();
  },
  setGroupList() {
    getGroup(ProfileStore.getProfile().id, (groups) => {
      var arr = [];
      for (var i = 0; i < groups.length; i++ ) {
        var group = ActorClient.getGroup(groups[i].id);
        if(group) {
          arr.push({
            peerInfo: {
              avatar: group.avatar,
              placeholder: group.placeholder,
              title: group.name,
              peer: {
                id: group.id,
                type: 'group',
                key: 'g' + group.id
              }
            }
          });
        }
      }
      dispatch(ActionTypes.QUICK_SEARCH_CHANGED_GROUP, { list: arr });
    });
  }
};
export default QuickSearchActionCreators;


text:
talks
=====

A repo of my talks


text:
package io.vertx.ext.auth.jwt.authorization;

import io.vertx.codegen.annotations.VertxGen;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authorization.AuthorizationProvider;
import io.vertx.ext.auth.jwt.authorization.impl.MicroProfileAuthorizationImpl;

/**
 * Implementation of the Microprofile MP-JWT 1.1 RBAC based on the access token groups key.
 *
 * @author Paulo Lopes.
 */
@VertxGen
public interface MicroProfileAuthorization extends AuthorizationProvider {

  /**
   * Factory method to create a Authorization provider for tokens adhering to the MP-JWT 1.1 spec.
   * When the user is known to not be a JWT, (e.g.: a OAuth2 response token) then the root claim
   * is expected to be extracted from {@link User#attributes()} under the key {@code accessToken}.
   *
   * @return a AuthorizationProvider
   */
  static MicroProfileAuthorization create() {
    return new MicroProfileAuthorizationImpl();
  }
}


text:
layout: docs
title: Upgrading from 2.x to 3.x
permalink: /docs/upgrading/2-to-3/
---

Upgrading from an older version of Jekyll? A few things have changed in 3.0
that you'll want to know about.

Before we dive in, go ahead and fetch the latest version of Jekyll:

{% highlight shell %}
$ gem update jekyll
{% endhighlight %}

Please note: Jekyll 3 requires Ruby version >= 2.0.0.

Diving in

Want to get a new Jekyll site up and running quickly? Simply
   run jekyll new SITENAME to create a new folder with a bare bones
   Jekyll site.

### site.collections has changed

In 2.x, your iterations over `site.collections` yielded an array with the collection
label and the collection object as the first and second items, respectively. In 3.x,
this complication has been removed and iterations now yield simply the collection object.
A simple conversion must be made in your templates:

- `collection[0]` becomes `collection.label`
- `collection[1]` becomes `collection`

When iterating over `site.collections`, ensure the above conversions are made.

For `site.collections.myCollection` in Jekyll 2, you now do:

{% highlight liquid %}
{% raw %}
{% assign myCollection = site.collections | where: "label", "myCollection" | first %}
{% endraw %}
{% endhighlight %}

This is a bit cumbersome at first, but is easier than a big `for` loop.

### Dropped dependencies

We dropped a number of dependencies the Core Team felt were optional. As such, in 3.0, they must be explicitly installed and included if you use any of the features. They are:

- jekyll-paginate – Jekyll's pagination solution from days past
- jekyll-coffeescript – processing of CoffeeScript
- jekyll-gist – the `gist` Liquid tag
- pygments.rb – the Pygments highlighter
- redcarpet – the Markdown processor
- toml – an alternative to YAML for configuration files
- classifier-reborn – for `site.related_posts`

### Future posts

A seeming feature regression in 2.x, the `--future` flag was automatically _enabled_.
The future flag allows post authors to give the post a date in the future and to have
it excluded from the build until the system time is equal or after the post time.
In Jekyll 3, this has been corrected. **Now, `--future` is disabled by default.**
This means you will need to include `--future` if you want your future-dated posts to
generate when running `jekyll build` or `jekyll serve`.

### Layout metadata

Introducing: `layout`. In Jekyll 2 and below, any metadata in the layout was merged onto
the `page` variable in Liquid. This caused a lot of confusion in the way the data was
merged and some unexpected behaviour. In Jekyll 3, all layout data is accessible via `layout`
in Liquid. For example, if your layout has `class: my-layout` in its YAML front matter,
then the layout can access that via `{% raw %}{{ layout.class }}{% endraw %}`.

### Syntax highlighter changed

For the first time, the default syntax highlighter has changed for the
`highlight` tag and for backtick code blocks. Instead of [Pygments.rb](https://github.com/tmm1/pygments.rb),
it's now [Rouge](http://rouge.jneen.net/). If you were using the `highlight` tag with certain
options, such as `hl_lines`, they may not be available when using Rouge. To
go back to using Pygments, set `highlighter: pygments` in your
`_config.yml` file and run `gem install pygments.rb` or add
`gem 'pygments.rb'` to your project's `Gemfile`.

### Relative Permalink support removed

In Jekyll 3 and above, relative permalinks have been deprecated. If you
created your site using Jekyll 2 and below, you may receive the following
error when trying to **serve** or **build**:

{% highlight text %}
Since v3.0, permalinks for pages in subfolders must be relative to the site
source directory, not the parent directory. Check
http://jekyllrb.com/docs/upgrading/ for more info.
{% endhighlight %}

This can be fixed by removing the following line from your `_config.yml` file:

{% highlight yaml %}
relative_permalinks: true
{% endhighlight %}

### Permalinks no longer automatically add a trailing slash

In Jekyll 2, any URL constructed from the `permalink:` field had a trailing slash (`/`) added to it automatically.  Jekyll 3 no longer adds a trailing slash automatically to `permalink:` URLs. This can potentially result in old links to pages returning a 404 error. For example, suppose a page previously contained the YAML `permalink: /:year-:month-:day-:title` that resulted in the URL `example.com/2016-02-01-test/` (notice the trailing slash), Jekyll internally generates a folder named `2016-02-01-test`. In Jekyll 3, the same `permalink:` generate the file `2016-02-01-test.html` and the URL for the same page will be `example.com/2016-02-01-test`, and consequently any links to the old URL will result in a 404 error. In order to maintain the same URLs and avoid this problem, a trailing slash should be added to the `permalink:` field, for example `permalink: /:year-:month-:day-:title/`.

### All my posts are gone! Where'd they go!

Try adding `future: true` to your `_config.yml` file. Are they showing up now? If they are, then you were ensnared by an issue with the way Ruby parses times. Each of your posts is being read in a different timezone than you might expect and, when compared to the computer's current time, is "in the future." The fix for this is to add [a timezone offset](https://en.wikipedia.org/wiki/List_of_UTC_time_offsets) to each post (and make sure you remove `future: true` from your `_config.yml` file). If you're writing from California, for example, you would change this:

{% highlight yaml %}
---
date: 2016-02-06 19:32:10
---
{% endhighlight %}

to this (note the offset):

{% highlight yaml %}
---
date: 2016-02-06 19:32:10 -0800
---
{% endhighlight %}

### My categories have stopped working!

If you organized your categories as  `/_posts/code/2008-12-24-closures.md`, you will need to restructure your directories to put the categories _above_ the `_posts` directories, as follows: `/code/_posts/2008-12-24-closures.md`.

_Did we miss something? Please click "Improve this page" above and add a section. Thanks!_


text:
using System;
using System.Threading.Tasks;

namespace Nessos.Effects.DependencyInjection
{
    /// <summary>
    ///   Defines a suite of abstract effects that perform actions against the specified dependency type.
    /// </summary>
    /// <typeparam name="TDependency">The dependency the abstract effect depends on.</typeparam>
    public static class IO<TDependency>
    {
        /// <summary>
        ///   Defines an abstract effect that performs an operation against the specified dependency type.
        /// </summary>
        /// <typeparam name="TResult">The result of the effectful computation.</typeparam>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<TResult> Do<TResult>(Func<TDependency, TResult> func)
        {
            return new FuncDependencyEffect<TDependency, TResult>(dep => new ValueTask<TResult>(func(dep)));
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against the specified dependency type.
        /// </summary>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<Unit> Do(Action<TDependency> func)
        {
            return new FuncDependencyEffect<TDependency, Unit>(dep => { func(dep); return new ValueTask<Unit>(Unit.Value); });
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against the specified dependency type.
        /// </summary>
        /// <typeparam name="TResult">The result of the effectful computation.</typeparam>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<TResult> Do<TResult>(Func<TDependency, Task<TResult>> func)
        {
            return new FuncDependencyEffect<TDependency, TResult>(async dep => await func(dep).ConfigureAwait(false));
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against the specified dependency type.
        /// </summary>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<Unit> Do(Func<TDependency, Task> func)
        {
            return new FuncDependencyEffect<TDependency, Unit>(async dep => { await func(dep).ConfigureAwait(false); return Unit.Value; });
        }
    }

    /// <summary>
    ///   Defines a suite of abstract effects that perform actions against a dependency container.
    /// </summary>
    public static class IO
    {
        /// <summary>
        ///   Defines an abstract effect that performs an operation against a dependency container.
        /// </summary>
        /// <typeparam name="TResult">The result of the effectful computation.</typeparam>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<TResult> Do<TResult>(Func<IContainer, TResult> func)
        {
            return new ContainerFuncDependencyEffect<TResult>(c => new ValueTask<TResult>(func(c)));
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against a dependency container.
        /// </summary>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<Unit> Do(Action<IContainer> func)
        {
            return new ContainerFuncDependencyEffect<Unit>(c => { func(c); return new ValueTask<Unit>(Unit.Value); });
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against a dependency container.
        /// </summary>
        /// <typeparam name="TResult">The result of the effectful computation.</typeparam>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<TResult> Do<TResult>(Func<IContainer, Task<TResult>> func)
        {
            return new ContainerFuncDependencyEffect<TResult>(async c => await func(c).ConfigureAwait(false));
        }

        /// <summary>
        ///   Defines an abstract effect that performs an operation against a dependency container.
        /// </summary>
        /// <param name="func">The effectful operation performed against the dependency.</param>
        public static DependencyEffect<Unit> Do(Func<IContainer, Task> func)
        {
            return new ContainerFuncDependencyEffect<Unit>(async c => { await func(c).ConfigureAwait(false); return Unit.Value; });
        }
    }
}