コード例 #1
0
        public string Eval(string command, ScriptContext context = null)
        {
            if(context == null)
                context = new ScriptContext(Guid.NewGuid().ToString(), null, CancellationToken.None, _services, null);

            return _variableReplacer.Replace(command, context);
        }
コード例 #2
0
 public void Execute(ScriptContext context /*, System.Windows.Window window*/)
 {
     //Get correct structure set... In our case structure set is named "PSOAS"
     var ss = context.Patient.StructureSets
     .FirstOrDefault(s => s.Structures.Any(st => st.Id.Equals("PSOAS", StringComparison.InvariantCultureIgnoreCase)));
     //Find the structure named "L5_MID"
     var l5mid = ss.Structures.FirstOrDefault(s => s.Id.Equals("L5_MID", StringComparison.InvariantCultureIgnoreCase));
     double avg = double.NaN;
     if (l5mid != null)
     {
         //Create a map of slice area to image slice, so we know which slice to sample
         var l5midContours = GetSliceAreas(ss.Image, l5mid);
         //If all slices have a NaN value, then there is no contour
         if (!l5midContours.Any(p => !double.IsNaN(p.Value) && p.Value > 0))
         {
             MessageBox.Show("L5 Mid not found");
         }
         else
         {
             //Assumption is L5 contour is only on one slice, find the first slice with a valid area
             var z = l5midContours.First(p => !double.IsNaN(p.Value) && p.Value > 0).Key;
             avg = GetSliceHUAvg(ss.Image, z, l5mid);
             MessageBox.Show(string.Format("L5_MID Stats :\nArea: {0} cm^2\nHUavg = {1} HU", l5midContours[z].ToString("F2"), avg.ToString("F2")));
         }
     }
 }
コード例 #3
0
ファイル: Get.cs プロジェクト: rofr/playground
        public static object Eval(XmlNode node, ScriptContext ctx)
        {
            string varName = XmlHelper.ReadAttribute(node, "var");
            string className = XmlHelper.ReadAttribute(node, "class");
            string propertyName = XmlHelper.ReadAttribute(node, "property");

            object result = null;

            if (varName != null)
            {
                if (propertyName == null)//Get the variable itself
                {
                    result = ctx.State[varName];
                }
                else //assign a property of the variable
                {
                    result = ReflectionHelper.GetProperty(ctx.State[varName], propertyName);
                }
            }
            else if (className != null) //static property
            {
                throw new NotImplementedException("Static property getter not implemented");
            }

            return result;
        }
コード例 #4
0
ファイル: Set.cs プロジェクト: rofr/playground
        public static object Eval(XmlNode node, ScriptContext ctx)
        {
            string varName = XmlHelper.ReadAttribute(node, "var");
            string className = XmlHelper.ReadAttribute(node, "class");
            string propertyName = XmlHelper.ReadAttribute(node, "property");

            object value = ctx.Eval(node.ChildNodes);

            if (varName != null)
            {
                if (propertyName == null)//Assign a new value to the variable
                {
                    ctx.State[varName] = value;
                }
                else //assign a property of the variable
                {
                    ReflectionHelper.SetProperty(ctx.State[varName], propertyName, value);
                }
            }
            else if (className != null) //static property
            {
                throw new NotImplementedException("Static property setter not implemented");
            }

            return value;
        }
コード例 #5
0
ファイル: Arithmetic.cs プロジェクト: rofr/playground
 public static object Modulus(XmlNode node, ScriptContext ctx)
 {
     if(node.ChildNodes.Count != 2) throw new Exception();
     int a = (int) ctx.Eval(node.ChildNodes[0]);
     int b = (int)ctx.Eval(node.ChildNodes[1]);
     return a % b;
 }
コード例 #6
0
        public bool Evaluate(string block, ScriptContext context)
        {
            var replacer = context.Get<IVariableReplacer>();
            var scriptLog = context.Get<IScriptLog>();

            var replaced = replacer.Replace(block, context);
            // replace single equals with double equals
            replaced = Regex.Replace(replaced, "([^=:<>])=(?!=)", "$1==");

            if(context.DebugLevel > 0) {
                scriptLog.Log(context.Name, "if {0}".ToFormat(replaced), context.LineNumber);
            }

            try
            {
                var interpreter = new Interpreter();
                var result = (bool)interpreter.Eval(replaced);
                if(context.DebugLevel > 0) {
                    scriptLog.Log(context.Name, "if result {0}".ToFormat(result.ToString().ToLower()), context.LineNumber);
                }
                return result;
            }
            catch(Exception exc)
            {
                scriptLog.Log(context.Name, "if result {0}".ToFormat(exc), context.LineNumber);

                return false;
            }
        }
コード例 #7
0
ファイル: BooleanOperators.cs プロジェクト: rofr/playground
 public static object And(XmlNode node, ScriptContext ctx)
 {
     foreach(XmlNode childNode in node.ChildNodes)
     {
         if (!(bool)ctx.Eval(childNode)) return false;
     }
     return true;
 }
コード例 #8
0
        public override Task<CompletionEventArgs> Execute(ScriptContext context, Token token)
        {
            if(context.DebugLevel > 0) {
                context.Get<IScriptLog>().Log(context.Name, "waitforre " + token.Value, context.LineNumber);
            }

            return base.Execute(context, token);
        }
コード例 #9
0
        public string Replace(string data, ScriptContext context)
        {
            data = SetArguments(data, context);
            data = SetLocalVars(data, context);
            data = SetGlobalVars(data, context);

            return data;
        }
コード例 #10
0
ファイル: Graphics.cs プロジェクト: jing-lu/ReoScript
 public static ObjectValue CreatePointObject(ScriptContext ctx, float x, float y)
 {
     return ctx.Srm.CreateNewObject((obj) =>
     {
         obj["x"] = x;
         obj["y"] = y;
     });
 }
コード例 #11
0
ファイル: SessionScope.cs プロジェクト: mizzunet/spike-box
        /// <summary>
        /// Constructs a new instance of an <see cref="AppScope"/>.
        /// </summary>
        /// <param name="name">The unique name for the scope.</param>
        /// <param name="parent">The parent scope to attach to the scope.</param>
        /// <param name="context">The execution context that is used to execute scripts.</param>
        internal SessionScope(string name, AppScope parent, ScriptContext context)
            : base(name, parent, context, context.GetPrototype("Session"))
        {
            // Create a new channel linked to the session
            this.SessionChannel = new Channel(context);

            // When creating, set the current thread channel
            Channel.Current = this.SessionChannel;
        }
コード例 #12
0
 public Task Echo(string command, ScriptContext context = null)
 {
     return Publish(command, context, t => {
         t.Color = "#00FFFF";
         t.Mono = true;
         if(context != null && context.DebugLevel > 0)
             _scriptLog.Log(context.Name, "echo {0}".ToFormat(t.Text), context.LineNumber);
     });
 }
コード例 #13
0
ファイル: BooleanOperators.cs プロジェクト: rofr/playground
        public static object LessThanOrEqual(XmlNode node, ScriptContext ctx)
        {
            if(node.ChildNodes.Count != 2) throw new Exception("Expected 2 child nodes");
            object o1 = ctx.Eval(node.ChildNodes[0]);
            object o2 = ctx.Eval(node.ChildNodes[1]);

            var n1 = o1 is double ? (double) o1 : (int) o1;
            var n2 = o2 is double ? (double)o2 : (int) o2;
            return n1 <= n2;
        }
コード例 #14
0
ファイル: ITokenHandler.cs プロジェクト: joemcbride/outlander
        public virtual Task<CompletionEventArgs> Execute(ScriptContext context, Token token)
        {
            Token = token;
            Context = context;
            TaskSource = new TaskCompletionSource<CompletionEventArgs>();

            execute();

            return TaskSource.Task;
        }
コード例 #15
0
ファイル: while.cs プロジェクト: rofr/playground
        public static object Eval(XmlNode node, ScriptContext ctx)
        {
            XmlNode condition = node.FirstChild;

            object result = null;
            while ((bool)(ctx.Eval(condition)))
            {
                result = ctx.Eval(node.ChildNodes, 1, node.ChildNodes.Count-1);
            }
            return result;
        }
コード例 #16
0
        public Task EchoCommand(string command, ScriptContext context = null)
        {
            var formatted = command;
            if(context != null && !string.IsNullOrWhiteSpace(context.Name)) {
                formatted = "[{0}]: {1}".ToFormat(context.Name, command);
            }

            return Publish(formatted, context, t => {
                t.Color = "ADFF2F";
            });
        }
コード例 #17
0
        private string SetGlobalVars(string data, ScriptContext context)
        {
            var matches = Regex.Matches(data, Global_Vars_Regex);
            foreach(Match match in matches) {
                var value = context.GlobalVar.Get(match.Groups[1].Value);
                if(!string.IsNullOrWhiteSpace(value))
                    data = Regex.Replace(data, match.Groups[0].Value.Replace("$", "\\$"), value);
            }

            return data;
        }
コード例 #18
0
ファイル: Arithmetic.cs プロジェクト: rofr/playground
 public static object Add(XmlNode node, ScriptContext ctx)
 {
     double sum = 0;
     foreach(XmlNode childNode in node.ChildNodes)
     {
         object o =  ctx.Eval(childNode);
         double operand = o is int ? (int) o : (double) o;
         sum += operand;
     }
     return sum;
 }
コード例 #19
0
ファイル: ScriptBuilder.cs プロジェクト: wenbinke/susucms
        public ScriptBuilder(FrontContext frontContext, HtmlHelper htmlHelper)
        {
            _htmlHelper = htmlHelper;
            _frontContext = frontContext;

            var viewData = _frontContext.ViewData;
            if (viewData.ScriptContext == null)
            {
                viewData.ScriptContext = new ScriptContext();
            }
            _scriptContext = viewData.ScriptContext;
        }
コード例 #20
0
        private string SetLocalVars(string data, ScriptContext context)
        {
            if(context.LocalVars != null) {
                var matches = Regex.Matches(data, Local_Vars_Regex);
                foreach(Match match in matches) {
                    var value = context.LocalVars.Get(match.Groups[1].Value);
                    if(!string.IsNullOrWhiteSpace(value))
                        data = Regex.Replace(data, match.Groups[0].Value, value);
                }
            }

            return data;
        }
コード例 #21
0
    public void Load(ref ScriptContext Context)
    {
        List<object> Args = (List<object>)Context.Arguments;
            object[] Params = Args.ToArray();
            string channel = Context.channel.Name;

            for (int index = 0; index < Params.Length; index++)
            {
                Console.WriteLine("Argument {0}: {1}", index + 1, Params[index] as string);
            }

            Context.server.SendMessage(channel, "... _ _ ...");
    }
コード例 #22
0
        public void SetUp()
        {
            theGameState = new StubGameState();
            theGameServer = new StubGameServer(theGameState);
            theScriptLog = new InMemoryScriptLog();
            theLocalVars = new SimpleDictionary<string, string>();

            theServices = new InMemoryServiceLocator();
            theServices.Add<IGameServer>(theGameServer);
            theServices.Add<IScriptLog>(theScriptLog);

            theScriptContext = new ScriptContext("1", "unvar", CancellationToken.None, theServices, theLocalVars);
            theHandler = new UnVarTokenHandler();
        }
コード例 #23
0
        public MainWindow()
        {
            InitializeComponent();
            Kernel.Info.Log += new Action<string>(msg =>
            {
                textBox3.Dispatcher.Invoke(new Action(() => { textBox3.Text += msg; }));
            });
            Kernel.Error.Log += new Action<string>(msg =>
                {
                    textBox3.Dispatcher.Invoke(new Action(() => { textBox3.Text += msg; }));
                });

            context = Kernel.CreateContext();
        }
コード例 #24
0
        public virtual Task<CompletionEventArgs> Execute(ScriptContext context, Token token)
        {
            var matcher = BuildMatcher(context, token);

            context.CancelToken.Register(() => {
                if(_matchers.Contains(matcher))
                {
                    _matchers.Remove(matcher);
                }
            });

            _matchers.Add(matcher);

            return matcher.TaskSource.Task;
        }
コード例 #25
0
    public void Load(ref ScriptContext Context)
    {
        try
            {
                List<object> Args = (List<object>)Context.Arguments;
                object[] Params = Args.ToArray();
                string channel = Context.channel.Name;

                Context.server.SendMessage(channel, "The Version history of Blizzeta to Date:");
                Context.server.SendMessage(channel, "Blizzeta was first known as VBBot(Visual Basic), then moved to BlizzyBot, then BlizzyBotPT, BlizzyBotPT2, BlizzyBotNT, BlizzyBotNT6 <endVB> Blizzeta 1.0(C#), Blizzeta 1.1, Blizzeta 2(Thresher), Blizzeta 3, Blizzeta 3.1, Blizzeta 3.2, Blizzeta 3.3, Blizzeta 3.4, Blizzeta 4.0, Blizzeta 5.0, Blizzeta 6.0, Blizzeta 6.1, Blizzeta 6.2, Blizzeta 6.3, Blizzeta 6.4, Blizzeta 6.5, Blizzeta 6.6, Blizzeta 7 Codenamed Zero");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
    }
コード例 #26
0
        public void SetUp()
        {
            theGameState = new StubGameState();
            theGameServer = new StubGameServer(theGameState);
            theScriptLog = new InMemoryScriptLog();
            theCommandProcessor = new StubCommandProcessor();

            theServices = new InMemoryServiceLocator();
            theServices.Add<IGameServer>(theGameServer);
            theServices.Add<IScriptLog>(theScriptLog);
            theServices.Add<ICommandProcessor>(theCommandProcessor);

            theScriptContext = new ScriptContext("1", "gototoken", CancellationToken.None, theServices, null);
            theScriptContext.DebugLevel = 5;
            theHandler = new GotoTokenHandler();
        }
コード例 #27
0
        object IScriptingProvider.Execute(string script, ScriptExecutionOptions options)
        {
            ScriptContext context = new ScriptContext(options);

            Engine eng = new Engine(_ => _.Strict());
            eng.SetValue("context", context);

            object v = eng.Execute(script);

            if (context.ret != null)
            {
                return context.ret;
            }

            return v;
        }
コード例 #28
0
ファイル: Module.cs プロジェクト: mizzunet/spike-box
        /// <summary>
        /// Registers all the modules into the script context.
        /// </summary>
        /// <param name="context"></param>
        public static void IncludeIn(ScriptContext context)
        {
            try
            {
                // Set the context to be the current one
                ScriptContext.Current = context;

                // Inject the modules in parallel, as they are no dependancies
                // at the moment between components.
                foreach (var module in Modules.Resolve())
                    context.Import(module.Name, module.Register);
            }
            finally
            {
                // Reset back the context
                ScriptContext.Current = null;
            }
        }
コード例 #29
0
        public void SetUp()
        {
            theGameState = new StubGameState();
            theGameServer = new StubGameServer(theGameState);
            theGameStream = new GameStream(theGameState);

            theGameState.Set(ComponentKeys.Roundtime, "0");

            theLog = new InMemoryScriptLog();

            theServices = new InMemoryServiceLocator();
            theServices.Add<IGameServer>(theGameServer);
            theServices.Add<IScriptLog>(theLog);

            theScriptContext = new ScriptContext("1", "waitfor", CancellationToken.None, theServices, null);
            theScriptContext.DebugLevel = 5;

            theHandler = new WaitForReTokenHandler(theGameState, theGameStream);
        }
コード例 #30
0
        public void SetUp()
        {
            theGameState = new StubGameState();
            theGameServer = new StubGameServer(theGameState);
            theLogger = new InMemoryScriptLog();
            theGameStream = new GameStream(theGameState);

            theServices = new InMemoryServiceLocator();
            theServices.Add<IGameServer>(theGameServer);
            theServices.Add<IGameState>(theGameState);
            theServices.Add<IScriptLog>(theLogger);
            theServices.Add<IVariableReplacer>(new VariableReplacer());
            theServices.Add<ICommandProcessor>(new CommandProcessor(theServices, theServices.Get<IVariableReplacer>(), theLogger));
            theServices.Add<IGameStream>(theGameStream);

            theScriptContext = new ScriptContext("1", "sendcommand", CancellationToken.None,  theServices, null);
            theScriptContext.DebugLevel = 5;

            theHandler = new SendCommandTokenHandler();
        }
コード例 #31
0
 private void txtDefaultValue_TextChanged(object sender, EventArgs e)
 {
     ScriptContext.CodeTBXInput_TextChanged(sender, e);
 }
コード例 #32
0
 private void txtDefaultValue_KeyDown(object sender, KeyEventArgs e)
 {
     ScriptContext.CodeInput_KeyDown(sender, e);
 }
コード例 #33
0
        public static Tuple <List <List <double[, ]> >, string, List <double[]> > ParotidChop(ref ExternalPlanSetup plan, HNPlan hnPlan, List <List <Structure> > matchingStructures, StructureSet ss, ScriptContext context)
        {
            /*
             * 1. Find contralateral parotid (one with least overlap, largest sum of distance from PTVs), get contours
             * 2.) split this up into its separate contours
             * 3. make new structure for each
             * 4. make constraint for each based on importance
             */

            //1.
            Structure contraPar = Segmentation.FindContraPar(plan, ss, hnPlan, matchingStructures, context);
            //Now get contours for it
            // GetContours function will return the list of contours, as well as a list of all z-planes which contours were taken from, in a tuple
            var tuple = Segmentation.GetContours(contraPar, context);
            List <double[, ]> contours = tuple.Item1;
            List <double[]>   planes   = tuple.Item2;


            //2. Now the parotid segmentation!
            int numCutsZ = 2;
            int numCutsX = 2;
            int numCutsY = 1;
            List <List <double[, ]> > choppedContours = Segmentation.Chop(contours, numCutsX, numCutsY, numCutsZ, contraPar.Name);

            return(Tuple.Create(choppedContours, contraPar.Name, planes));
        }
コード例 #34
0
 public override List <string> GetValue(ScriptContext context)
 {
     return(context.Commands);
 }
コード例 #35
0
        public void Filters_with_HandleUnknownValueAttribute_handles_unkownn_values()
        {
            var context = new ScriptContext().Init();

            Assert.That(new PageResult(context.OneTimePage("{{ undefined | otherwise('undefined serverArg') }}")).Result, Is.EqualTo("undefined serverArg"));
        }
コード例 #36
0
ファイル: Filter.cs プロジェクト: jiahao42/weverca
 public static object filter_input(ScriptContext /*!*/ context, FilterInput type, string variable_name)
 {
     return(filter_input(context, type, variable_name, (int)FilterSanitize.FILTER_DEFAULT, null));
 }
コード例 #37
0
 private void OnContextDestroy(ScriptContext context)
 {
     Release();
 }
コード例 #38
0
 public virtual object closeCursor(ScriptContext context)
 {
     this.CloseReader();
     return(null);
 }
コード例 #39
0
ファイル: PDOStatement.PHP.cs プロジェクト: jiahao42/weverca
 public virtual object setFetchMode(ScriptContext context, object fetch_to_mode, [Optional] object fetch_to_dest /*=null*/, [Optional] object fetch_to_args /*=null*/)
 {
     return(false);
 }
コード例 #40
0
 public ResourceProperties(ScriptContext context, Player player)
     : base(context, player)
 {
     pr = player.PlayerActor.Trait <PlayerResources>();
 }
コード例 #41
0
 public PDOStatement(ScriptContext context, PDO pdo)
     : base(context, true)
 {
     this.m_pdo = pdo;
     this.setFetchMode(context, (int)PDOFetchType.PDO_FETCH_BOTH, null, null);
 }
コード例 #42
0
        internal void Prepare(ScriptContext context, string query, Dictionary <int, object> options)
        {
            this.m_prepMode = PreparedMode.None;
            this.m_prepName = new Dictionary <string, string>();
            this.m_prepNum  = new List <string>();
            int           pos         = 0;
            StringBuilder sbRewritten = new StringBuilder();

            while (pos < query.Length)
            {
                char c = query[pos];
                switch (c)
                {
                case '?':
                {
                    if (this.m_prepMode == PreparedMode.None)
                    {
                        this.m_prepMode = PreparedMode.Numbers;
                    }
                    else
                    {
                        if (this.m_prepMode != PreparedMode.Numbers)
                        {
                            PDOException.Throw(context, "Mixed parameter mode : use only '?' or ':name' pattern", null, null, null);
                            return;
                        }
                    }
                    int    paramNum = this.m_prepNum.Count;
                    string pName    = this.m_pdo.Driver.GetParameterName("p" + paramNum);
                    this.m_prepNum.Insert(paramNum, pName);
                    sbRewritten.Append(pName);
                }
                break;

                case ':':
                {
                    if (this.m_prepMode == PreparedMode.None)
                    {
                        this.m_prepMode = PreparedMode.Named;
                    }
                    else
                    {
                        if (this.m_prepMode != PreparedMode.Named)
                        {
                            PDOException.Throw(context, "Mixed parameter mode : use only '?' or ':name' pattern", null, null, null);
                            return;
                        }
                    }
                    Match  m         = regName.Match(query, pos);
                    string paramName = m.Value;
                    string pName     = this.m_pdo.Driver.GetParameterName(paramName);
                    this.m_prepName[paramName] = pName;
                    sbRewritten.Append(pName);
                    pos += paramName.Length;
                }
                break;

                case '"':
                    sbRewritten.Append(c);
                    this.SkipToNext(query, sbRewritten, ref pos, '"');
                    break;

                case '\'':
                    sbRewritten.Append(c);
                    this.SkipToNext(query, sbRewritten, ref pos, '\'');
                    break;

                default:
                    sbRewritten.Append(c);
                    break;
                }
                pos++;
            }

            //this.CurrentCommand.CommandText = sbRewritten.ToString();
            this.Init(sbRewritten.ToString(), options);
            string[] arrParams = null;
            switch (this.m_prepMode)
            {
            case PreparedMode.Named:
                arrParams = this.m_prepName.Values.ToArray();
                break;

            case PreparedMode.Numbers:
                arrParams = this.m_prepNum.ToArray();
                break;

            case PreparedMode.None:
            default:
                break;
            }
            this.CurrentCommand.Parameters.Clear();
            if (arrParams != null)
            {
                foreach (string paramName in arrParams)
                {
                    var param = this.CurrentCommand.CreateParameter();
                    param.ParameterName = paramName;
                    this.CurrentCommand.Parameters.Add(param);
                }
            }
            this.CurrentCommand.Prepare();
        }
コード例 #43
0
ファイル: Filter.cs プロジェクト: jiahao42/weverca
 public static object filter_input(ScriptContext /*!*/ context, FilterInput type, string variable_name, int filter)
 {
     return(filter_input(context, type, variable_name, filter, null));
 }
コード例 #44
0
 public GuardProperties(ScriptContext context, Actor self)
     : base(context, self)
 {
     guard = self.Trait <Guard>();
 }
コード例 #45
0
ファイル: GameMusic.cs プロジェクト: IndiegameGarden/Quest
 public void OnUpdate(ScriptContext ctx)
 {
     rp.Time = ctx.ScriptComp.SimTime; // gameTime.ElapsedGameTime.TotalSeconds;
     MusicEngine.GetInstance().Render(soundScript, rp);
 }
コード例 #46
0
        private static int Wain(string[] args)
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode."
            };
            var file        = app.Argument("script", "Path to CSX script");
            var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue);

            var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue);

            var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue);

            var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);

            var verbosity = app.Option("--verbosity", " Set the verbosity level of the command. Allowed values are t[trace], d[ebug], i[nfo], w[arning], e[rror], and c[ritical].", CommandOptionType.SingleValue);

            var nocache = app.Option("--nocache", "disable DLL caching", CommandOptionType.NoValue);

            var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray();
            var argsAfterDoubleHypen   = args.SkipWhile(a => a != "--").Skip(1).ToArray();

            app.HelpOption("-? | -h | --help");

            app.VersionOption("-v | --version", GetVersion);

            var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue);

            app.Command("eval", c =>
            {
                c.Description = "Execute CSX code.";
                var code      = c.Argument("code", "Code to execute.");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(code.Value))
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                        exitCode       = await RunCode(code.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), cwd.Value(), packageSources.Values?.ToArray());
                    }
                    return(exitCode);
                });
            });

            app.Command("init", c =>
            {
                c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script.";
                var fileName  = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'");
                var cwd       = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    scaffolder.InitializerFolder(fileName.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("new", c =>
            {
                c.Description        = "Creates a new script file";
                var fileNameArgument = c.Argument("filename", "The script file name");
                var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue);
                c.OnExecute(() =>
                {
                    var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var scaffolder = new Scaffolder(logFactory);
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }
                    scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory());
                    return(0);
                });
            });

            app.Command("publish", c =>
            {
                c.Description              = "Creates a self contained executable or DLL from a script";
                var fileNameArgument       = c.Argument("filename", "The script file name");
                var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed.  Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue);
                var dllName          = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time).  Defaults to the name of the script.", CommandOptionType.SingleValue);
                var dllOption        = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue);
                var commandConfig    = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue);
                var publishDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                var runtime          = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue);

                c.OnExecute(() =>
                {
                    if (fileNameArgument.Value == null)
                    {
                        c.ShowHelp();
                        return(0);
                    }

                    var optimizationLevel = OptimizationLevel.Debug;
                    if (commandConfig.HasValue() && commandConfig.Value().ToLower() == "release")
                    {
                        optimizationLevel = OptimizationLevel.Release;
                    }

                    var runtimeIdentifier = runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier;
                    var absoluteFilePath  = Path.IsPathRooted(fileNameArgument.Value) ? fileNameArgument.Value : Path.Combine(Directory.GetCurrentDirectory(), fileNameArgument.Value);

                    // if a publish directory has been specified, then it is used directly, otherwise:
                    // -- for EXE {current dir}/publish/{runtime ID}
                    // -- for DLL {current dir}/publish
                    var publishDirectory = publishDirectoryOption.Value() ??
                                           (dllOption.HasValue() ? Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish") : Path.Combine(Path.GetDirectoryName(absoluteFilePath), "publish", runtimeIdentifier));

                    var absolutePublishDirectory = Path.IsPathRooted(publishDirectory) ? publishDirectory : Path.Combine(Directory.GetCurrentDirectory(), publishDirectory);

                    var logFactory    = CreateLogFactory(verbosity.Value(), debugMode.HasValue());
                    var compiler      = GetScriptCompiler(publishDebugMode.HasValue(), logFactory);
                    var scriptEmmiter = new ScriptEmitter(ScriptConsole.Default, compiler);
                    var publisher     = new ScriptPublisher(logFactory, scriptEmmiter);
                    var code          = SourceText.From(File.ReadAllText(absoluteFilePath));
                    var context       = new ScriptContext(code, absolutePublishDirectory, Enumerable.Empty <string>(), absoluteFilePath, optimizationLevel);

                    if (dllOption.HasValue())
                    {
                        publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, dllName.Value());
                    }
                    else
                    {
                        publisher.CreateExecutable <int, CommandLineScriptGlobals>(context, logFactory, runtimeIdentifier);
                    }

                    return(0);
                });
            });

            app.Command("exec", c =>
            {
                c.Description        = "Run a script from a DLL.";
                var dllPath          = c.Argument("dll", "Path to DLL based script");
                var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue);
                c.OnExecute(async() =>
                {
                    int exitCode = 0;
                    if (!string.IsNullOrWhiteSpace(dllPath.Value))
                    {
                        if (!File.Exists(dllPath.Value))
                        {
                            throw new Exception($"Couldn't find file '{dllPath.Value}'");
                        }

                        var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                        var absoluteFilePath = Path.IsPathRooted(dllPath.Value) ? dllPath.Value : Path.Combine(Directory.GetCurrentDirectory(), dllPath.Value);

                        var compiler = GetScriptCompiler(commandDebugMode.HasValue(), logFactory);
                        var runner   = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result   = await runner.Execute <int>(absoluteFilePath, app.RemainingArguments.Concat(argsAfterDoubleHypen));
                        return(result);
                    }
                    return(exitCode);
                });
            });

            app.OnExecute(async() =>
            {
                int exitCode = 0;

                if (infoOption.HasValue())
                {
                    Console.Write(GetEnvironmentInfo());
                    return(0);
                }

                var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue());

                if (!string.IsNullOrWhiteSpace(file.Value))
                {
                    if (Debugger.IsAttached || nocache.HasValue())
                    {
                        var optimizationLevel = OptimizationLevel.Debug;
                        if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                        {
                            optimizationLevel = OptimizationLevel.Release;
                        }
                        exitCode = await RunScript(file.Value, debugMode.HasValue(), logFactory, optimizationLevel, app.RemainingArguments.Concat(argsAfterDoubleHypen), interactive.HasValue(), packageSources.Values?.ToArray());
                    }
                    else
                    {
                        string cacheFolder = Path.Combine(Path.GetTempPath(), "dotnet-scripts");
                        // create unique folder name based on the path
                        string uniqueFolderName = "";
                        using (var sha = SHA256.Create())
                        {
                            uniqueFolderName = Convert.ToBase64String(sha.ComputeHash(Encoding.Unicode.GetBytes(file.Value))).Replace("=", String.Empty).Replace("/", string.Empty);
                        }

                        string publishDirectory = Path.Combine(cacheFolder, uniqueFolderName);
                        if (!Directory.Exists(publishDirectory))
                        {
                            Directory.CreateDirectory(publishDirectory);
                        }

                        string absoluteSourcePath;
                        SourceText code;
                        if (!File.Exists(file.Value))
                        {
                            if (IsHttpUri(file.Value))
                            {
                                var downloader     = new ScriptDownloader();
                                var rawCode        = await downloader.Download(file.Value);
                                absoluteSourcePath = Path.Combine(publishDirectory, "source.csx");
                                File.WriteAllText(absoluteSourcePath, rawCode);
                                code = SourceText.From(rawCode);
                            }
                            else
                            {
                                throw new Exception($"Couldn't find file '{file}'");
                            }
                        }
                        else
                        {
                            absoluteSourcePath = Path.IsPathRooted(file.Value) ? Path.GetFullPath(file.Value) : Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), file.Value));
                            code = SourceText.From(File.ReadAllText(absoluteSourcePath));
                        }

                        // given the path to a script we create a %temp%\dotnet-scripts\{uniqueFolderName} path
                        string pathToDll = Path.Combine(publishDirectory, Path.GetFileNameWithoutExtension(absoluteSourcePath) + ".dll");

                        // source hash is the checkSum of the code
                        string sourceHash = Convert.ToBase64String(code.GetChecksum().ToArray());

                        // get hash code from previous run
                        string hashCache = Path.Combine(publishDirectory, ".hash");
                        var compiler     = GetScriptCompiler(true, logFactory);

                        // if we don't have hash
                        if (!File.Exists(hashCache) ||
                            // or we haven't created a dll
                            !Directory.Exists(publishDirectory) ||
                            // the hashcode has changed (meaning new content)
                            File.ReadAllText(hashCache) != sourceHash)
                        {
                            // then we autopublish into the %temp%\dotnet-scripts\{uniqueFolderName} path
                            var optimizationLevel = OptimizationLevel.Debug;
                            if (configuration.HasValue() && configuration.Value().ToLower() == "release")
                            {
                                optimizationLevel = OptimizationLevel.Release;
                            }

                            var runtimeIdentifier = ScriptEnvironment.Default.RuntimeIdentifier;
                            var scriptEmmiter     = new ScriptEmitter(ScriptConsole.Default, compiler);
                            var publisher         = new ScriptPublisher(logFactory, scriptEmmiter);
                            var context           = new ScriptContext(code, publishDirectory, Enumerable.Empty <string>(), absoluteSourcePath, optimizationLevel);

                            // create the assembly in our cache folder
                            publisher.CreateAssembly <int, CommandLineScriptGlobals>(context, logFactory, Path.GetFileNameWithoutExtension(pathToDll));

                            // save sourceHash for next time, so we can know it's ok to use the generated dll next time
                            File.WriteAllText(hashCache, sourceHash);
                        }


                        // run the cached %temp%\dotnet-scripts\{uniqueFolderName}/package.dll
                        var runner = new ScriptRunner(compiler, logFactory, ScriptConsole.Default);
                        var result = await runner.Execute <int>(pathToDll, app.RemainingArguments.Concat(argsAfterDoubleHypen));
                        return(result);
                    }
                }
                else
                {
                    await RunInteractive(debugMode.HasValue(), logFactory, packageSources.Values?.ToArray());
                }
                return(exitCode);
            });


            return(app.Execute(argsBeforeDoubleHyphen));
        }
コード例 #47
0
 private object fetch(ScriptContext context, int fetch_style)
 {
     return(this.fetch(context, fetch_style, FETCH_ORI_NEXT, 0));
 }
コード例 #48
0
        public static Tuple <List <List <Structure> >, List <List <Structure> >, List <List <string> >, bool> StartOptimizer(ScriptContext context, HNPlan hnPlan, List <List <Structure> > matchingStructures, int numIterations, List <Tuple <bool, double[], string> > features, Tuple <string, string, bool> beamParams) //Returns list of matching structures
        {
            // Check for patient plan loaded
            ExternalPlanSetup plan = context.ExternalPlanSetup;


            Patient      patient = context.Patient;
            StructureSet ss      = context.StructureSet;
            Course       course  = context.Course;
            Image        image3d = context.Image;


            //Create two VMAT beams
            BeamMaker(ref plan, ss, plan.TotalDose.Dose, beamParams);
            //set prescriptions dose
            int numFractions    = hnPlan.Fractions;
            int dosePerFraction = (int)hnPlan.PrescriptionDose / numFractions;

            plan.SetPrescription(numFractions, new DoseValue(dosePerFraction, "cGy"), 1);


            //matchingStructures is the same length as hnPlan.ROIs.count
            //Now set optimization constraints
            List <List <Structure> >  optimizedStructures = OptObjectivesEditing.SetConstraints(ref plan, hnPlan, matchingStructures, true); //true to check for opti structures, returns new matching list of structures
            List <List <double[, ]> > choppedContours;
            List <double[]>           planes;
            string contraParName;

            if (features[0].Item1 == true) //parotid segmentation feature
            {
                Tuple <List <List <double[, ]> >, string, List <double[]> > choppedAndName = ParotidChop(ref plan, hnPlan, matchingStructures, ss, context);
                choppedContours = choppedAndName.Item1;
                contraParName   = choppedAndName.Item2;
                planes          = choppedAndName.Item3;
            }
            else
            {
                choppedContours = new List <List <double[, ]> >();
                contraParName   = "";
                planes          = new List <double[]>();
            }
            Tuple <bool, List <List <string> > > optimData = Optimize(choppedContours, planes, ref plan, ref ss, hnPlan, context, optimizedStructures, matchingStructures, contraParName, numIterations, features, beamParams);
            bool isPassed = optimData.Item1;
            List <List <string> > updatesLog = optimData.Item2;

            return(Tuple.Create(optimizedStructures, matchingStructures, updatesLog, isPassed));
        }
コード例 #49
0
 public MobileProperties(ScriptContext context, Actor self)
     : base(context, self)
 {
     mobile = self.Trait <Mobile>();
 }
コード例 #50
0
ファイル: GameMusic.cs プロジェクト: IndiegameGarden/Quest
 public void OnDraw(ScriptContext ctx)
 {
 }
コード例 #51
0
        public async Task Does_evaluate_variable_binding_expressions()
        {
            var context = new ScriptContext
            {
                Args =
                {
                    ["key"] = "the-key",
                }
            }.Init();

            context.VirtualFiles.WriteFile("page.html", @"Prop = {{ Prop }}");

            var model = CreateModelBinding();

            var pageResultArg = new NestedModelBinding
            {
                Int    = 2,
                Prop   = "Nested Prop",
                Object = new ModelBinding
                {
                    Int  = 21,
                    Prop = "Nested Nested Prop",
                },
                AltNested = new AltNested
                {
                    Field = "Object AltNested Field"
                }
            };

            var result = await new PageResult(context.GetPage("page"))
            {
                Model = model,
                Args  = { ["pageResultArg"] = pageResultArg }
            }.Init();

            var scope = result.CreateScope();

            object value;

            value = scope.EvaluateExpression("key");
            Assert.That(value, Is.EqualTo("the-key"));
            value = scope.EvaluateExpression("Prop");
            Assert.That(value, Is.EqualTo(model.Prop));

            value = scope.EvaluateExpression("model.Prop");
            Assert.That(value, Is.EqualTo(model.Prop));
            value = scope.EvaluateExpression("model.Object.Prop");
            Assert.That(value, Is.EqualTo(model.Object.Prop));
            value = scope.EvaluateExpression("model.Object.Object.Prop");
            Assert.That(value, Is.EqualTo(model.Object.Object.Prop));
            value = scope.EvaluateExpression("model.Object.AltNested.Field");
            Assert.That(value, Is.EqualTo(model.Object.AltNested.Field));
            value = scope.EvaluateExpression("model[0].Prop");
            Assert.That(value, Is.EqualTo(model[0].Prop));
            value = scope.EvaluateExpression("model[0].Object.Prop");
            Assert.That(value, Is.EqualTo(model[0].Object.Prop));
            value = scope.EvaluateExpression("model.List[0]");
            Assert.That(value, Is.EqualTo(model.List[0]));
            value = scope.EvaluateExpression("model.List[0].Prop");
            Assert.That(value, Is.EqualTo(model.List[0].Prop));
            value = scope.EvaluateExpression("model.List[0].Object.Prop");
            Assert.That(value, Is.EqualTo(model.List[0].Object.Prop));
            value = scope.EvaluateExpression("model.Dictionary[\"map-key\"].Prop");
            Assert.That(value, Is.EqualTo(model.Dictionary["map-key"].Prop));
            value = scope.EvaluateExpression("model.Dictionary['map-key'].Object.Prop");
            Assert.That(value, Is.EqualTo(model.Dictionary["map-key"].Object.Prop));
            value = scope.EvaluateExpression("model.Dictionary['map-key'].Object.AltNested.Field");
            Assert.That(value, Is.EqualTo(model.Dictionary["map-key"].Object.AltNested.Field));
            value = scope.EvaluateExpression("Object.AltNested.Field");
            Assert.That(value, Is.EqualTo(model.Object.AltNested.Field));

            value = scope.EvaluateExpression("pageResultArg.Object.Prop");
            Assert.That(value, Is.EqualTo(pageResultArg.Object.Prop));
            value = scope.EvaluateExpression("pageResultArg.AltNested.Field");
            Assert.That(value, Is.EqualTo(pageResultArg.AltNested.Field));
        }
コード例 #52
0
 public virtual object execute(ScriptContext context, [Optional] object input_parameters)
 {
     return(this.ExecuteInternal((input_parameters != Arg.Default) ? input_parameters : null));
 }
コード例 #53
0
 public ActorGlobal(ScriptContext context) : base(context)
 {
 }
コード例 #54
0
 /// <inheritdoc />
 protected override object Compare(object lhs, object rhs, ScriptContext context)
 {
     return((dynamic)lhs > (dynamic)rhs);
 }
コード例 #55
0
 public static bool Defined(ScriptContext context, string name)
 {
     return(context.IsConstantDefined(name));
 }
コード例 #56
0
 public UtilsGlobal(ScriptContext context) : base(context)
 {
 }
コード例 #57
0
        public static Tuple <bool, List <List <string> > > Optimize(List <List <double[, ]> > choppedContours, List <double[]>
                                                                    planes, ref ExternalPlanSetup plan, ref StructureSet ss, HNPlan hnPlan, ScriptContext context, List <List <Structure> > optimizedStructures, List <List <Structure> > matchingStructures, string contraName, int numIterations, List <Tuple <bool, double[], string> > features, Tuple <string, string, bool> beamParams)
        //return a list of strings which is the log of constraint updates during optimization.
        {
            //Only make parotid structures if that feature has been selected

            if (features[0].Item1 == true)
            {
                double priorityRatio = features[0].Item2[0];
                Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, priorityRatio);
            }
            else
            {
                //remove previously segmented structures if there
                foreach (Structure structure in ss.Structures.ToList())
                {
                    if (structure.Name.ToLower().Contains("cpg_subseg"))
                    {
                        ss.RemoveStructure(structure);
                    }
                }
            }

            //Now run the first VMAT optimization.
            plan.SetCalculationModel(CalculationType.PhotonVMATOptimization, "PO_13623");
            plan.SetCalculationModel(CalculationType.DVHEstimation, "DVH Estimation Algorithm [15.6.06]");
            plan.SetCalculationModel(CalculationType.PhotonVolumeDose, "AAA_13623");
            plan.OptimizationSetup.AddNormalTissueObjective(100, 3, 95, 50, 0.2);
            bool jawTracking = beamParams.Item3;

            //use jaw tracking
            if (jawTracking)
            {
                try
                {
                    plan.OptimizationSetup.UseJawTracking = true;
                } catch
                {
                    System.Windows.MessageBox.Show("Could not use jaw tracking. Proceeding without.");
                }
            }

            // plan.OptimizeVMAT();
            plan.CalculateDose();
            string treatmentCenter = beamParams.Item1;
            string treatmentArea   = beamParams.Item2;
            string mlcId           = "";
            int    areaNum         = Int32.Parse(Regex.Match(treatmentArea, @"\d+").Value);

            if (treatmentCenter == "BC Cancer - Surrey")
            {
                switch (areaNum)
                {
                case 2:
                    mlcId = "";
                    break;

                case 3:
                    mlcId = "";
                    break;

                case 4:
                    mlcId = "";
                    break;

                case 5:
                    mlcId = "";
                    break;

                case 6:
                    mlcId = "";
                    break;
                }
            }
            else if (treatmentCenter == "BC Cancer - Vancouver")
            {
                switch (areaNum)
                {
                case 1:
                    mlcId = "1";
                    break;

                case 2:
                    mlcId = "HHM0767";
                    break;

                case 3:
                    mlcId = "";
                    break;

                case 4:
                    mlcId = "";
                    break;

                case 5:
                    mlcId = "";
                    break;

                case 6:
                    mlcId = "HML0990";
                    break;

                case 7:
                    mlcId = "MLC0987";
                    break;
                }
            }
            string mlcID     = "HML0990";
            int    numCycles = 1;
            OptimizationOptionsVMAT oov;

            ;
            bool isPassed = false;
            List <List <string> > updateLog = new List <List <string> >();

            for (int iter = 0; iter < numIterations; iter++)
            {
                //mlcID = plan.Beams.FirstOrDefault<Beam>().MLC.Id;
                oov = new OptimizationOptionsVMAT(numCycles, mlcID);
                plan.OptimizeVMAT(oov);
                plan.CalculateDose();

                //Now need to perform a plan check and iteratively adjust constraints based on whether they passed or failed, and whether they passed with flying colours or failed miserably.
                //Going to find the percentage by which the constraint failed or passed, and adjust both the priority and dose constraint based on this.
                updateLog.Add(OptObjectivesEditing.UpdateConstraints(ref plan, ref ss, ref hnPlan, context, optimizedStructures, matchingStructures, numCycles));
                if (features[0].Item1 == true)
                {
                    Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, features[0].Item2[0]);
                }
            }
            numCycles = 4;
            oov       = new OptimizationOptionsVMAT(numCycles, mlcID);
            //Now for a maximum of 3 tries, perform 4-cycle vmat optimization followed by constraint updating until a plan is passed
            for (int i = 0; i < 3; i++)
            {
                plan.OptimizeVMAT(oov);
                plan.CalculateDose();
                updateLog.Add(OptObjectivesEditing.UpdateConstraints(ref plan, ref ss, ref hnPlan, context, optimizedStructures, matchingStructures, numCycles));
                if (features[0].Item1 == true)
                {
                    Segmentation.MakeParotidStructures(choppedContours, planes, ref plan, ref ss, hnPlan, context, matchingStructures, contraName, features[0].Item2[0]);
                }
                isPassed = Check.EvaluatePlan(context, hnPlan, matchingStructures, optimizedStructures).Item1;
                if (isPassed)
                {
                    break;
                }
            }


            return(Tuple.Create(isPassed, updateLog));
        }
コード例 #58
0
 private void frmAddVariable_FormClosing(object sender, FormClosingEventArgs e)
 {
     ScriptContext.RemoveIntellisenseControls(Controls);
 }
コード例 #59
0
ファイル: CLR.cs プロジェクト: xmaxmex/Phalanger
 public Worker(ScriptContext /*!*/ context, object[] args)
 {
     this.context = context;
     this.args    = args;
 }
コード例 #60
0
 public virtual object getIterator(ScriptContext context)
 {
     throw new NotImplementedException();
 }