Пример #1
0
        public void CallNCScript()
        {
            ScriptParser parser = new ScriptParser();

            parser.Types.AddType <Script>();
            IScript ncscript = parser.Parse("parameter($data, script) return($data.name)");

            Mock <IScriptCompiler> scriptcompiler = new Mock <IScriptCompiler>();

            scriptcompiler.Setup(s => s.CompileScriptAsync(It.IsAny <string>(), It.IsAny <int?>())).ReturnsAsync(new CompiledScript {
                Instance = ncscript
            });

            Mock <IScriptImportService> importservice = new Mock <IScriptImportService>();

            importservice.Setup(s => s.Script(It.IsAny <string>(), It.IsAny <int?>())).Returns(new ScriptExecutor(new WorkableLogger(new NullLogger <JavascriptTests>(), null), scriptcompiler.Object, "Test", 1));
            importservice.Setup(s => s.Clone(It.IsAny <WorkableLogger>())).Returns(() => importservice.Object);

            PythonService pythonservice = new PythonService(importservice.Object, null);
            PythonScript  script        = new PythonScript(pythonservice, "script=load.Script('Test', None)\nscript.Execute({'data':{'Name':'Test'}})");

            Assert.AreEqual("Test", script.Execute(new Dictionary <string, object> {
                ["log"] = null
            }));
        }
        public static PRUdpPacket Decode(byte[] bytes)
        {
            var    hex = bytes.ToHex();
            var    str = hex.Substring(4, 2);
            string sessionid = "", sig = "", seqnum = "", connsig = "", fragid = "", payload = "";
            var    typenflags = str.FromHexToBits();
            var    checksum   = hex.Substring(hex.Length - 8);

            int[] data = new int[typenflags.Count];
            for (int i = 0; i < typenflags.Count; i++)
            {
                if ((bool)typenflags[i])
                {
                    data[i] = 1;
                }
                else
                {
                    data[i] = 0;
                }
            }
            var flags  = Convert.ToString(data[0]) + Convert.ToString(data[1]) + Convert.ToString(data[2]) + Convert.ToString(data[3]) + Convert.ToString(data[4]);
            var type   = Convert.ToString(data[5]) + Convert.ToString(data[6]) + Convert.ToString(data[7]);
            var packet = new PRUdpPacket();

            packet.Type  = (PacketTypes)Convert.ToInt32(type, 2);
            packet.Flags = PFlags.ParseFlags(flags);
            if (packet.Type == PacketTypes.SYN || packet.Type == PacketTypes.CONNECT)
            {
                sessionid = hex.Substring(6, 2);
                sig       = hex.Substring(8, 8);
                seqnum    = hex.Substring(16, 4);
                connsig   = hex.Substring(20, 8);

                /*var f = connsig.Substring(0, 2);
                 * var ff = connsig.Substring(2, 2);
                 * var fff = connsig.Substring(4, 2);
                 * var ffff = connsig.Substring(6, 2);
                 * connsig = ffff + fff + ff + f;*/
            }
            else if (packet.Type == PacketTypes.DATA)
            {
                sessionid         = hex.Substring(6, 2);
                sig               = hex.Substring(8, 8);
                seqnum            = hex.Substring(16, 4);
                fragid            = hex.Substring(20, 2);
                payload           = PythonScript.DecompressPacketPayload(RC4.Decrypt(Encoding.ASCII.GetBytes("CD&ML"), hex.Substring(22, hex.Length - 30).FromHex()).ToHex().Substring(2)).Result;
                packet.RMCPayload = RMCPayload.Decode(payload);
            }
            else
            {
                sessionid = hex.Substring(6, 2);
                seqnum    = hex.Substring(8, 4);
            }
            packet.SessionId           = sessionid;
            packet.Signature           = sig;
            packet.Checksum            = checksum;
            packet.ConnectionSignature = connsig;
            packet.Payload             = payload;
            return(packet);
        }
Пример #3
0
        public void TypeConversion()
        {
            Mock <IConfigurationSection> typeconfig = new Mock <IConfigurationSection>();

            typeconfig.SetupGet(s => s.Key).Returns("NamedCode");
            typeconfig.SetupGet(s => s.Value).Returns("ScriptService.Dto.NamedCode,ScriptService");

            Mock <IConfigurationSection> typesconfig = new Mock <IConfigurationSection>();

            typesconfig.Setup(s => s.GetChildren()).Returns(new[] { typeconfig.Object });

            Mock <IConfiguration> config = new Mock <IConfiguration>();

            config.Setup(s => s.GetSection("Types")).Returns(typesconfig.Object);

            TypeCreator   creator       = new TypeCreator(new NullLogger <TypeCreator>(), config.Object);
            PythonService pythonservice = new PythonService(new Mock <IScriptImportService>().Object, creator);

            PythonScript script = new PythonScript(pythonservice, "import NamedCode\ncode=NamedCode()\ncode.Name='Test'\ntest.TestMethod(code)");

            Assert.AreEqual("Test", script.Execute(new Dictionary <string, object> {
                ["log"]  = new WorkableLogger(new NullLogger <JavascriptTests>(), null),
                ["test"] = this
            }));
        }
    internal string ConvertScript(PythonScript script, Dictionary <string, PythonScript> modules)
    {
        _modules = modules;

        var ast = script.AST;

        if (!(ast.Body is SuiteStatement suiteStatement))
        {
            throw new ArgumentException(
                      $"Expected {script.Filename} to parse into a SuiteStatement, but got: {ast.Body}");
        }

        _currentLine = suiteStatement.Start.Line;

        var declarations   = new StringBuilder();
        var declaredFields = new Dictionary <string, GuessedType>();

        // This will pre-discover which functions are condition callbacks to infer their arguments
        if (script.Type == ScriptType.TemplePlusCondition)
        {
            var condFinder = new ConditionCallbackFinder();
            suiteStatement.Walk(condFinder);
            script.ConditionCallbacks = condFinder.CallbackFunctions;
        }

        HandleTopLevelStatement(script, suiteStatement, declarations, declaredFields);

        return(CreateScriptFile(declarations.ToString(), script));
    }
Пример #5
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool S = false;

            DA.GetData(0, ref S);
            PythonScript script = PythonScript.Create();

            script.SetVariable("bakeornot", S ? 1 : 0);
            script.ExecuteScript("import scriptcontext as sc\nsc.sticky['NOAH_BAKE_INFO'] = bakeornot");
            foreach (IGH_DocumentObject obj in ghDoc.Objects)
            {
                if (obj is GH_Cluster)
                {
                    GH_Cluster  objCluster = (GH_Cluster)obj;
                    GH_Document clusterDoc = objCluster.Document("");
                    foreach (IGH_DocumentObject clusterObj in clusterDoc.Objects)
                    {
                        if (clusterObj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9"))
                        {
                            clusterObj.ExpireSolution(true);
                        }
                    }
                    obj.ExpireSolution(true);
                }
                else
                {
                    if (obj.ComponentGuid == new Guid("79EF4718-2B5A-4BFF-AB97-76A036598DB9"))
                    {
                        obj.ExpireSolution(true);
                    }
                }
            }
        }
Пример #6
0
        public void Export(IAssetExportEnvironment env)
        {
            PythonScript input      = env.Input as PythonScript;
            string       outputPath = env.AddOutputPath(input.Name + SourceFileExtPrimary);

            SaveScriptData(input.Content, outputPath);
        }
        protected override void Initialize()
        {
            base.Initialize();

            if (Doc != null)
            {
                Doc.SolutionEnd += OnDocSolutionEnd;
            }

            m_py = PythonScript.Create();
            if (m_py != null)
            {
                SetScriptTransientGlobals();
                m_py.Output = m_py_output.Write;
                m_py.SetVariable("__name__", "__main__");
                m_env = new PythonEnvironment(this, m_py);

                m_py.SetVariable(PARENT_ENVIRONMENT_NAME, m_env);
                m_py.SetIntellisenseVariable(PARENT_ENVIRONMENT_NAME, m_env);

                m_py.ContextId = 2;                                      // 2 is Grasshopper

                m_env.LoadAssembly(typeof(GH_Component).Assembly);       //add Grasshopper.dll reference
                m_env.LoadAssembly(typeof(ZuiPythonComponent).Assembly); //add GHPython.dll reference

                UnpackScriptResources();

                m_env.AddGhPythonPackage();
            }
        }
Пример #8
0
        public static void TestPPDeepScript2()
        {
            string filename = @"..\..\..\..\ProjectTestFiles\Quiz-week06.docx";
            string msghash  = "384:dXOa+qC78kbdvxvga7C5wgbzDdlHAuZLz:Ih8kB9gKC5FthAGz";
            string outhash  = PythonScript.PPDeepHash(filename).Trim();

            Assert.AreEqual(msghash, outhash);
        }
Пример #9
0
        public static void TestPPDeepScript()
        {
            string filename = @"..\..\..\..\ProjectTestFiles\Microsoftsuiteguidance.doc";
            string msghash  = "192:81TH/p5Q+YUrfClLZaAE6/6rNavrgYjk+4bWlLLdPD1l:81THvQpqiSwvxjk+tLLdL";
            string outhash  = PythonScript.PPDeepHash(filename).Trim();

            Assert.AreEqual(msghash, outhash);
        }
Пример #10
0
        public static void ExecutePythonScriptDirty(string sampleFile)
        {
            string pythonFile = @"C:\Users\Derek\source\pyrepo\YaraPlay.py";
            string pythonArgs = "-f " + sampleFile;
            string output     = PythonScript.ExecutePythonScript(pythonFile, pythonArgs);

            Console.WriteLine(output);
        }
Пример #11
0
        public void AwaitTask()
        {
            PythonService pythonservice = new PythonService(new Mock <IScriptImportService>().Object, null);
            PythonScript  script        = new PythonScript(pythonservice, "await(test.TestTask())");

            Assert.AreEqual("test", script.Execute(new Dictionary <string, object> {
                ["test"] = this
            }));
        }
Пример #12
0
        public void ReturnConstant()
        {
            PythonService pythonservice = new PythonService(new Mock <IScriptImportService>().Object, null);
            PythonScript  script        = new PythonScript(pythonservice, "7");

            Assert.AreEqual(7, script.Execute(new Dictionary <string, object> {
                ["test"] = this
            }));
        }
Пример #13
0
        public void IntCall()
        {
            PythonService pythonservice = new PythonService(new Mock <IScriptImportService>().Object, null);
            PythonScript  script        = new PythonScript(pythonservice, "test.TestNumber(7)");

            Assert.AreEqual(7, script.Execute(new Dictionary <string, object> {
                ["test"] = this
            }));
        }
Пример #14
0
        internal PythonEnvironment(GH_Component component, PythonScript script)
        {
            Component = component;
            Script    = script;

            if (script != null)
            {
                Type scriptType = script.GetType();

                var scopeField = scriptType.GetField("m_scope");
                if (scopeField != null)
                {
                    LocalScope = scopeField.GetValue(script);
                }

                var intellisenseField = scriptType.GetField("m_intellisense",
                                                            BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                if (intellisenseField != null)
                {
                    Intellisense = intellisenseField.GetValue(script);
                    if (Intellisense != null)
                    {
                        var intellisenseType = Intellisense.GetType();
                        var scopeProperty    = intellisenseType.GetProperty("Scope");
                        IntellisenseScope = scopeProperty.GetValue(Intellisense, null);
                    }
                }

                var baseType = scriptType.BaseType;
                if (baseType != null && baseType != typeof(object))
                {
                    var hostType = baseType.Assembly.GetType("RhinoPython.Host");
                    if (hostType != null)
                    {
                        var engineInfo = hostType.GetProperty("Engine");
                        if (engineInfo != null)
                        {
                            Engine = engineInfo.GetValue(null, null);

                            if (Engine != null)
                            {
                                var runtimeInfo = Engine.GetType().GetProperty("Runtime");
                                Runtime = runtimeInfo.GetValue(Engine, null);
                            }
                        }

                        var scopeInfo = hostType.GetProperty("Scope", BindingFlags.NonPublic |
                                                             BindingFlags.GetProperty |
                                                             BindingFlags.Static);
                        if (scopeInfo != null)
                        {
                            ScriptScope = scopeInfo.GetValue(null, null);
                        }
                    }
                }
            }
        }
Пример #15
0
        public static void ExecutePythonScriptNoMatches(string sampleFile)
        {
            string pythonFile = @"..\..\..\..\PythonScripts\yara_script.py";
            string pythonArgs = "-f " + sampleFile;
            string foutput    = PythonScript.ExecutePythonScript(pythonFile, pythonArgs).Replace("\r", "");
            string doutput    = "\tScanning file: " + sampleFile.Replace("\"", "") + "\n\tNo matches.\n";

            Console.WriteLine(foutput);
            Assert.AreEqual(doutput, foutput);
        }
Пример #16
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string str = "";
            object obj = null;

            DA.GetData <string>(0, ref str);
            DA.GetData <object>(1, ref obj);
            PythonScript val = PythonScript.Create();

            val.SetVariable("V", obj);
            val.ExecuteScript("import scriptcontext as sc\nsc.sticky['" + str + "'] = V");
        }
Пример #17
0
        public static void ExecutePythonScriptTestBadPaths(string sampleFile)
        {
            string pythonFile = @"..\..\..\..\PythonScripts\yara_script.py";
            //string sampleFile = "\"C:\\Users\\Derek\\OneDrive\\Documents\\CSC205\\ProjectTestFiles\\COVID-19 Precautions.txt\"";
            //Note filenames with spaces must be encapsulated sufficienctly
            //string sampleFile = "\""+@"..\..\..\..\ProjectTestFiles\COVID-19 Precautions.txt" +"\"";
            string pythonArgs = "-f " + sampleFile;
            string foutput    = PythonScript.ExecutePythonScript(pythonFile, pythonArgs).Replace("\r", "");
            string doutput    = "\tScanning file: " + sampleFile.Replace("\"", "") + "\n\tError scanning file.\n";

            Console.WriteLine(foutput);
            Assert.AreEqual(doutput, foutput);
        }
Пример #18
0
        public void LoadData(PythonScript data)
        {
            if (DesignMode)
            {
                return;
            }

            Script             = data;
            pythonTextbox.Text = Script.Text;

            ScriptLoaded?.Invoke(this, EventArgs.Empty);

            Trace.Listeners.Add(new OutputTraceListener(outputTextBox));
        }
        public byte[] Encode()
        {
            var packet = "313f";
            var s      = Convert.ToString((int)Type, 2);

            if (s.Length != 3)
            {
                s = s.PadLeft(3 - s.Length + 1, '0');
            }
            var iii = 0;

            foreach (var fl in Flags)
            {
                iii += (int)fl;
            }
            var s1 = Convert.ToString(iii, 2);

            if (s1.Length != 5)
            {
                s1 = s1.PadLeft(5 - s1.Length + 1, '0');
            }
            var typenflags = s1 + s;

            int[] bits = typenflags.PadLeft(8, '0').Select(c => int.Parse(c.ToString())).ToArray();
            var   b    = bits.ToBitArray().ToHex();

            packet += b;    //type and flags
            packet += "00"; //sessionid
            if (Type != PacketTypes.DATA)
            {
                packet += ConnectionSignature; //connection signature
            }
            else
            {
                packet += "5790aecd"; //cdae9057
            }
            packet += "00";           // "db44870f";
            packet += "0001";         //packet number
            //packet += ConnectionSignature; //encrypted empty payload, static//my head hurts....
            packet += "db44870f";
            if (!string.IsNullOrEmpty(Payload))
            {
                packet += "00";
                Payload = PythonScript.CompressPacketPayload(RC4.Encrypt(Encoding.ASCII.GetBytes("CD&ML"), Payload.FromHex()).ToHex()).Result;
                packet += "02";
            }
            packet += Payload;
            packet += CalculateChecksum(packet); //calculate checksum to append at the end
            return(packet.FromHex());
        }
Пример #20
0
        public static void Main()
        {
            PythonScript Python = Subprocess;

            try {
                string pyProc0 = Python("test_args.py", "2 3 4 5 cat");
                Console.WriteLine($"pyProc0: {pyProc0}");
                dynamic pyProc1 = Python("antigravityTurtle.py", "");
                Console.WriteLine($"pyProc1: {pyProc1}");
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
Пример #21
0
 public void ExecuteScript()
 {
     try
     {
         var script = new PythonScript(GetCodeToExecute());
         script.ExecuteScript();
         var pi = PythonInterpreter.Instance;
         Trace.Write(pi.GetOutput());
     }
     catch (Exception exc)
     {
         Trace.TraceWarning(exc.Message);
         return;
     }
 }
Пример #22
0
        public DrawEffect(string script_path, dynamic param)
        {
            draw   = new DrawEffectScriptConector();
            effect = new BattleMapEffectScriptConector.Effect(new ScriptManager(script_path));
            status = new ActionStatusScriptConector(this);

            python_script = new PythonScript(script_path,
                                             (s) => {
                s.SetVariable("param", param);
                s.SetVariable("draw", draw);
                s.SetVariable("effect", effect);
                s.SetVariable("status", status);
            }
                                             );
        }
Пример #23
0
        public IEnumerable <IModObject> Load(Mod mod)
        {
            // TODO - should scripts be mod objects?
            {
                var    name = "builtins";
                string filename;
                string stockFilename = filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Scripts", name);
                if (ModPath == null)
                {
                    filename = stockFilename;
                }
                else
                {
                    filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Mods", ModPath, "Scripts", name);
                }
                mod.GlobalScript = PythonScript.Load(filename) ?? PythonScript.Load(stockFilename) ?? new PythonScript(name, "");
            }
            {
                var    name = "GameInit";
                string filename;
                string stockFilename = filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Scripts", name);
                if (ModPath == null)
                {
                    filename = stockFilename;
                }
                else
                {
                    filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Mods", ModPath, "Scripts", name);
                }
                mod.GameInitScript = PythonScript.Load(filename) ?? PythonScript.Load(stockFilename) ?? new PythonScript(name, "");
            }
            {
                var    name = "EndTurn";
                string filename;
                string stockFilename = filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Scripts", name);
                if (ModPath == null)
                {
                    filename = stockFilename;
                }
                else
                {
                    filename = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Mods", ModPath, "Scripts", name);
                }
                mod.EndTurnScript = PythonScript.Load(filename) ?? PythonScript.Load(stockFilename) ?? new PythonScript(name, "");
            }

            yield break;
        }
Пример #24
0
        Unit target_unit = null; // 対象ユニット

        public BattleMapEffectScriptConector(string script_path, bool is_hit, int effect_value, Unit action_unit, Unit target_unit)
        {
            var script_manager = new ScriptManager(script_path);

            effect = new Effect(script_manager);
            action = new Action();

            python_script = new PythonScript(script_path);
            python_script.SetVariable("effect", effect);
            python_script.SetVariable("action", action);

            this.is_hit       = is_hit;
            this.effect_value = effect_value;
            this.action_unit  = action_unit;
            this.target_unit  = target_unit;
        }
Пример #25
0
        public MainWindow()
        {
            InitializeComponent();

            // Subscribe to status update events
            ((App)Application.Current).OnStatusUpdate += OnStatusUpdate;

            // Find Unity paths
            var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            txtUnityPath.Text       = Utils.FindPath($@"{programFiles}\Unity\Hub\Editor\*") ?? "<not set>";
            txtUnityScriptPath.Text = Utils.FindPath($@"{programFiles}\Unity\Hub\Editor\*\Editor\Data\Resources\PackageManager\ProjectTemplates\libcache\com.unity.template.3d-*\ScriptAssemblies") ?? "<not set>";

            // Populate script target combo box and select IDA by default
            cboPyTarget.ItemsSource  = PythonScript.GetAvailableTargets();
            cboPyTarget.SelectedItem = (cboPyTarget.ItemsSource as IEnumerable <string>).First(x => x == "IDA");
        }
Пример #26
0
        public void Import(IAssetImportEnvironment env)
        {
            foreach (AssetImportInput input in env.Input)
            {
                ContentRef <PythonScript> targetRef = env.GetOutput <PythonScript>(input.AssetName);

                if (targetRef.IsAvailable)
                {
                    PythonScript target = targetRef.Res;

                    string fileData = File.ReadAllText(input.Path);
                    target.UpdateContent(fileData);

                    env.AddOutput(targetRef, input.Path);
                }
            }
        }
    public string ConvertSnippet(string snippet,
                                 PythonScript withinScript = null,
                                 Dictionary <string, GuessedType> context = null)
    {
        var ast = ParseSnippet(snippet);

        var script = new PythonScript(withinScript?.Filename ?? "snippet", snippet, ast);

        var expressionConverter = new ExpressionConverter(script, _typings, _modules);

        if (context != null)
        {
            expressionConverter.AddVariables(context);
        }

        ast.Body.Walk(expressionConverter);
        return(expressionConverter.Result.ToString());
    }
Пример #28
0
        public void PythonScript_OnCompleted_works()
        {
            string               text    = @"
from SharpETL.Components import Element
def OnCompleted(a):
  yield Element(a.Id, a.Id, [])
";
            PythonScript         script  = new PythonScript("script", text, _pythonEngine);
            Mock <IScriptAction> maction = new Mock <IScriptAction>();

            maction.Setup(x => x.Id).Returns("ok");
            var result  = script.OnCompleted(maction.Object);
            var element = result.FirstOrDefault();

            Assert.IsNotNull(element);
            Assert.AreEqual("ok", element.Id);
            Assert.AreEqual("ok", element.Name);
        }
Пример #29
0
        public void PythonScript_OnError_OnFinally_works()
        {
            string               text    = @"
from SharpETL.Components import Element
def OnError(a, ex):
    yield Element(ex.Message, ex.Message, [])
def OnFinally(a):
    pass
";
            PythonScript         script  = new PythonScript("script", text, _pythonEngine);
            Mock <IScriptAction> maction = new Mock <IScriptAction>();
            var result  = script.OnError(maction.Object, new Exception("error"));
            var element = result.FirstOrDefault();

            Assert.IsNotNull(element);
            Assert.AreEqual("error", element.Id);
            Assert.AreEqual("error", element.Name);
            script.OnFinally(maction.Object);
        }
Пример #30
0
        public void PythonScript_OnElement_works()
        {
            string               text     = @"
from SharpETL.Components import Element
def OnElement(a, e):
  yield Element(e.Id, e.Id, [])";
            string               testeid  = "TestOK_OnElement";
            PythonScript         script   = new PythonScript("script", text, _pythonEngine);
            Mock <IScriptAction> maction  = new Mock <IScriptAction>();
            Mock <IElement>      melement = new Mock <IElement>();

            melement.Setup(x => x.Id).Returns(testeid);
            var result = script.OnElement(maction.Object, melement.Object);

            foreach (IElement e in result)
            {
                Assert.AreEqual(testeid, e.Name);
                Assert.AreEqual(testeid, e.Id);
            }
        }