Example #1
0
        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            if (ViewModelBase.IsInDesignModeStatic)
            {
                // SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
            }
            else
            {
                // SimpleIoc.Default.Register<IDataService, DataService>();
            }

            SimpleIoc.Default.Register <IMessageDialog>(() => new MessageDialog(Application.Current.MainWindow));

            // https://mail.python.org/pipermail/ironpython-users/2013-January/016388.html
            var options = new Dictionary <string, object>();

            options["Frames"]     = true;
            options["FullFrames"] = true;
            var py = Python.CreateRuntime(options);

            dynamic sys = py.GetSysModule();

            sys.path.append(@"C:\Program Files (x86)\IronPython 2.7");
            sys.path.append(@"C:\Program Files (x86)\IronPython 2.7\DLLs");
            sys.path.append(@"C:\Program Files (x86)\IronPython 2.7\Lib");
            sys.path.append(@"C:\Program Files (x86)\IronPython 2.7\Lib\site-packages");

            SimpleIoc.Default.Register <IPythonWrapper>(() => new PythonWrapper(py, @"pythons\Python.py"));
            SimpleIoc.Default.Register <IMainViewModel, MainViewModel>();
        }
Example #2
0
        void encryptFileName()
        {
            FileStream   fp2 = new FileStream("temp_data.txt", FileMode.Create);
            StreamWriter wp  = new StreamWriter(fp2);

            for (int i = 0; i < 32; i++)
            {
                wp.WriteLine(keyArray[i]);
            }
            Regex  reExp = new Regex(@"\\{1}[^\\]+$", RegexOptions.RightToLeft);
            string title = reExp.Match(textBox_input.Text).ToString();

            title = title.Remove(0, 1);
            wp.WriteLine(title.Length);
            while (title != "")
            {
                while (title != "")
                {
                    wp.WriteLine(char.ConvertToUtf32(title, 0));
                    title = title.Remove(0, 1);
                }
            }
            wp.Close();
            fp2.Close();
            ScriptRuntime pyRumTime = Python.CreateRuntime();
            dynamic       obj       = pyRumTime.UseFile("rsa.py");

            obj.ras_pub(textBox_pub.Text, "temp_data.txt", outPath + ".txt");
            File.Delete("temp_data.txt");
        }
Example #3
0
        public PythonEngine(ContentManager content)
        {
            ScriptRuntime runtime = Python.CreateRuntime(new Dictionary <string, object>
            {
#if DEBUG
                { "Debug", true },
#endif
            });
            var interopClasses = new[]
            {
                typeof(BaseEntity),
                typeof(Microsoft.Xna.Framework.Graphics.Texture2D),
                typeof(Jv.Games.Xna.Sprites.Sprite),
            };

            foreach (var interopType in interopClasses)
            {
                runtime.LoadAssembly(Assembly.GetAssembly(interopType));
            }

            Engine = runtime.GetEngine("py");
            var paths = Engine.GetSearchPaths();

            paths.Add("PlayerScripts");
            paths.Add(Path.Combine(content.RootDirectory, "Scripts"));
            paths.Add(Path.Combine(content.RootDirectory, "Scripts/Entities"));
            Engine.SetSearchPaths(paths);
        }
Example #4
0
        /// <summary>
        /// ItemCF推荐
        /// 给用户id为user_id的用户推荐电影
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static ArrayList recommendItemCF(int user_id)
        {
            string        serverpath = pyScriptPath + "ItemCFRecommend.py";
            ScriptRuntime pyRuntime  = Python.CreateRuntime();
            ScriptEngine  Engine     = pyRuntime.GetEngine("python");

            ICollection <string> Paths = Engine.GetSearchPaths();

            Paths.Add("D:\\Anaconda2-32\\Lib");
            Paths.Add("D:\\Anaconda2-32\\DLLs");
            Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages");

            Engine.SetSearchPaths(Paths);

            ScriptScope pyScope = Engine.CreateScope();

            dynamic pyScript = Engine.ExecuteFile(serverpath, pyScope);

            IronPython.Runtime.List user_item_list = getUserLikeItem(user_id);

            PythonDictionary similar_matrix = getItemSimilarityMatrix(user_item_list);


            IronPython.Runtime.List result = pyScript.recommend_item_cf(user_item_list, similar_matrix, 3);

            return(getRecommendMovie(result));
        }
        static public void Run()
        {
            var     pythonRT   = Python.CreateRuntime();
            dynamic pythonFile = pythonRT.UseFile(@"C:\Users\rober\source\repos\DynamicLessons\DynamicLessons\Fight.py");

            pythonFile.run();
        }
Example #6
0
        public ScriptManager(string scriptsDir, string pythonLibsDir)
        {
            _scripts = new Dictionary <string, Script>();

            ScriptRuntime runtime = Python.CreateRuntime();

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                runtime.LoadAssembly(assembly);
            }

            _scriptEngine = runtime.GetEngine("py");
            var paths = _scriptEngine.GetSearchPaths();

            if (!string.IsNullOrEmpty(scriptsDir))
            {
                paths.Add(scriptsDir);
            }

            if (!string.IsNullOrEmpty(pythonLibsDir))
            {
                paths.Add(pythonLibsDir);
            }

            _scriptEngine.SetSearchPaths(paths);
        }
Example #7
0
        private void loadPythonModules(string path)
        {
            if (path.Length == 0)
            {
                throw new Exception("You must set a valid python path.");
            }

            if (Directory.Exists(path) == false)
            {
                throw new Exception(string.Format("{0} path does not exist.", path));
            }

            if (File.Exists(Path.Combine(path, "python.exe")) == false)
            {
                throw new Exception(string.Format("Cannot find python.exe file in {0}.", path));
            }

            if (this.pythonRuntime != null)
            {
                this.pythonRuntime.Shutdown();
            }

            this.pythonRuntime = Python.CreateRuntime();
            var engine = this.pythonRuntime.GetEngine("IronPython");
            var paths  = engine.GetSearchPaths();

            paths.Add(path);
            paths.Add(Path.Combine(path, "DLLs"));
            paths.Add(Path.Combine(path, "lib"));
            paths.Add(Path.Combine(path, "lib\\site-packages"));
            paths.Add(Path.Combine(Directory.GetCurrentDirectory(), "scripts"));
            engine.SetSearchPaths(paths);
        }
Example #8
0
        static void Main(string[] args)
        {
            //<Snippet2>
            // Set the current directory to the IronPython libraries.
            System.IO.Directory.SetCurrentDirectory(
                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) +
                @"\IronPython 2.6 for .NET 4.0\Lib");

            // Create an instance of the random.py IronPython library.
            Console.WriteLine("Loading random.py");
            ScriptRuntime py     = Python.CreateRuntime();
            dynamic       random = py.UseFile("random.py");

            Console.WriteLine("random.py loaded.");
            //</Snippet2>

            //<Snippet3>
            // Initialize an enumerable set of integers.
            int[] items = Enumerable.Range(1, 7).ToArray();

            // Randomly shuffle the array of integers by using IronPython.
            for (int i = 0; i < 5; i++)
            {
                random.shuffle(items);
                foreach (int item in items)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine("-------------------");
            }
            //</Snippet3>
        }
Example #9
0
 public Engine()
 {
     // Load a script with all the utility functions that are required
     // pe.ExecuteFile(InputTestDirectory + "\\EngineTests.py");
     _env = Python.CreateRuntime();
     _pe  = _env.GetEngine("py");
 }
Example #10
0
        public Highlighter()
        {
            if (_highlight == null)
            {
                var     ipy = Python.CreateRuntime();
                dynamic clr = ipy.GetClrModule();
                clr.AddReference("pygments");

                _lexers = ipy.Import("pygments.lexers").lexers;
                Lexers  = ((IEnumerable)_lexers.get_all_lexers()).Cast <object>().Select(each => {
                    dynamic e = each;
                    return(new Lexer {
                        Name = e[0],
                        Aliases = ((IEnumerable <object>)(e[1])).Select(i => i.ToString()).ToArray(),
                        Filemasks = ((IEnumerable <object>)(e[2])).Select(i => i.ToString()).ToArray(),
                        MediaTypes = ((IEnumerable <object>)(e[3])).Select(i => i.ToString()).ToArray(),
                    });
                }).ToArray();

                _styles = ipy.Import("pygments.styles").styles;
                Styles  =
                    ((IEnumerable)_styles.get_all_styles()).Cast <object>().Select(each => each.ToString()).ToArray();

                _highlight  = ipy.Import("pygments").highlight;
                _formatters = ipy.Import("pygments.formatters").formatters;
            }
        }
        private void InitIronPython()
        {
            if (m_engine == null)
            {
                //s_engine = Python.CreateEngine();
                //s_runtime = s_engine.Runtime;
                // s_scope = s_engine.CreateScope();

                m_runtime = Python.CreateRuntime();
                m_runtime.LoadAssembly(typeof(String).Assembly);
                //runtime.LoadAssembly(typeof(Uri).Assembly);

                // no module name System
                //m_runtime.ImportModule("System");

                m_scope = m_runtime.CreateScope();

                m_engine = Python.GetEngine(m_runtime);

                ICollection <string> paths = m_engine.GetSearchPaths();
                foreach (string s in s_pythonLibPath)
                {
                    paths.Add(s);
                }
                m_engine.SetSearchPaths(paths);
            }
        }
Example #12
0
        public PythonHelper()
        {
            engine = Python.CreateEngine();
            ScriptRuntime pyRunTime = Python.CreateRuntime();

            scope = pyRunTime.UseFile("hello.py");
        }
Example #13
0
        public double risk(double lng, double lat, AirCondition airCondition)
        {
            CoorTransferer coorTransferer = new CoorTransferer(20);

            double[] coor = coorTransferer.Nautica2xy(lng, lat);

            PollutedPoint pollutedPoint = new PollutedPoint((int)coor[0], (int)coor[1]);

            foreach (PollutionSource pollutionSource in this.PollutionSources)
            {
                double sourceLng = pollutionSource.X;
                double sourceLat = pollutionSource.Y;

                double[] source = coorTransferer.Nautica2xy(sourceLng, sourceLat);

                pollutionSource.X = source[0];
                pollutionSource.Y = source[1];

                // 加载外部 python 脚本文件.
                ScriptRuntime pyRumTime = Python.CreateRuntime();
                dynamic       obj       = pyRumTime.UseFile("t.py");
                obj.GetArbitraryC(pollutedPoint, airCondition, pollutionSource);    // python脚本计算污染点的浓度值,并将计算结果返回给对象的污染物浓度属性

                // 使用后还原
                pollutionSource.X = sourceLng;
                pollutionSource.Y = sourceLat;
            }

            return(pollutedPoint.Concentration);
        }
Example #14
0
        public int test(int a, int b)
        {
            var py  = Python.CreateEngine();
            var ipy = Python.CreateRuntime();

            try
            {
                //py.ExecuteFile("test.py");
                // dynamic q = ipy.UseFile("test.py");

                ScriptEngine engine = Python.CreateEngine();
                ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
                ScriptScope  scope  = engine.CreateScope();
                source.Execute(scope);

                dynamic Calculator = scope.GetVariable("Calculator");
                dynamic calc       = Calculator();
                int     result     = calc.add(a, b);

                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    "Oops! We couldn't execute the script because of an exception: " + ex.Message);
            }
            return(0);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            ScriptRuntime pyRuntime = Python.CreateRuntime();
            dynamic       obj       = pyRuntime.UseFile(@"recommend.py");

            IronPython.Runtime.List mustlst = new IronPython.Runtime.List();
            IronPython.Runtime.List wantlst = new IronPython.Runtime.List();

            foreach (int i in index_must)
            {
                mustlst.Add(i);
            }
            foreach (int i in index_want)
            {
                wantlst.Add(i);
            }

            string result = obj.getPeople(mustlst, wantlst);

            purl  = obj.getUrl(mustlst, wantlst);
            pname = result;
            MessageBox.Show("为你推荐:" + pname);

            People infofr = new People(pname, purl);

            infofr.Show();
        }
Example #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            DateTime temtime = DateTime.Now;

            try
            {
                string        pypathstr = "";
                string        pyfilestr = "";
                ScriptRuntime pyRunTime = Python.CreateRuntime();
                pypathstr = AppContext.BaseDirectory;
                //pypathstr = "E:\\mysoft\\202003test\\ServerMonitor\\ServerMonitor\\pythonfiles\\";
                pyfilestr = "pythonfiles\\digital1.py";
                dynamic obj = pyRunTime.UseFile(pypathstr + pyfilestr);
                //dynamic obj = pyRunTime.UseFile("digital1.py");
                int int1 = 0, int2 = 0;
                int1 = int.Parse(text_data1.Text);
                int2 = int.Parse(text_data2.Text);
                int val = obj.sum(int1, int2);

                label_result1.Text = val.ToString();
                //MessageBox.Show(val + "");
            }
            catch (Exception ex)
            {
                ClassLog.Writelog(temtime.ToString(), "ServerManger.python1", " .button1_Click()  调用python计算 " + ex.ToString());
                Debug.Print(ex.ToString());
            }
        }
Example #17
0
        static void Main(string[] args)
        {
            var     ipy        = Python.CreateRuntime();
            dynamic pythonFile = ipy.UseFile("test.py");

            // Passing data into a Python function
            object[] data =
            {
                "String 1",
                100,
                true,
                10.03,
                'c'
            };
            pythonFile.call(data);

            // Retrieving data from a getter function
            Console.WriteLine();
            string name = pythonFile.getName();

            Console.WriteLine(name);


            // Passing user-inputed data to a Python function
            Console.WriteLine();
            string msg = Console.ReadLine();

            Console.WriteLine(pythonFile.printMsg(msg));

            // Squaring number
            Console.WriteLine();
            Console.WriteLine(pythonFile.squareNum(100));
        }
Example #18
0
    static void Main()
    {
        var     ipy  = Python.CreateRuntime();
        dynamic test = ipy.UseFile("Test.py");

        test.Simple();
    }
Example #19
0
 private void button7_Click(object sender, EventArgs e)
 {
     if (textBox3.Text != "" && textBox11.Text != "" && textBox5.Text != "")
     {
         if (isdigit(textBox3) && isdigit(textBox11) && isdigit(textBox5))
         {
             if (textBox4.Text.Length - 1 >= textBox11.Text.Length)
             {
                 ScriptRuntime pyRumTime = Python.CreateRuntime();
                 dynamic       obj       = pyRumTime.UseFile("rsa.py");
                 textBox12.Text = obj.demo_cal(textBox11.Text, textBox5.Text, textBox3.Text);
                 textBox11.Text = "";
             }
             else
             {
                 MessageBox.Show("输入数字过长,请输入" + (textBox4.Text.Length - 1).ToString() + "位及" + (textBox4.Text.Length - 1).ToString() + "位以下长度的数字", "提示", MessageBoxButtons.OK);
             }
         }
         else
         {
             isdigit(textBox11);
             isdigit(textBox5);
             MessageBox.Show("亲,非法输入,文本框只能输入数字", "提示", MessageBoxButtons.OK);
         }
     }
 }
Example #20
0
 private void Initilize_Index()
 {
     pyRunTime = Python.CreateRuntime();
     Console.WriteLine();
     obj_Index = pyRunTime.UseFile(@"..//..//PyShell//Global_Index.py");
     //obj_Index = pyRunTime.UseFile(@"..\..\..\PyShell\Global_Index.py");
 }
        private void UpdateScript(string script)
        {
            LogTo.Debug("A script was changed - {0}", script);

            if (File.Exists(script))
            {
                _runtime.Shutdown();
                _runtime = Python.CreateRuntime();
                try
                {
                    _script = _runtime.UseFile(script);
                    LogTo.Info("Script loaded");
                    ScriptScope scope  = _script;
                    dynamic     parser = scope.GetVariable("ParserScript");
                    name    = parser.Name;
                    version = parser.Version;
                    author  = parser.Author;
                    LogTo.Info("Name: {0}, Version: {1}, Author: {2}", name, version, author);
                }
                catch (SyntaxErrorException e)
                {
                    LogTo.ErrorException("Syntax error", e);
                }
                catch (Exception e)
                {
                    LogTo.WarnException("Script error", e);
                }
            }
            else
            {
                LogTo.Error("Script not loaded (file doesn't exist)");
            }
        }
Example #22
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            var     py   = Python.CreateRuntime();
            dynamic test = py.UseFile("stats.py");

            txtStats.Text = test.playerStats();
        }
        public void Create()
        {
            LogTo.Debug("PythonPacketParser created");
            _runtime = Python.CreateRuntime();

            var scriptDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            if (scriptDirectory == null)
            {
                throw new NullReferenceException("ScriptDirectory should not be null");
            }

            LogTo.Debug("Looking for python decoder in {0}", scriptDirectory);
            watcher = new FileSystemWatcher(scriptDirectory, "*.py");

            watcher.Changed            += (sender, args) => UpdateScript(args.FullPath);
            watcher.NotifyFilter        = NotifyFilters.LastWrite | NotifyFilters.FileName;
            watcher.EnableRaisingEvents = true;
            UpdateScript("interpreter.py");

            try
            {
                LogTo.Debug(InterpretPacket((new UTF8Encoding()).GetBytes("Hello from Python")));
            }
            catch (Exception e)
            {
                LogTo.WarnException("Interpreting python script threw an error", e);
            }
        }
Example #24
0
        private void button2_Click(object sender, EventArgs e)
        {
            string        pypathstr = "";
            string        pyfilestr = "";
            ScriptRuntime pyRunTime = Python.CreateRuntime();

            pypathstr = AppContext.BaseDirectory;
            //pypathstr = "E:\\mysoft\\202003test\\ServerMonitor\\ServerMonitor\\pythonfiles\\";
            pyfilestr = "pythonfiles\\digital1.py";
            dynamic      obj      = pyRunTime.UseFile(pypathstr + pyfilestr);
            string       strfind1 = "";
            string       strfind2 = "";
            UTF8Encoding utf8     = new UTF8Encoding();

            strfind1 = textBox1.Text;
            strfind2 = strfind1; // utf8.GetString(encodedBytes);
            strfind2 = StringToUnicode(strfind1);
            Debug.Print(strfind1);
            Debug.Print(strfind2);
            var strArray = obj.regSearch1("e:\\city.txt", strfind2);

            listBox1.Items.Clear();
            foreach (var s in strArray)
            {
                string ss0 = "";
                string ss1 = "";
                ss0 = "\\" + s;
                //Debug.Print(s);
                ss1 = UnicodeToString(ss0);
                listBox1.Items.Add(s);
            }
            int count = listBox1.Items.Count;

            label3.Text = count.ToString();
        }
Example #25
0
        static void Main(string [] args)
        {
            // Set the current directory to the IronPython libraries.
            Directory.SetCurrentDirectory(@"C:\Program Files\IronPython 2.7\Lib");

            // Create an instance of the random.py IronPython Library.
            Console.WriteLine("Loading random.py");
            ScriptRuntime py     = Python.CreateRuntime();
            dynamic       random = py.UseFile("random.py");

            Console.WriteLine("random.py loaded.");

            // Initialize an enumerable set of integers.
            int[] items = Enumerable.Range(1, 7).ToArray();

            // Randomly shuffle the array of integers by using IronPython.
            for (int i = 0; i < 5; i++)
            {
                random.shuffle(items);
                foreach (int item in items)
                {
                    Console.WriteLine(item);
                }
                Console.WriteLine("--------------------");
            }

            Console.WriteLine("Press any key to EXIT...");
            Console.ReadKey();
        }
Example #26
0
        /// <summary>
        /// Выполнить
        /// </summary>
        /// <exception cref="Exception"></exception>
        /// <exception cref="PythonCreateRuntimeException"></exception>
        /// <exception cref="ScriptRuntimeUseFileException"></exception>
        /// <exception cref="ScriptRunMethodException"></exception>
        public void Do()
        {
            DataTable dataTablBefore = GetTableBefore();

            OnSetDataTableBefore(dataTablBefore);

            DataTable dataTableAfter = GetTableAfter();

            ScriptRuntime p;

            try
            {
                p = Python.CreateRuntime();
            }
            catch (Exception e)
            {
                throw new PythonCreateRuntimeException(e);
            }

            dynamic script;

            try
            {
                script = p.UseFile(_pythonFileName);
            }
            catch (Exception e)
            {
                throw new ScriptRuntimeUseFileException(e);
            }

            try
            {
                script.Change(dataTableAfter);
            }
            catch (Exception e)
            {
                throw new ScriptRunMethodException("Change", e);
            }

            int no = 0;

            OnConvertMaximum(dataTableAfter.Rows.Count);
            foreach (DataRow row in dataTableAfter.Rows)
            {
                try
                {
                    script.ToCalculate(no, row);
                }
                catch (Exception e)
                {
                    throw new ScriptRunMethodException("ToCalculate", e);
                }

                ++no;
                OnSetConvertValue(no);
            }

            OnSetDataTableAfter(dataTableAfter);
        }
Example #27
0
        private static dynamic CreateEngynePython(string filepath)
        {
            var py = Python.CreateRuntime();

            dynamic pyrpogram = py.UseFile(filepath);

            return(pyrpogram);
        }
Example #28
0
        static void Main(string[] args)
        {
            ScriptRuntime python = Python.CreateRuntime();
            dynamic       r      = python.UseFile("hello.py");

            Console.WriteLine(r.yreadlines(@"C:\Users\LSQ\Desktop\Mes讨论内容.txt"));
            Console.Read();
        }
Example #29
0
        static void Main(string[] args)
        {
            var pythonRuntime = Python.CreateRuntime();

            dynamic pythonFile = pythonRuntime.UseFile("Test.py");

            pythonFile.SayHelloToPython();
        }
Example #30
0
        private static void Monster_Data(DesignerItem monster, int aiID)
        {
            var     ipy  = Python.CreateRuntime();
            dynamic test = ipy.UseFile("Code\\monster_data.py");

            IronPython.Runtime.PythonDictionary data  = test.data;
            IronPython.Runtime.PythonDictionary unit  = null;
            IronPython.Runtime.PythonTuple      tuple = null;
            List <int> aiIDList = new List <int>();

            aiIDList.Add(aiID);
            int monsterID = -1;

            for (int i = 0; i < monster.outputValue.Count; ++i)
            {
                MyTextBox tempTextBox = monster.outputValue[i];
                if (tempTextBox.Property.Equals("ID"))
                {
                    try { monsterID = Convert.ToInt32(tempTextBox.propertyValue); }
                    catch (Exception e)
                    {
                        var ex = new Exception("缺少怪物ID");
                        throw ex;
                    }
                }
            }
            if (data.ContainsKey(monsterID))
            {
                unit = data[monsterID] as IronPython.Runtime.PythonDictionary;
                if (unit["monsterAI"] != null)
                {
                    tuple = unit["monsterAI"] as IronPython.Runtime.PythonTuple;
                    for (int i = 0; i < tuple.Count; ++i)
                    {
                        int exitAIID = Convert.ToInt32(tuple[i]);
                        if (!aiIDList.Contains(exitAIID))
                        {
                            aiIDList.Add(exitAIID);
                        }
                    }
                }
            }
            else
            {
                unit = new IronPython.Runtime.PythonDictionary();
            }
            unit["monsterAI"] = new IronPython.Runtime.PythonTuple(aiIDList);
            for (int i = 0; i < monster.outputValue.Count; ++i)
            {
                MyTextBox tempTextBox = monster.outputValue[i];
                if (!tempTextBox.Property.Equals(tempTextBox.propertyValue) && tempTextBox.propertyValue != null && !tempTextBox.Property.Equals("ID"))
                {
                    unit[tempTextBox.Property] = tempTextBox.propertyValue;
                }
            }
            data[monsterID] = unit;
            exportCode(data, "monster_data.py");
        }